text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
# Face Recognition for the Happy House
Welcome to the first assignment of week 4! Here you will build a face recognition system. Many of the ideas presented here are from [FaceNet](https://arxiv.org/pdf/1503.03832.pdf). In lecture, we also talked about [DeepFace](https://research.fb.com/wp-content/uploads/2016/11/deepface-closing-the-gap-to-human-level-performance-in-face-verification.pdf).
Face recognition problems commonly fall into two categories:
- **Face Verification** - "is this the claimed person?". For example, at some airports, you can pass through customs by letting a system scan your passport and then verifying that you (the person carrying the passport) are the correct person. A mobile phone that unlocks using your face is also using face verification. This is a 1:1 matching problem.
- **Face Recognition** - "who is this person?". For example, the video lecture showed a face recognition video (https://www.youtube.com/watch?v=wr4rx0Spihs) of Baidu employees entering the office without needing to otherwise identify themselves. This is a 1:K matching problem.
FaceNet learns a neural network that encodes a face image into a vector of 128 numbers. By comparing two such vectors, you can then determine if two pictures are of the same person.
**In this assignment, you will:**
- Implement the triplet loss function
- Use a pretrained model to map face images into 128-dimensional encodings
- Use these encodings to perform face verification and face recognition
In this exercise, we will be using a pre-trained model which represents ConvNet activations using a "channels first" convention, as opposed to the "channels last" convention used in lecture and previous programming assignments. In other words, a batch of images will be of shape $(m, n_C, n_H, n_W)$ instead of $(m, n_H, n_W, n_C)$. Both of these conventions have a reasonable amount of traction among open-source implementations; there isn't a uniform standard yet within the deep learning community.
Let's load the required packages.
```
from keras.models import Sequential
from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate
from keras.models import Model
from keras.layers.normalization import BatchNormalization
from keras.layers.pooling import MaxPooling2D, AveragePooling2D
from keras.layers.merge import Concatenate
from keras.layers.core import Lambda, Flatten, Dense
from keras.initializers import glorot_uniform
from keras.engine.topology import Layer
from keras import backend as K
K.set_image_data_format('channels_first')
import cv2
import os
import numpy as np
from numpy import genfromtxt
import pandas as pd
import tensorflow as tf
from fr_utils import *
from inception_blocks_v2 import *
%matplotlib inline
%load_ext autoreload
%autoreload 2
np.set_printoptions(threshold=np.nan)
```
## 0 - Naive Face Verification
In Face Verification, you're given two images and you have to tell if they are of the same person. The simplest way to do this is to compare the two images pixel-by-pixel. If the distance between the raw images are less than a chosen threshold, it may be the same person!
<img src="images/pixel_comparison.png" style="width:380px;height:150px;">
<caption><center> <u> <font color='purple'> **Figure 1** </u></center></caption>
Of course, this algorithm performs really poorly, since the pixel values change dramatically due to variations in lighting, orientation of the person's face, even minor changes in head position, and so on.
You'll see that rather than using the raw image, you can learn an encoding $f(img)$ so that element-wise comparisons of this encoding gives more accurate judgements as to whether two pictures are of the same person.
## 1 - Encoding face images into a 128-dimensional vector
### 1.1 - Using an ConvNet to compute encodings
The FaceNet model takes a lot of data and a long time to train. So following common practice in applied deep learning settings, let's just load weights that someone else has already trained. The network architecture follows the Inception model from [Szegedy *et al.*](https://arxiv.org/abs/1409.4842). We have provided an inception network implementation. You can look in the file `inception_blocks.py` to see how it is implemented (do so by going to "File->Open..." at the top of the Jupyter notebook).
The key things you need to know are:
- This network uses 96x96 dimensional RGB images as its input. Specifically, inputs a face image (or batch of $m$ face images) as a tensor of shape $(m, n_C, n_H, n_W) = (m, 3, 96, 96)$
- It outputs a matrix of shape $(m, 128)$ that encodes each input face image into a 128-dimensional vector
Run the cell below to create the model for face images.
```
FRmodel = faceRecoModel(input_shape=(3, 96, 96))
print("Total Params:", FRmodel.count_params())
```
** Expected Output **
<table>
<center>
Total Params: 3743280
</center>
</table>
By using a 128-neuron fully connected layer as its last layer, the model ensures that the output is an encoding vector of size 128. You then use the encodings the compare two face images as follows:
<img src="images/distance_kiank.png" style="width:680px;height:250px;">
<caption><center> <u> <font color='purple'> **Figure 2**: <br> </u> <font color='purple'> By computing a distance between two encodings and thresholding, you can determine if the two pictures represent the same person</center></caption>
So, an encoding is a good one if:
- The encodings of two images of the same person are quite similar to each other
- The encodings of two images of different persons are very different
The triplet loss function formalizes this, and tries to "push" the encodings of two images of the same person (Anchor and Positive) closer together, while "pulling" the encodings of two images of different persons (Anchor, Negative) further apart.
<img src="images/triplet_comparison.png" style="width:280px;height:150px;">
<br>
<caption><center> <u> <font color='purple'> **Figure 3**: <br> </u> <font color='purple'> In the next part, we will call the pictures from left to right: Anchor (A), Positive (P), Negative (N) </center></caption>
### 1.2 - The Triplet Loss
For an image $x$, we denote its encoding $f(x)$, where $f$ is the function computed by the neural network.
<img src="images/f_x.png" style="width:380px;height:150px;">
<!--
We will also add a normalization step at the end of our model so that $\mid \mid f(x) \mid \mid_2 = 1$ (means the vector of encoding should be of norm 1).
!-->
Training will use triplets of images $(A, P, N)$:
- A is an "Anchor" image--a picture of a person.
- P is a "Positive" image--a picture of the same person as the Anchor image.
- N is a "Negative" image--a picture of a different person than the Anchor image.
These triplets are picked from our training dataset. We will write $(A^{(i)}, P^{(i)}, N^{(i)})$ to denote the $i$-th training example.
You'd like to make sure that an image $A^{(i)}$ of an individual is closer to the Positive $P^{(i)}$ than to the Negative image $N^{(i)}$) by at least a margin $\alpha$:
$$\mid \mid f(A^{(i)}) - f(P^{(i)}) \mid \mid_2^2 + \alpha < \mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2$$
You would thus like to minimize the following "triplet cost":
$$\mathcal{J} = \sum^{N}_{i=1} \large[ \small \underbrace{\mid \mid f(A^{(i)}) - f(P^{(i)}) \mid \mid_2^2}_\text{(1)} - \underbrace{\mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2}_\text{(2)} + \alpha \large ] \small_+ \tag{3}$$
Here, we are using the notation "$[z]_+$" to denote $max(z,0)$.
Notes:
- The term (1) is the squared distance between the anchor "A" and the positive "P" for a given triplet; you want this to be small.
- The term (2) is the squared distance between the anchor "A" and the negative "N" for a given triplet, you want this to be relatively large, so it thus makes sense to have a minus sign preceding it.
- $\alpha$ is called the margin. It is a hyperparameter that you should pick manually. We will use $\alpha = 0.2$.
Most implementations also normalize the encoding vectors to have norm equal one (i.e., $\mid \mid f(img)\mid \mid_2$=1); you won't have to worry about that here.
**Exercise**: Implement the triplet loss as defined by formula (3). Here are the 4 steps:
1. Compute the distance between the encodings of "anchor" and "positive": $\mid \mid f(A^{(i)}) - f(P^{(i)}) \mid \mid_2^2$
2. Compute the distance between the encodings of "anchor" and "negative": $\mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2$
3. Compute the formula per training example: $ \mid \mid f(A^{(i)}) - f(P^{(i)}) \mid - \mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2 + \alpha$
3. Compute the full formula by taking the max with zero and summing over the training examples:
$$\mathcal{J} = \sum^{N}_{i=1} \large[ \small \mid \mid f(A^{(i)}) - f(P^{(i)}) \mid \mid_2^2 - \mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2+ \alpha \large ] \small_+ \tag{3}$$
Useful functions: `tf.reduce_sum()`, `tf.square()`, `tf.subtract()`, `tf.add()`, `tf.reduce_mean`, `tf.maximum()`.
```
# GRADED FUNCTION: triplet_loss
def triplet_loss(y_true, y_pred, alpha = 0.2):
"""
Implementation of the triplet loss as defined by formula (3)
Arguments:
y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.
y_pred -- python list containing three objects:
anchor -- the encodings for the anchor images, of shape (None, 128)
positive -- the encodings for the positive images, of shape (None, 128)
negative -- the encodings for the negative images, of shape (None, 128)
Returns:
loss -- real number, value of the loss
"""
anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]
### START CODE HERE ### (≈ 4 lines)
# Step 1: Compute the (encoding) distance between the anchor and the positive
pos_dist = tf.square(anchor-positive)
# Step 2: Compute the (encoding) distance between the anchor and the negative
neg_dist = tf.square(anchor-negative)
# Step 3: subtract the two previous distances and add alpha.
basic_loss = tf.reduce_sum(pos_dist-neg_dist)+alpha
# Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples.
loss = tf.reduce_sum(tf.maximum(basic_loss,0.))
### END CODE HERE ###
return loss
with tf.Session() as test:
tf.set_random_seed(1)
y_true = (None, None, None)
y_pred = (tf.random_normal([3, 128], mean=6, stddev=0.1, seed = 1),
tf.random_normal([3, 128], mean=1, stddev=1, seed = 1),
tf.random_normal([3, 128], mean=3, stddev=4, seed = 1))
loss = triplet_loss(y_true, y_pred)
print("loss = " + str(loss.eval()))
```
**Expected Output**:
<table>
<tr>
<td>
**loss**
</td>
<td>
350.026
</td>
</tr>
</table>
## 2 - Loading the trained model
FaceNet is trained by minimizing the triplet loss. But since training requires a lot of data and a lot of computation, we won't train it from scratch here. Instead, we load a previously trained model. Load a model using the following cell; this might take a couple of minutes to run.
```
FRmodel.compile(optimizer = 'adam', loss = triplet_loss, metrics = ['accuracy'])
load_weights_from_FaceNet(FRmodel)
```
Here're some examples of distances between the encodings between three individuals:
<img src="images/distance_matrix.png" style="width:380px;height:200px;">
<br>
<caption><center> <u> <font color='purple'> **Figure 4**:</u> <br> <font color='purple'> Example of distance outputs between three individuals' encodings</center></caption>
Let's now use this model to perform face verification and face recognition!
## 3 - Applying the model
Back to the Happy House! Residents are living blissfully since you implemented happiness recognition for the house in an earlier assignment.
However, several issues keep coming up: The Happy House became so happy that every happy person in the neighborhood is coming to hang out in your living room. It is getting really crowded, which is having a negative impact on the residents of the house. All these random happy people are also eating all your food.
So, you decide to change the door entry policy, and not just let random happy people enter anymore, even if they are happy! Instead, you'd like to build a **Face verification** system so as to only let people from a specified list come in. To get admitted, each person has to swipe an ID card (identification card) to identify themselves at the door. The face recognition system then checks that they are who they claim to be.
### 3.1 - Face Verification
Let's build a database containing one encoding vector for each person allowed to enter the happy house. To generate the encoding we use `img_to_encoding(image_path, model)` which basically runs the forward propagation of the model on the specified image.
Run the following code to build the database (represented as a python dictionary). This database maps each person's name to a 128-dimensional encoding of their face.
```
database = {}
database["danielle"] = img_to_encoding("images/danielle.png", FRmodel)
database["younes"] = img_to_encoding("images/younes.jpg", FRmodel)
database["tian"] = img_to_encoding("images/tian.jpg", FRmodel)
database["andrew"] = img_to_encoding("images/andrew.jpg", FRmodel)
database["kian"] = img_to_encoding("images/kian.jpg", FRmodel)
database["dan"] = img_to_encoding("images/dan.jpg", FRmodel)
database["sebastiano"] = img_to_encoding("images/sebastiano.jpg", FRmodel)
database["bertrand"] = img_to_encoding("images/bertrand.jpg", FRmodel)
database["kevin"] = img_to_encoding("images/kevin.jpg", FRmodel)
database["felix"] = img_to_encoding("images/felix.jpg", FRmodel)
database["benoit"] = img_to_encoding("images/benoit.jpg", FRmodel)
database["arnaud"] = img_to_encoding("images/arnaud.jpg", FRmodel)
```
Now, when someone shows up at your front door and swipes their ID card (thus giving you their name), you can look up their encoding in the database, and use it to check if the person standing at the front door matches the name on the ID.
**Exercise**: Implement the verify() function which checks if the front-door camera picture (`image_path`) is actually the person called "identity". You will have to go through the following steps:
1. Compute the encoding of the image from image_path
2. Compute the distance about this encoding and the encoding of the identity image stored in the database
3. Open the door if the distance is less than 0.7, else do not open.
As presented above, you should use the L2 distance (np.linalg.norm). (Note: In this implementation, compare the L2 distance, not the square of the L2 distance, to the threshold 0.7.)
```
# GRADED FUNCTION: verify
def verify(image_path, identity, database, model):
"""
Function that verifies if the person on the "image_path" image is "identity".
Arguments:
image_path -- path to an image
identity -- string, name of the person you'd like to verify the identity. Has to be a resident of the Happy house.
database -- python dictionary mapping names of allowed people's names (strings) to their encodings (vectors).
model -- your Inception model instance in Keras
Returns:
dist -- distance between the image_path and the image of "identity" in the database.
door_open -- True, if the door should open. False otherwise.
"""
### START CODE HERE ###
# Step 1: Compute the encoding for the image. Use img_to_encoding() see example above. (≈ 1 line)
encoding = img_to_encoding(image_path, FRmodel)
# Step 2: Compute distance with identity's image (≈ 1 line)
dist = np.linalg.norm(encoding-database[identity])
# Step 3: Open the door if dist < 0.7, else don't open (≈ 3 lines)
if dist<0.7:
print("It's " + str(identity) + ", welcome home!")
door_open = 1
else:
print("It's not " + str(identity) + ", please go away")
door_open = 0
### END CODE HERE ###
return dist, door_open
```
Younes is trying to enter the Happy House and the camera takes a picture of him ("images/camera_0.jpg"). Let's run your verification algorithm on this picture:
<img src="images/camera_0.jpg" style="width:100px;height:100px;">
```
verify("images/camera_0.jpg", "younes", database, FRmodel)
```
**Expected Output**:
<table>
<tr>
<td>
**It's younes, welcome home!**
</td>
<td>
(0.65939283, True)
</td>
</tr>
</table>
Benoit, who broke the aquarium last weekend, has been banned from the house and removed from the database. He stole Kian's ID card and came back to the house to try to present himself as Kian. The front-door camera took a picture of Benoit ("images/camera_2.jpg). Let's run the verification algorithm to check if benoit can enter.
<img src="images/camera_2.jpg" style="width:100px;height:100px;">
```
verify("images/camera_2.jpg", "kian", database, FRmodel)
```
**Expected Output**:
<table>
<tr>
<td>
**It's not kian, please go away**
</td>
<td>
(0.86224014, False)
</td>
</tr>
</table>
### 3.2 - Face Recognition
Your face verification system is mostly working well. But since Kian got his ID card stolen, when he came back to the house that evening he couldn't get in!
To reduce such shenanigans, you'd like to change your face verification system to a face recognition system. This way, no one has to carry an ID card anymore. An authorized person can just walk up to the house, and the front door will unlock for them!
You'll implement a face recognition system that takes as input an image, and figures out if it is one of the authorized persons (and if so, who). Unlike the previous face verification system, we will no longer get a person's name as another input.
**Exercise**: Implement `who_is_it()`. You will have to go through the following steps:
1. Compute the target encoding of the image from image_path
2. Find the encoding from the database that has smallest distance with the target encoding.
- Initialize the `min_dist` variable to a large enough number (100). It will help you keep track of what is the closest encoding to the input's encoding.
- Loop over the database dictionary's names and encodings. To loop use `for (name, db_enc) in database.items()`.
- Compute L2 distance between the target "encoding" and the current "encoding" from the database.
- If this distance is less than the min_dist, then set min_dist to dist, and identity to name.
```
# GRADED FUNCTION: who_is_it
def who_is_it(image_path, database, model):
"""
Implements face recognition for the happy house by finding who is the person on the image_path image.
Arguments:
image_path -- path to an image
database -- database containing image encodings along with the name of the person on the image
model -- your Inception model instance in Keras
Returns:
min_dist -- the minimum distance between image_path encoding and the encodings from the database
identity -- string, the name prediction for the person on image_path
"""
### START CODE HERE ###
## Step 1: Compute the target "encoding" for the image. Use img_to_encoding() see example above. ## (≈ 1 line)
encoding = img_to_encoding(image_path, model)
## Step 2: Find the closest encoding ##
# Initialize "min_dist" to a large value, say 100 (≈1 line)
min_dist = 100
# Loop over the database dictionary's names and encodings.
for (name, db_enc) in database.items():
# Compute L2 distance between the target "encoding" and the current "emb" from the database. (≈ 1 line)
dist = np.linalg.norm(encoding-database[name])
# If this distance is less than the min_dist, then set min_dist to dist, and identity to name. (≈ 3 lines)
if dist<min_dist:
min_dist = dist
identity = name
### END CODE HERE ###
if min_dist > 0.7:
print("Not in the database.")
else:
print ("it's " + str(identity) + ", the distance is " + str(min_dist))
return min_dist, identity
```
Younes is at the front-door and the camera takes a picture of him ("images/camera_0.jpg"). Let's see if your who_it_is() algorithm identifies Younes.
```
who_is_it("images/camera_0.jpg", database, FRmodel)
```
**Expected Output**:
<table>
<tr>
<td>
**it's younes, the distance is 0.659393**
</td>
<td>
(0.65939283, 'younes')
</td>
</tr>
</table>
You can change "`camera_0.jpg`" (picture of younes) to "`camera_1.jpg`" (picture of bertrand) and see the result.
Your Happy House is running well. It only lets in authorized persons, and people don't need to carry an ID card around anymore!
You've now seen how a state-of-the-art face recognition system works.
Although we won't implement it here, here're some ways to further improve the algorithm:
- Put more images of each person (under different lighting conditions, taken on different days, etc.) into the database. Then given a new image, compare the new face to multiple pictures of the person. This would increae accuracy.
- Crop the images to just contain the face, and less of the "border" region around the face. This preprocessing removes some of the irrelevant pixels around the face, and also makes the algorithm more robust.
<font color='blue'>
**What you should remember**:
- Face verification solves an easier 1:1 matching problem; face recognition addresses a harder 1:K matching problem.
- The triplet loss is an effective loss function for training a neural network to learn an encoding of a face image.
- The same encoding can be used for verification and recognition. Measuring distances between two images' encodings allows you to determine whether they are pictures of the same person.
Congrats on finishing this assignment!
### References:
- Florian Schroff, Dmitry Kalenichenko, James Philbin (2015). [FaceNet: A Unified Embedding for Face Recognition and Clustering](https://arxiv.org/pdf/1503.03832.pdf)
- Yaniv Taigman, Ming Yang, Marc'Aurelio Ranzato, Lior Wolf (2014). [DeepFace: Closing the gap to human-level performance in face verification](https://research.fb.com/wp-content/uploads/2016/11/deepface-closing-the-gap-to-human-level-performance-in-face-verification.pdf)
- The pretrained model we use is inspired by Victor Sy Wang's implementation and was loaded using his code: https://github.com/iwantooxxoox/Keras-OpenFace.
- Our implementation also took a lot of inspiration from the official FaceNet github repository: https://github.com/davidsandberg/facenet
| github_jupyter |
# Time Domain Spectral Simulations
Demonstrate how to inspect simulated spectra produced using `quicktransients`.
```
import numpy as np
from astropy.io import fits
from astropy.table import Table, Column
from desispec.io.spectra import read_spectra
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('font', size=14)
```
## Input Files
The `quicktransients` program in the [desisim transients branch](https://github.com/desihub/desisim) will produce two FITS outputs:
1. A truth file with information about the templates used for each object.
2. A spect file with the templates "observed" under conditions specified by the user.
The spectra can then be coadded using the `desi_coadd_spectra` program available in [desispec](https://github.com/desihub/desispec).
```
truth_file = '../../bgs_2020-03-08_0300s_001_truth.fits'
spect_file = '../../bgs_2020-03-08_0300s_001_spect.fits'
coadd_file = '../../bgs_2020-03-08_0300s_001_coadd.fits'
```
### Contents of the Truth File
The truth file has the following tables:
1. A wavelength table called `WAVE`.
1. A flux table called `FLUX`.
1. A `TARGETS` table simulating a target list available in data.
1. A simulation `TRUTH` table with information about the object (redshift, flux, etc.).
1. A simulation `OBJTRUTH` table with line fluxes and other data generated for each object.
```
hdus = fits.open(truth_file)
hdus.info()
wave = hdus['WAVE'].data
flux = hdus['FLUX'].data
targets = Table.read(truth_file, 'TARGETS')
truth = Table.read(truth_file, 'TRUTH')
objtr = Table.read(truth_file, 'OBJTRUTH')
truth
r = 22.5 - 2.5*np.log10(truth['FLUX_R'])
z = truth['TRUEZ']
fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.scatter(z, r)
ax.set(xlabel='$z$', ylabel='$r$')
fig.tight_layout();
targets
objtr
```
#### Object Truth Data
Plot transient data from the objtruth table:
1. Distribution of "epoch," time in days w.r.t. $t_0$.
1. Distribution of transient/host flux ratio in $r$ band.
```
fig, axes = plt.subplots(1,2, figsize=(9,4), sharey=True)
ax = axes[0]
n, bins, patches = ax.hist(objtr['TRANSIENT_EPOCH'], bins=10, color='k', alpha=0.3)
x = 0.5*(bins[1:] + bins[:-1])
dx = 0.5*np.diff(bins)
ax.errorbar(x, n, xerr=dx, yerr=np.sqrt(n), fmt=',', color='k')
ax.set(xlabel='epoch [day]', ylabel='count')
ax = axes[1]
n, bins, patches = ax.hist(objtr['TRANSIENT_RFLUXRATIO'], bins=10, color='k', alpha=0.3)
x = 0.5*(bins[1:] + bins[:-1])
dx = 0.5*np.diff(bins)
ax.errorbar(x, n, xerr=dx, yerr=np.sqrt(n), fmt=',', color='k')
ax.set(xlabel=r'$r_\mathrm{trans}/r_\mathrm{host}$')
fig.tight_layout();
```
#### Plot Templates
Draw the first 10 templates generated from the mock catalog.
```
for i in range(10):
plt.plot(wave, flux[i])
```
### Observed Spectra
The spectra generated under observing conditions are stored in a single file. A `FIBERMAP` table provides a summary of target data for each object, and individual wavelength, flux, variance, resolution, and mask tables are present for each camera.
The data are best accessed using the `read_spectra` function from [desispec](https://github.com/desihub/desispec), which packs everything into a single object.
```
spectra = read_spectra(spect_file)
hdus = fits.open(spect_file)
hdus.info()
spectra.fibermap
```
### Coadd Files
The coadds are generated using the `desi_coadd_spectra` program available in [desispec](https://github.com/desihub/desispec). For example, to add data across the cameras run
```
desi_coadd_spectra -i bgs_2020-03-08_0150s_001_spect.fits -o bgs_2020-03-08_0150s_001_coadd.fits --coadd-cameras
```
The data can then be accessed using the `read_spectra` function.
```
coadds = read_spectra(coadd_file)
hdus = fits.open(coadd_file)
hdus.info()
coadds.fibermap
```
### Spectral Scores
Per-camera median coadded fluxes and SNRs are available in a scores table.
The code below computes a total SNR and adds it to the table.
```
if 'MEDIAN_COADD_SNR' not in coadds.scores.columns:
totsnr = None
for cam in 'BRZ':
camsnr = coadds.scores['MEDIAN_COADD_SNR_{}'.format(cam)]
if totsnr is None:
totsnr = camsnr**2
else:
totsnr += camsnr**2
totsnr = np.sqrt(totsnr)
coadds.scores.add_column(Column(totsnr, name='MEDIAN_COADD_SNR'))
coadds.scores
```
### Plot Results
To visualize the results, the templates, camera data, and coadds for the first 10 spectra in the input files listed at the top of this notebook are plotted.
```
from scipy.signal import medfilt
fig, axes = plt.subplots(10,3, figsize=(14,30), sharex=True)
for i in range(10):
axes[i,0].plot(wave, flux[i], alpha=0.7, label='template')
axes[i,0].legend()
for _filt, _col in zip(spectra.bands, ['b', 'r', 'saddlebrown']):
wl = spectra.wave[_filt]
fl = spectra.flux[_filt][i]
axes[i,1].plot(wl, fl, color=_col, alpha=0.7, label=_filt)
axes[i,1].legend()
axes[i,2].plot(coadds.wave['brz'], coadds.flux['brz'][i], alpha=0.7, label='coadd')
axes[i,2].plot(coadds.wave['brz'], medfilt(coadds.flux['brz'][i], 149), color='yellow')
axes[i,2].legend()
fig.tight_layout();
```
| github_jupyter |
```
# import packages
import numpy as np
import matplotlib.pyplot as plt
import arviz as az
import pybeam.default as pbd
# modify figure text settings
plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['ps.fonttype'] = 42
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams.update({ 'mathtext.default' : 'regular' })
# define base model
model = {'type' : 'base', # model type ('base' or 'ugm')
'sigma' : 1.0, # sets sigma, the scaling parameter
'threshold' : 'fixed', # sets threshold type (fixed, linear, exponential, or weibull)
'leakage' : False, # if True, drift rate has leaky integration
'delay' : False, # if True, decision threshold motion is delayed
'contamination' : False} # if True, uniform contamination added to model
# outputs which parameters your model uses
pbd.parse_model(model)
# parameters for simulated data
phi = {'t_nd' : 0.25, # non-decision time
'w' : 0.5, # relative start point
'mu' : 1.0, # drift rate
'a' : 0.75} # decision threshold location
# simulate data
rt = pbd.simulate_model(N_sims = 500, # number of data points to simulate
model = model, # model dictionary
phi = phi, # parameters used to simulate data
seed = 123) # rng seed
# plot simulated data and model likelihood function
pbd.plot_rt(model = model, # model dictionary
phi = phi, # parameters used for model likelihood
rt = rt, bins = 50); # dictionary of simulated rt data
# define model priors
p = {'pt_nd' : 'Uniform("t_nd", lower = 0.0, upper = 0.75)', # prior for non-decision time
'pw' : 'Uniform("w", lower = 0.3, upper = 0.7)', # prior for relative start point
'pmu' : 'Uniform("mu", lower = -5.0, upper = 5.0)', # prior for drift rate
'pa' : 'Uniform("a", lower = 0.1, upper = 1.0)'} # prior for decision threshold
# define model conditions
c = {'rt' : rt, # dictionary containing reaction time data
't_nd' : 'pt_nd', # sets prior used for non-decision time, references p['pt_nd']
'w' : 'pw', # sets prior used for relative start point, references p['pw']
'mu' : 'pmu', # sets prior used for the drift rate, references p['pmu']
'a' : 'pa'} # sets prior used prior for the threshold, references p['pa']
# load conditions into dictionary
cond = {0 : c}
# run parameter inference
trace = pbd.inference(model = model, # model dictionary
priors = p, # priors dictionary
conditions = cond, # conditions dictionary
samples = 25000, # number of samples completed per chain
chains = 3, # number of chains
cores = 3, # number of cpu's to run chains on
file_name = 'flat' ) # name of output file
# plot trace
pbd.plot_trace(file_name = 'flat', burnin = 12500);
# navarro analytic solution for the base model
def fpt(v, a, w, t):
cons = (np.pi/(a*a))*np.exp(-v*a*w - v*v*t/2.0)
sum_terms = 0.0
for ii in range(1,1000):
sum_terms += ii*np.exp(-ii*ii*np.pi*np.pi*t/(2.0*a*a))*np.sin(ii*np.pi*w)
out = cons*sum_terms
return out
# set figure size and subplot spacing
fig, axs = plt.subplots(2, 3, figsize=(6.2, 3.6), dpi=600);
plt.subplots_adjust(hspace=0.75)
# calculate model likelihood using PyBEAM, and plot in panel [0,0]
model_rt = pbd.model_rt(model = model, phi = phi)
axs[0,0].plot(model_rt['time'], model_rt['model_rt_upper'], color = 'r', linewidth = 2)
axs[0,0].plot(-model_rt['time'], model_rt['model_rt_lower'], color = 'r', label = '_nolegend_', linewidth = 2)
axs[0,0].set_xlim(-2.5, 2.5)
# calculate model likelihood from navarro analytic solution, plot in panel [0,0]
t = np.linspace(0.01, 2.5, 1000)
f_bu = np.zeros_like(t)
f_bl = np.zeros_like(t)
v = 1.0
w = 0.5
a = 0.75
for ii in range(len(t)):
f_bl[ii] = fpt(v, 2.0*a, w, t[ii])
f_bu[ii] = fpt(-v, 2.0*a, (1.0 - w), t[ii])
axs[0,0].plot(t + 0.25, f_bu, color = 'b', linestyle = '--', linewidth = 2)
axs[0,0].plot(-(t + 0.25), f_bl, color = 'b', linestyle = '--', label = '_nolegend_', linewidth = 2)
axs[0,0].legend(['PyBEAM', 'Analytic'], fontsize = 7.5, handlelength = 1.0)
# import mcmc inference data
file_name = 'flat'
burnin = 12500
trace = az.from_netcdf(file_name + '.nc')
trace = trace.sel(draw=slice(burnin,None))
trace = trace.posterior.stack(draws=("chain", "draw"))
# plot 100 random values from the posteriors in panel [0,1]
t_nd = trace.t_nd.values
w = trace.w.values
mu = trace.mu.values
a = trace.a.values
N_pp = 100
for ii in range(N_pp):
ind = np.random.randint(0, len(t_nd))
t_nd_ind = t_nd[ind]
w_ind = w[ind]
mu_ind = mu[ind]
a_ind = a[ind]
phi_temp = {'t_nd' : t_nd_ind, 'w' : w_ind, 'mu' : mu_ind, 'a' : a_ind}
rt_model = pbd.model_rt(model = model, phi = phi)
if (ii == 0):
axs[0,1].plot(rt_model['time'], rt_model['model_rt_upper'], color = 'r')
axs[0,1].plot(-rt_model['time'], rt_model['model_rt_lower'], color = 'r', linewidth = 0.5, label = '_nolegend_')
else:
axs[0,1].plot(rt_model['time'], rt_model['model_rt_upper'], color = 'r', linewidth = 0.5, label='_nolegend_')
axs[0,1].plot(-rt_model['time'], rt_model['model_rt_lower'], color = 'r', linewidth = 0.5, label='_nolegend_')
# plot histogram of simulated data in panel [0,1]
axs[0,1].set_xlim(-2.5, 2.5)
rt_all = np.concatenate((rt['rt_upper'], -rt['rt_lower']))
axs[0,1].hist(rt_all, density = True, bins = 25, edgecolor = 'k', facecolor = 'lightgrey');
axs[0,1].legend(['PyBEAM', 'Data'], fontsize = 7.5, loc = 'upper left', handlelength = 1)
# plot histogram of non-decision time posterior
axs[0,2].hist(t_nd, density = True, bins = 10, edgecolor = 'k', facecolor = 'lightgrey');
axs[0,2].axvline(x=0.25, c = 'b', linewidth = 2.5)
axs[0,2].set_xlim(0.125, 0.35)
axs[0,2].set_xlabel('Non-decision Time ($t_{nd}$)')
axs[0,2].legend(['True', 'Posterior'], fontsize = 7.5, loc = 'upper left', handlelength = 1.0)
# plot histogram of relative start posterior
axs[1,0].hist(w, density = True, bins = 10, edgecolor = 'k', facecolor = 'lightgrey');
axs[1,0].axvline(x=0.5, c = 'b', linewidth = 3)
axs[1,0].set_xlim(0.25, 0.75)
axs[1,0].set_xlabel('Relative Start ($w$)')
# plot histogram of drift rate posterior
axs[1,1].hist(mu, density = True, bins = 10, edgecolor = 'k', facecolor = 'lightgrey');
axs[1,1].axvline(x=1.0, c = 'b', linewidth = 3)
axs[1,1].set_xlim(0.0, 2.0)
axs[1,1].set_xlabel('Drift ($\mu$)')
# plot histogram of decison threshold posterior
axs[1,2].hist(a, density = True, bins = 10, edgecolor = 'k', facecolor = 'lightgrey');
axs[1,2].axvline(x=0.75, c = 'b', linewidth = 3)
axs[1,2].set_xlim(0.5, 1.0)
axs[1,2].set_xlabel('Decision Threshold (a)')
# add remaining axis labels and titles
axs[0,0].set_xlabel('Time (s)')
axs[0,0].set_title('A) Likelihood Val.', loc = 'left')
axs[0,1].set_xlabel('Time (s)')
axs[0,1].set_title('B) Posterior Pred.', loc = 'left')
axs[0,2].set_title('C1) Posteriors', loc = 'left')
axs[1,0].set_title('C2)', loc = 'left')
axs[1,1].set_title('C3)', loc = 'left')
axs[1,2].set_title('C4)', loc = 'left')
axs[0,0].set_ylim(0.0, 2.0)
axs[0,1].set_ylim(0.0, 2.0)
# remove yticks and ytick labels
for ii in range(2):
for jj in range(3):
axs[ii,jj].set_yticklabels([])
axs[ii,jj].set_yticks([])
# save figure as pdf
plt.savefig('flat.pdf', bbox_inches = 'tight', dpi = 600)
```
| github_jupyter |
```
# Imports
import os
import numpy as np
import xarray as xr
def load_ndwi(prod, res=30.):
"""
Load NDWI index (and rename the array)
"""
# Read NDWI index
ndwi = prod.load(NDWI)[NDWI]
ndwi_name = f"NDWI {ndwi.attrs['sensor']}"
return ndwi.rename(ndwi_name)
def extract_water(ndwi):
"""
Extract water from NDWI index (and rename the array)
"""
# Assert water bodies when NDWI index > 0.2
water = xr.where(ndwi > 0.2, 1, 0)
# Set nodata where ndwi is nan.
# WARNING: the function xr.DataArray.where sets by default np.nan where the condition is false !
# See here: http://xarray.pydata.org/en/stable/generated/xarray.DataArray.where.html
water = water.where(~np.isnan(ndwi))
# Plot a subsampled version
water_name = f"WATER {ndwi.attrs['sensor']}"
return water.rename(water_name)
# Create logger
import logging
logger = logging.getLogger("eoreader")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# First of all, we need some satellite data.
# Let's take 3 products covering approximately the same area
prod_folder = os.path.join("/home", "data", "DS3", "CI", "extracteo", "water")
paths = [
# Landsat-8 OLCI collection 2
os.path.join(prod_folder, "LC08_L1TP_200030_20201220_20210310_02_T1.tar"),
# Landsat-5 TM collection 2
os.path.join(prod_folder, "LT05_L1TP_200030_20111110_20200820_02_T1.tar"),
# Sentinel-2 L2A
os.path.join(prod_folder, "S2A_MSIL2A_20191215T110441_N0213_R094_T30TXP_20191215T122756.zip"),
]
from eoreader.reader import Reader
from eoreader.bands import *
# Create the reader
eoreader = Reader()
# Loop on all the products
water_arrays = []
ndwi_arrays = []
extents = []
for path in paths:
logger.info(f"*** {os.path.basename(path)} ***")
# Open the product
prod = eoreader.open(path, remove_tmp=True)
# Get extents
extents.append(prod.extent)
# Read NDWI index
# 60.0 meters is the lower resolution between the wanted products (Landsat 5 MSS)
ndwi = load_ndwi(prod, res=60.)
ndwi_arrays.append(ndwi)
# Extract water
water_arrays.append(extract_water(ndwi))
logger.info("\n")
# Plot the tiles
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
nrows = len(paths)
plt.figure(figsize=(4 * nrows, 6 * nrows))
for i in range(nrows):
# Compute cartopy projection (EOReader always is in UTM)
extent = extents[i]
str_epsg = str(extent.crs.to_epsg())
zone = str_epsg[-2:]
is_south = str_epsg[2] == 7
proj = ccrs.UTM(zone, is_south)
# Get extent values
# The extents must be defined in the form (min_x, max_x, min_y, max_y)
bounds = extent.bounds
extent_val = [bounds.minx[0], bounds.maxx[0], bounds.miny[0], bounds.maxy[0]]
# Plot NDWI
axes = plt.subplot(nrows, 2, 2*i+1, projection=proj)
axes.set_extent(extent_val, proj)
axes.imshow(ndwi_arrays[i][0, ::10, ::10], origin='upper', extent=extent_val, transform=proj)
axes.coastlines(linewidth=1)
# Plot water
axes = plt.subplot(nrows, 2, 2*i+2, projection=proj)
axes.set_extent(extent_val, proj)
axes.imshow(water_arrays[i][0, ::10, ::10], origin='upper', extent=extent_val, transform=proj)
axes.coastlines(linewidth=1)
```
| github_jupyter |
```
import xarray as xr
import numpy as np
import pandas as pd
# random fake dataset
da = xr.DataArray(np.random.randn(2, 3, 2), dims=("x", "y",'t'), coords={"x": [10, 20], 'y':[33,44,55], 't':[7,8]})
da=da.rename('elev')
ds=da.to_dataset()
ds
# function to apply
def fn(x,y,elev,z):
misc_arr = [np.array([[1,2],[3,4],[5,6],[1,2]]), np.array([[9,8],[7,6],[5,4],[3,2],[1,0],[9,8]])]
return misc_arr
# using groupby and apply --> this is likely a bug that was fixed in the most recent version
ds.groupby('t', squeeze=False).apply(fn, args=(ds.x, ds.y, ds.elev, 10))
# create a groupby wrapper to deal with the args issues
def fn_wrapper(gb):
x=gb.x
y=gb.y
elev=gb.elev
z = 12
# print(gb)
array = fn(x,y,elev,z)
bergs=pd.Series({'bergs':[array]}, dtype='object')
return gb.assign(new_var=('t',bergs))
ds.groupby('t', squeeze=False).apply(fn_wrapper)
# this doesn't work because the function itself still returns the array. It's the wrapper that turns the array into a series with dtype object to add back in to the DataSet
# could add an xarray boolean flag to the fn that defaults to false but returns the series instead if run for an xarray object
# xr.apply_ufunc(fn, ds.x, ds.y, ds.elev.groupby('t'),12, input_core_dims=[['x'],['y'],['x','y'],[]],output_core_dims=[['t']], exclude_dims=set(['x','y']))
new_vals=xr.apply_ufunc(fn, ds.x, ds.y, ds.elev.groupby('t',squeeze=False), 12, input_core_dims=[['x'],['y'],['x','y','t'],[]],output_core_dims=[['t']], exclude_dims=set(['x','y']))
new_vals
xr.merge([ds,new_vals.rename('new_val')])
# prepending the variable doesn't work because the dataset is rewritten during the groupby().apply() operation.
# first add the new variable to the dataset before running the function
ds=ds.assign(new_var=('t',[misc_arr, misc_arr2]))
ds
```
## Is what I want to do possible? YES
***DO NOTE DELETE THESE BLOCKS OF CODE - USE FOR EXAMPLE!***
```
misc_arr = [np.array([[1,2],[3,4],[5,6],[1,2]]), np.array([[9,8],[7,6],[5,4],[3,2],[1,0],[9,8]])]
misc_arr2 = [np.array([[9,8],[7,6],[5,4],[3,2],[1,0],[9,8]]), np.array([[9,8],[7,6],[5,4],[3,2],[1,0],[9,8]]),
np.array([[1,2],[3,4],[5,6],[1,2]])]
misc_arr3 = [np.array([[1,2],[3,4],[5,6],[7,8],[1,2]])]
misc_arr4 = [np.array([[1,2],[3,4],[5,6],[1,2]]), np.array([[9,8],[7,6],[5,4],[9,8]]),
np.array([[1,2],[3,4],[5,6],[7,6],[5,4],[1,2]]), np.array([[3,4],[5,6],[10,12],[9,8],[1,2]]),
np.array([[9,8],[7,6],[5,4],[1,2],[3,4],[9,8]])]
```
print(len(misc_arr))
print(len(misc_arr2))
print(len(misc_arr3))
print(len(misc_arr4))
```
da = xr.DataArray([misc_arr, misc_arr2, misc_arr3, misc_arr4], dims='time', name='tests')
da
ds = da.to_dataset()
ds
```
Helpful XArray resources from Ryan and others
http://xarray.pydata.org/en/stable/indexing.html#align-and-reindex
http://xarray.pydata.org/en/stable/examples/multidimensional-coords.html#Plotting
https://earth-env-data-science.github.io/lectures/xarray/xarray-part2.html
https://earth-env-data-science.github.io/lectures/xarray/xarray-part2.html#transformations
https://earth-env-data-science.github.io/lectures/pandas/pandas_groupby.html
https://rabernat.github.io/research_computing_2018/xarray.html
https://corteva.github.io/rioxarray/stable/examples/reproject_match.html
| github_jupyter |
```
#importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import nltk
import re
from collections import Counter
import time
import operator
#nltk.download('stopwords')
#from nltk.corpus import stopwords
#Importing dataset with codes description
descr = pd.read_csv('desc.csv', encoding = "ISO-8859-1", sep = ';', dtype = str)
#descr.head()
descr = descr[['code', 'name', 'notes']]
descr_test = []
for i in range(len(descr)):
if len(descr.iloc[i,0]) == 2:
descr_test.append(descr.iloc[i])
pd.DataFrame(descr_test).head()
desc_y = pd.DataFrame(descr_test).iloc[:,0].values
desc_X = pd.DataFrame(descr_test).iloc[:,1].values
desc_X2 = pd.DataFrame(descr_test).iloc[:,2].values
for i in range(len(desc_X2)):
if not pd.isnull(desc_X2[i]):
pos = desc_X2[i].find('Ekskluderer: ')
if pos != -1:
desc_X2[i] = desc_X2[i][1:(pos-1)].lower().replace('omfatter ', '')
else:
desc_X2[i] = desc_X2[i][1:].lower().replace('omfatter ', '')
desc_X2[0]
#Importing dataset with company's descriptions
dataset = pd.read_csv('BESK_ALLE.csv', encoding = "ISO-8859-1", sep=';', dtype = 'str')
dataset = dataset[:1575675]
dataset = dataset[~dataset.besk.isnull()]
#define y and X
X = dataset.iloc[:, 1].values
y = dataset.iloc[:, 0].values
X_desc = X
X_desc = np.concatenate((X_desc, desc_X), axis = None)
X_desc = np.concatenate((X_desc, desc_X2), axis = None)
y_2 = []
for i in range(len(y)):
y_2.append(y[i][:2])
y_2.extend(desc_y)
y_2.extend(desc_y)
y_2 = np.array(y_2)
y_2 = y_2[~pd.DataFrame(X_desc)[0].isnull()]
X_desc = X_desc[~pd.DataFrame(X_desc)[0].isnull()]
del desc_X
del desc_X2
del desc_y
del descr
del descr_test
X_bag = np.array(X_desc)
del X_desc
labels_list = []
tmp = list(Counter(y).items())
for i in tmp:
if i[1] < 2:
labels_list.append(i[0])
del tmp
labels_list
index_1 = np.where(pd.DataFrame(y)[0].isin(labels_list))
index_wo1 = np.where(~pd.DataFrame(y)[0].isin(labels_list))
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import StratifiedShuffleSplit
sss = StratifiedShuffleSplit(y[index_wo1], 1, test_size = 0.20, random_state = 0)
index_train = list(sss)[0][0]
index_test = list(sss)[0][1]
del sss
#X sets for fatstext
X_train = X[index_1]
X_train = np.concatenate((X_train, X[index_wo1][index_train]), axis = None)
X_test = X[index_wo1][index_test]
#y sets for fatstext
y_train = y[index_1]
y_train = np.concatenate((y_train, y[index_wo1][index_train]), axis = None)
y_test = y[index_wo1][index_test]
#sets for RandomForest
#after split to train_set is added desc_X, desc_X2
index_tmp = np.concatenate((index_1, list(range(len(X), len(X_bag)))), axis = None)
#X set for RandomForest
X_bag_train = X_bag[index_tmp]
X_bag_train = np.concatenate((X_bag_train, X_bag[index_wo1][index_train]), axis = None)
X_bag_test = X_bag[index_wo1][index_test]
#y set for RandomForest
y_2_train = y_2[index_tmp]
y_2_train = np.concatenate((y_2_train, y_2[index_wo1][index_train]), axis = None)
y_2_test = y_2[index_wo1][index_test]
#file for 2 1st digits prediction
pd.DataFrame([X_bag_train[i] + ' __label__' + y_2_train[i] for i in range(len(X_bag_train))]).to_csv('ft_input_2_train.csv', encoding = "utf-8", index = None, header = None)
del index_tmp
del index_train
del index_test
del index_wo1
del index_1
import fastText
from fastText import train_supervised, tokenize, load_model, unicode_literals
import io
#loading for pretrained vector
#ISO-8859-1
def load_vectors(fname):
fin = io.open(fname, 'r', encoding='utf-8', newline='\n', errors='ignore')
n, d = map(int, fin.readline().split())
data = {}
for line in fin:
tokens = line.rstrip().split(' ')
data[tokens[0]] = map(float, tokens[1:])
fin.close()
return data
ts_before = time.time()
#from Paul's code
#model for 2 first digits
model_2 = train_supervised(
input = 'ft_input_2_train.csv',
wordNgrams = 3,
#label = '__label__',
verbose = 2,
minCount = 1, # minimal number of word occurences
neg = 10, #number of negatives sampled
dim = 300,
pretrainedVectors = 'cc.nn.300.vec'
)
ts_after = time.time()
print(ts_after - ts_before)
#y for 2 first digits
y_2_pred = []
for i in range(len(X_test)):
pred = model_2.predict(X_test[i])[0][0]
y_2_pred.append(pred[9:11])
#see model work
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, log_loss
def metrics_score(test, pred):
print('accuracy: ', accuracy_score(test, pred))
print('precision: ', precision_score(test, pred, average='macro'))
print('recall: ', recall_score(test, pred, average='macro'))
print('f1: ', f1_score(test, pred, average='macro'))
metrics_score(y_2_test, y_2_pred)
labels = np.unique(y_2_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_2_test, y_2_pred, labels)
fig = plt.figure(figsize = (30,20))
import seaborn as sn
sn.heatmap(pd.DataFrame(cm, index = labels, columns = labels), annot = True)
pd.DataFrame([X_train[i] + ' __label__' + y_train[i] for i in range(len(X_train))]).to_csv('ft_input_train.csv', encoding = "utf-8", index = None, header = None)
#model for 5 digits
ts_before = time.time()
#from Paul's code
model = train_supervised(
input = 'ft_input_train.csv',
wordNgrams = 3,
#label = '__label__',
verbose = 2,
minCount = 1, # minimal number of word occurences
neg = 10, #number of negatives sampled
dim = 300,
pretrainedVectors = 'cc.nn.300.vec'
)
ts_after = time.time()
print(ts_after - ts_before)
y_pred = []
for i in range(len(X_test)):
pred = model.predict(X_test[i])[0][0]
pos = pred.find('.')
y_pred.append(pred[pos-2 :pos+4])
metrics_score(y_test, y_pred)
#2 level with Fasttext
ts_before = time.time()
y_lvl_pred = []
for t in range(len(X_test)):
pred = model.predict(X_test[t], k = 50)
#print(X_test[t])
res = {}
res.clear()
for i in range(len(pred[0])):
pred_2 = model_2.predict(X_bag_test[t], k = 50)
for j in range(len(pred_2[0])):
pos = pred[0][i].find('.')
if pred[0][i][pos-2:pos] == pred_2[0][j][9:11]:
res[pred[0][i][pos-2:pos + 4]] = pred_2[1][j] * pred[1][i]
break
y_lvl_pred.append(max(res.items(), key = operator.itemgetter(1))[0])
ts_after = time.time()
print(ts_after - ts_before)
metrics_score(y_test, y_lvl_pred)
```
| github_jupyter |
```
import lifelines
import matplotlib.pyplot as plt
from lifelines.datasets import load_rossi
from lifelines import CoxPHFitter
import pandas as pd
%matplotlib inline
from functools import reduce
from math import log, exp
import operator
rossi = load_rossi()
rossi.head()
def run_filtered_cox_ph(df, time_col, event_col, covariate_names ):
df = df[covariate_names + [time_col, event_col]]
cf = lifelines.CoxPHFitter()
cf.fit(df, time_col, event_col = event_col, include_likelihood= True)
return cf
cf = run_cox_ph(rossi, "week", "arrest", ["paro", "prio"])
def present_cox_ph(cf):
fig, axes = plt.subplots(nrows=1, ncols=2, sharex=True)
cf.baseline_cumulative_hazard_.plot(ax = axes[0], title = "Baseline Cumulative Hazard")
cf.baseline_survival_.plot(ax = axes[1], title = "Baseline Survival")
present_cox_ph(cf)
class CoxPHModel:
def __init__(self, df, survival_col, cens_col, prior_params, reference_loglik = None, covariate_names = None):
self.prior_params = prior_params
self.survival_col = survival_col
self.cens_col = cens_col
all_covariate_columns = [col for col in df.columns if col not in [cens_col, survival_col]]
if covariate_names == None:
self.covariate_names = all_covariate_columns
else:
self.covariate_names = covariate_names
self.df = df[self.covariate_names + [self.survival_col, self.cens_col]]
self.mask = [x in self.covariate_names for x in all_covariate_columns]
self._cf = None
if reference_loglik == None:
reference_loglik = self.loglik()
self.reference_loglik = reference_loglik
def prior(self):
parameter_contributions = [x[1] if x[0] else (1 - x[1]) for x in zip(self.mask , self.prior_params)]
return reduce(operator.mul, parameter_contributions, 1)
def _run(self):
self._cf = lifelines.CoxPHFitter()
self._cf.fit(self.df, self.survival_col, event_col = self.cens_col, include_likelihood= True)
def loglik(self):
if self._cf is None:
self._run()
return self._cf._log_likelihood
def summary(self):
if self._cf is None:
self._run()
return self._cf.summary.index, self._cf.summary["coef"], (self._cf.summary["se(coef)"] * self._cf.summary["se(coef)"])
def bayesian_information_critera(self):
size = len(self.covariate_names)
n = self.df.shape[0]
prior = self.prior()
loglik = self.loglik()
return (size * log(n)) - (2 * (loglik - self.reference_loglik)) - (2 * log(prior))
class BMACox:
def __init__(self, x, survival_col, cens_col, priors = None):
self.df = x
self.survival_col = survival_col
self.cens_col = cens_col
if priors == None:
self.priors = [0.5] * (len(self.df.columns) - 2) #Uniformative prior
else:
self.priors = priors
self.reference_loglik = None
self.full_model = self.create_model(None)
self._set_reference_loglik()
def _generate_model_definnitions(self):
names, coefs, var = self.full_model.summary()
model1 = ["fin", "prio"]
model2 = ["race", "mar"]
model6 = ["race", "age"]
model3 = ["prio", "race"]
model4 = ["prio", "race", "mar"]
model5 = ["prio", "age", "mar"]
return [model1, model2, model3, model4, model5, model6]
def _weight_by_posterior(self, values, posterior):
def add_dataframes(dfone, dftwo):
return dfone.add(dftwo, fill_value = 0)
output = zip(values, posterior)
weighted = [x[0] * x[1] for x in output]
running_total = weighted[0]
for i in range(1, len(weighted)):
running_total = add_dataframes(running_total, weighted[i])
return running_total
def run(self):
models = self._generate_model_definnitions()
models = [self.create_model(x) for x in models]
bics = [x.bayesian_information_critera() for x in models]
self.posterior_probabilities = []
min_bic = min(bics)
summation = sum( [exp(-0.5 * (bic - min_bic)) for bic in bics])
for bic in bics:
posterior = (exp(-0.5 * (bic - min_bic)))/summation
self.posterior_probabilities.append(posterior)
coefficiencts_by_model = [x.summary()[1] for x in models]
sterr_by_model = [x.summary()[2] for x in models]
self.coefficients_weighted = self._weight_by_posterior(coefficiencts_by_model, self.posterior_probabilities)
self.sterr_weighted = self._weight_by_posterior(sterr_by_model, self.posterior_probabilities)
return self.coefficients_weighted, self.sterr_weighted
def create_model(self, covariate_names):
return CoxPHModel(self.df, self.survival_col, self.cens_col, self.priors, self.reference_loglik, covariate_names)
def _set_reference_loglik(self):
self.reference_loglik = self.full_model.loglik()
bmaCox = BMACox(rossi, "week", "arrest")
posterior = bmaCox.run()
posterior[0]
for x in posterior:
print(x)
weighted = [x[0] * x[1] for x in p]
weighted
def add_dataframes(dfone, dftwo):
return dfone.add(dftwo, fill_value = 0)
running_total = weighted[0]
for i in range(1, len(weighted)):
running_total = add_dataframes(running_total, weighted[i])
running_total
pd.DataFrame([0], columns = ["coef"])
```
| github_jupyter |
# Plotly Visualization
The aim of this notebook is to proivde guidelines on how to achieve parity with Pandas' visualization methods as explained in http://pandas.pydata.org/pandas-docs/stable/visualization.html with the use of **Plotly** and **Cufflinks**
```
import pandas as pd
import cufflinks as cf
import numpy as np
from IPython.display import display,HTML
%reload_ext autoreload
%autoreload 2
```
## Theme
Cufflinks can set global theme (sytle) to used.
In this case we will use Matplotlib's `ggplot` style.
```
cf.set_config_file(theme='ggplot',sharing='public',offline=False)
```
## Basic Plotting
The `iplot` method on Series and DataFrame is wrapper of Plotly's `plot` method
```
# Cufflinks can generate random data for different shapes
# Let's generate a single line with 1000 points
cf.datagen.lines(1,1000).iplot()
# Generating 4 timeseries
df=cf.datagen.lines(4,1000)
df.iplot()
```
You can plot one column versus another using the *x* and *y* keywords in `iplot`
```
df3 = pd.DataFrame(np.random.randn(1000, 2), columns=['B', 'C']).cumsum()
df3['A'] = pd.Series(list(range(len(df3))))
df3.iplot(x='A', y='B')
```
## Bar Plots
```
df.ix[3].iplot(kind='bar',bargap=.5)
```
Calling a DataFrame’s `plot()` method with `kind='bar'` produces a multiple bar plot:
```
df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.iplot(kind='bar')
```
To produce a stacked bar plot, use `barmode=stack`
```
df.iplot(kind='bar',barmode='stack')
```
To get horizontal bar plots, pass `kind='barh'`
```
df.iplot(kind='barh',barmode='stack',bargap=.1)
```
## Histograms
Historgrams can be used with `kind='histogram'`
```
df = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),
'c': np.random.randn(1000) - 1}, columns=['a', 'b', 'c'])
df.iplot(kind='histogram')
```
Histogram can be stacked by using `barmode=stack`. Bin size can be changed by `bin` keyword.
```
df.iplot(kind='histogram',barmode='stack',bins=20)
```
Orientation can normalization can also be set for Histograms by using `orientation='horizontal'` and `histnorm=probability`.
```
df.iplot(kind='histogram',columns=['a'],orientation='h',histnorm='probability')
```
Histograms (and any other kind of plot) can be set in a multiple layout by using `subplots=True`
```
df_h=cf.datagen.histogram(4)
df_h.iplot(kind='histogram',subplots=True,bins=50)
```
## Box Plots
Boxplots can be drawn calling a `Series` and `DataFrame` with `kind='box'`
```
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
df.iplot(kind='box')
```
### Grouping values
```
df = pd.DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'] )
df['X'] = pd.Series(['A','A','A','A','A','B','B','B','B','B'])
```
Grouping values by generating a list of figures
```
figs=[df[df['X']==d][['Col1','Col2']].iplot(kind='box',asFigure=True) for d in pd.unique(df['X']) ]
cf.iplot(cf.subplots(figs))
```
Grouping values and ammending the keys
```
def by(df,category):
l=[]
for cat in pd.unique(df[category]):
_df=df[df[category]==cat]
del _df[category]
_df=_df.rename(columns=dict([(k,'{0}_{1}'.format(cat,k)) for k in _df.columns]))
l.append(_df.iplot(kind='box',asFigure=True))
return l
cf.iplot(cf.subplots(by(df,'X')))
```
## Area Plots
You can create area plots with Series.plot and DataFrame.plot by passing `kind='area'`. To produce stacked area plot, each column must be either all positive or all negative values.
When input data contains NaN, it will be automatically filled by 0. If you want to drop or fill by different values, use dataframe.dropna() or dataframe.fillna() before calling plot.
To fill the area you can use `fill=True`
```
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.iplot(kind='area',fill=True,opacity=1)
```
For non-stacked charts you can use `kind=scatter` with `fill=True`. Alpha value is set to 0.3 unless otherwise specified:
```
df.iplot(fill=True)
```
## Scatter Plot
You can create scatter plots with DataFrame.plot by passing `kind='scatter'`. Scatter plot requires numeric columns for x and y axis. These can be specified by x and y keywords each, otherwise the DataFrame index will be used as `x`
```
df = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd'])
df.iplot(kind='scatter',x='a',y='b',mode='markers')
```
Colors can be assigned as either a list or dicitonary by using `color`.
The marker symbol can be defined by using `symbol`
```
df.iplot(kind='scatter',mode='markers',symbol='dot',colors=['orange','teal','blue','yellow'],size=10)
```
Bubble charts can be used with `kind=bubble` and by assigning one column as the `size`
```
df.iplot(kind='bubble',x='a',y='b',size='c')
```
## Scatter Matrix
You can create a scatter plot matrix using the function `scatter_matrix`
```
df = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
df.scatter_matrix()
```
## Subplots
Subplots can be defined with `subplots=True`. The shape of the output can also be determined with `shape=(rows,cols)`. If omitted then the subplot shape will automatically defined.
Axes can be shared across plots with `shared_xaxes=True` as well as `shared_yaxes=True`
```
df=cf.datagen.lines(4)
df.iplot(subplots=True,shape=(4,1),shared_xaxes=True,vertical_spacing=.02,fill=True)
```
Subplot Title can be set with `subplot_titles`. If set to `True` then the column names will be used. Otherwise a list of strings can be passed.
```
df.iplot(subplots=True,subplot_titles=True,legend=False)
```
Irregular Subplots can also be drawn using `specs`.
For example, for getting a charts that spans across 2 rows we can use `specs=[[{'rowspan':2},{}],[None,{}]]`.
For a full set of advanced layout you can see `help(cufflinks.subplots)`
```
df=cf.datagen.bubble(10,50,mode='stocks')
figs=cf.figures(df,[dict(kind='histogram',keys='x',color='blue'),
dict(kind='scatter',mode='markers',x='x',y='y',size=5),
dict(kind='scatter',mode='markers',x='x',y='y',size=5,color='teal')],asList=True)
figs.append(cf.datagen.lines(1).figure(bestfit=True,colors=['blue'],bestfit_colors=['pink']))
base_layout=cf.tools.get_base_layout(figs)
sp=cf.subplots(figs,shape=(3,2),base_layout=base_layout,vertical_spacing=.15,horizontal_spacing=.03,
specs=[[{'rowspan':2},{}],[None,{}],[{'colspan':2},None]],
subplot_titles=['Histogram','Scatter 1','Scatter 2','Bestfit Line'])
sp['layout'].update(showlegend=False)
cf.iplot(sp)
```
### Shapes
Lines can be added with `hline` and `vline` for horizontal and vertical lines respectively.
These can be either a list of values (relative to the axis) or a dictionary.
```
df=cf.datagen.lines(3,columns=['a','b','c'])
df.iplot(hline=[2,4],vline=['2015-02-10'])
```
More advanced parameters can be passed in the form of a dictionary, including `width` and `color` and `dash` for the line dash type.
```
df.iplot(hline=[dict(y=-1,color='blue',width=3),dict(y=1,color='pink',dash='dash')])
```
Shaded areas can be plotted using `hspan` and `vspan` for horizontal and vertical areas respectively.
These can be set with a list of paired tuples (v0,v1) or a list of dictionaries with further parameters.
```
df.iplot(hspan=[(-1,1),(2,5)])
```
Extra parameters can be passed in the form of dictionaries, `width`, `fill`, `color`, `fillcolor`, `opacity`
```
df.iplot(vspan={'x0':'2015-02-15','x1':'2015-03-15','color':'teal','fill':True,'opacity':.4})
# Plotting resistance lines
max_vals=df.max().values.tolist()
resistance=[dict(kind='line',y=i,color=j,width=2) for i,j in zip(max_vals,['red','blue','pink'])]
df.iplot(hline=resistance)
```
Different shapes can also be used with `shapes` and identifying the `kind` which can be either *line*, *rect* or *circle*
```
# Get min to max values
df_a=df['a']
max_val=df_a.max()
min_val=df_a.min()
max_date=df_a[df_a==max_val].index[0].strftime('%Y-%m-%d')
min_date=df_a[df_a==min_val].index[0].strftime('%Y-%m-%d')
shape1=dict(kind='line',x0=max_date,y0=max_val,x1=min_date,y1=min_val,color='blue',width=2)
shape2=dict(kind='rect',x0=max_date,x1=min_date,fill=True,color='gray',opacity=.3)
df_a.iplot(shapes=[shape1,shape2])
```
#### Other Shapes
```
x0 = np.random.normal(2, 0.45, 300)
y0 = np.random.normal(2, 0.45, 300)
x1 = np.random.normal(6, 0.4, 200)
y1 = np.random.normal(6, 0.4, 200)
x2 = np.random.normal(4, 0.3, 200)
y2 = np.random.normal(4, 0.3, 200)
distributions = [(x0,y0),(x1,y1),(x2,y2)]
dfs=[pd.DataFrame(dict(x=i,y=j)) for i,j in distributions]
d=cf.Data()
gen=cf.colorgen(scale='ggplot')
for df in dfs:
d_=df.figure(kind='scatter',mode='markers',x='x',y='y',size=5,colors=gen.next())['data']
for _ in d_:
d.append(_)
gen=cf.colorgen(scale='ggplot')
shapes=[cf.tools.get_shape(kind='circle',x0=min(x),x1=max(x),
y0=min(y),y1=max(y),color=gen.next(),fill=True,
opacity=.3,width=.4) for x,y in distributions]
fig=cf.Figure(data=d)
fig['layout']=cf.getLayout(shapes=shapes,legend=False,title='Distribution Comparison')
cf.iplot(fig,validate=False)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/r12habh/Google-Colab-Torrent-Downloader-To-Drive/blob/master/Torrent_To_Google_Drive_Downloader_v4_1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Torrent To Google Drive Downloader v4.1
### Mount Google Drive
To stream files we need to mount Google Drive.
```
from google.colab import drive
drive.mount('/content/drive')
```
###Dependency
https://www.libtorrent.org/
```
!python -m pip install --upgrade pip setuptools wheel && python -m pip install lbry-libtorrent && apt install python3-libtorrent
```
### Code to download torrent
```
import libtorrent as lt
import time
import datetime
def download_torrent():
ses = lt.session()
ses.listen_on(6881, 6891)
link = input("Input Torrent Link or Magnet and Press Enter: ")
print(link)
handle = lt.add_magnet_uri(ses, link, params)
# change the 0 to a 1 to download sequential - this sequential option is only if you selected zip. If not,
# scroll farther down.
handle.set_sequential_download(0)
ses.start_dht()
begin = time.time()
print(datetime.datetime.now())
print('Downloading Metadata...')
while not handle.has_metadata():
time.sleep(1)
print('Got Metadata, Starting Torrent Download...')
print("Starting", handle.name())
while handle.status().state != lt.torrent_status.seeding:
s = handle.status()
state_str = ['queued', 'checking', 'downloading metadata',
'downloading', 'finished', 'seeding', 'allocating']
print('%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s ' % \
(s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \
s.num_peers, state_str[s.state]))
time.sleep(5)
end = time.time()
print(handle.name(), "COMPLETE")
print("Elapsed Time: ", int((end - begin) // 60), "min :", int((end - begin) % 60), "sec")
print(datetime.datetime.now())
zipp = input("Input 'Y'/'y' to zip the torrent and place it in your drive. Otherwise, leave blank. ")
if zipp == 'Y' or zipp == 'y':
zip_name = input("Input name you would like for the zip file: ")
import shutil
params = {
'save_path': '/content/temp/',
'storage_mode': lt.storage_mode_t(2),
}
download_torrent()
print("now time to zip")
print("Zipping ...")
final_zip_directory = '/content/drive/MyDrive/Torrent/' + zip_name
shutil.make_archive(final_zip_directory, 'zip', '/content/temp/')
shutil.rmtree('/content/temp/')
else:
params = {
'save_path': '/content/drive/MyDrive/Torrent/',
'storage_mode': lt.storage_mode_t(2),
}
download_torrent()
print('\nALL DONE!')
```
| github_jupyter |
<a href="https://colab.research.google.com/github/tae898/DeepLearning/blob/master/Chapter02_Linear_Algebra.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# 2.1 Scalars, Vectors, Matrices and Tensors
numpy package has a lot of useful stuffs for linear algebra.
```
import numpy as np
```
A scalar is a single number.
```
x = 1
x
```
A vector is an array of numbers.
In Python, we can represent them as a list of numbers.
```
x = [1, 2, 3, 4, 5, 6, 7, 8]
x
```
Its length (dimension) is the number of elements
```
len(x)
```
However in Python, it's more common and easier to represent a vector in a numpy array format.
```
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
x
```
We can access its elements with square brackets.
Note that Python uses zero-based indexing (i.e. its first element is at index 0, not 1)
```
x[4]
```
A matrix is a 2-D array of numbers.
Below cell will create a matrix whose height is 3 and width is 4
```
X = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [4, 3, 2, 1]])
X
```
We can check its height and width with its (numpy array) attribute called shape. We use the terms "number of rows" and "number of columns" interchangeably with height and width, respectively.
```
X.shape
```
Indexing a matrix is similar to that of a vector. We index row first and then column. Below will access the element at 1st row and 2nd column. Keep in mind again that python uses zero-based indexing.
```
X[1,2]
```
Using `:`, we can access row vectors and column vectors.
Below cells will print the 1st row vector and its length
```
X[1,:]
len(X[1,:])
```
Below cells will print the 2nd column vector and its length
```
X[:,2]
len(X[:,2])
```
Tensors described in the book are simply just called multi-dimensional arrays. They can be created the same way as we create matrices.
Below line will create a "tensor" with 3 axes (dimensions).
```
X = np.array( [[[1, 2], [2, 3], [3, 4]],
[[-1, -2], [-2, 8], [-8, 5]]])
X
```
Take a guess what the below lines will print to the console.
```
X.shape
X[0, 0, 0]
X[1, :, :]
```
Let's create a simple 2D array again for an example.
```
X = np.array([[1, 2, 3, 4],
[2, 3, 4, 5],
[4, 3, 2, 1]])
X.shape
```
Transpose of a matrix can be done by calling the numpy function `transpose()`
```
X_transposed = np.transpose(X)
X_transposed
X_transposed.shape
```
But Python is a highly objective-oriented langauge. Its instantiated objects normally have many attributes and methods that are very handy.
numpy objects have a lot of them too and one of them is `.T`. It gives you the transposed matrix.
```
X_transposed = X.T
X_transposed
X_transposed.shape
```
When you create a numpy vector like below, the vector normally does't really have a shape. It's more like a list of numbers.
```
x = np.array([1,2,3])
x.shape
```
We can use the numpy method `reshape()` to convert it to a row or a column vector.
```
x_row = np.array([1,2,3]).reshape(1,3)
x_row
x_row.shape
x_col = np.array([1,2,3]).reshape(3,1)
x_col
x_col.shape
```
`reshape()` also allows you to use -1, if you don't want to specify the dimension of that axis. It will figure out itself to find the length of that dimension. This is pretty handy.
```
x = np.array([1,2,3]).reshape(-1, 1)
x
x.shape
```
Transposing a column vector will give you a row vector.
```
x_transposed = x.T
x_transposed
x_transposed.shape
```
FYI, in mathematics, it's more common to use column vectors than row vectors.
> In the mathematic books, you'll see things like $\pmb{x} = [1, 2, 3]^T$, way more often than $\pmb{x} = [1, 2, 3]$
In Python, matrix addition can be done easily with the plus arithmetic operator.
```
A = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [4, 3, 2, 1]])
A
B = np.array([[-1, 2, 3, -4], [3, 3, 2, -5], [-1, -3, -2, -3]])
B
C = A + B
C
```
Obviously matrix addition only works when the two matrices are of the same shape. Otherwise Python interpretor will throw you an error!
```
A = np.array([[1, 2, 3, 4],
[2, 3, 4, 5],
[4, 3, 2, 1]])
B = np.array([[-1, 2, 3, -4],
[3, 3, 2, -5],
[-1, -3, -2, -3]])
B_transposed = B.T
C = A + B_transposed
```
Adding a scalar to a matrix or multiply a matrix by a scalar is done in a very straightforward way in Python.
```
a = 2
B = np.array([[-1, 2, 3, -4], [3, 3, 2, -5], [-1, -3, -2, -3]])
c = -1
# The addition of c will be broadcasted.
D = a*B + c
D
```
Broadcasting in Python is very straightforward as well. The only thing you have to worry about is if the shapes match or not.
```
A = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [4, 3, 2, 1]])
A
# row vector
row = np.array([4, 3, 2, 1]).reshape(1, -1)
row
# column vector
col = np.array([4, 3, 2]).reshape(-1, 1)
col
C = A + row
C
C = A + col
C
```
# 2.2 Multiplying Matrices and Vectors
```
import numpy as np
```
The matrix product of two matrices can be done using the arithmetic operator
`@` (from python 3.5). You can also use the numpy function such as `np.matmul()` or `np.dot()`
```
A = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [4, 3, 2, 1]])
A
B = np.array([[-1, 2, 3, -4], [3, 3, 2, -5], [-1, -3, -2, -3]]).T
B
A @ B
np.matmul(A, B)
np.dot(A, B)
```
The element-wise product of two matrices can be done using the arithmetic operator `*`. You can also use the numpy function such as `np.multiply()`
```
A = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [4, 3, 2, 1]])
A
B = np.array([[-1, 2, 3, -4], [3, 3, 2, -5], [-1, -3, -2, -3]])
B
A * B
np.multiply(A, B)
```
Each of the below cells create a 3 by 3 matrix with random values.
```
A = np.random.randint(low=0, high=10, size=(3, 3))
A
B = np.random.randint(low=0, high=10, size=(3, 3))
B
C = np.random.randint(low=0, high=10, size=(3, 3))
C
```
Matrix multiplication is distributive
```
A@(B+C)
A@B + A@C
```
Matrix multiplication is associative
```
A@(B@C)
(A@B)@C
```
Matrix multiplication is **not** commutative
```
A@B
B@A
```
The transpose of a matrix product has a simple form
```
(A@B).T
(B.T)@(A.T)
```
numpy is very powerful. It can also solve the system of linear equations quite easily.
Below code is from [scipy](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html)
Solve the following system of equations
> $\begin{pmatrix}3 & 1 \\ 1 & 2\end{pmatrix}
\begin{pmatrix}x_1 \\ x_2\end{pmatrix}
= \begin{pmatrix}9 \\ 8\end{pmatrix}$
```
A = np.array([[3,1], [1,2]])
b = np.array([9,8])
x = np.linalg.solve(A, b)
x
```
# 2.3 Identity and Inverse Matrices
```
import numpy as np
```
numpy has the funciton `identity()` to make identity matrices. Its usage is very straightforward
```
I3 = np.identity(3)
I3
I5 = np.identity(5)
I5
```
Multiplying an identity matrix with a vector will result in the same vector. Of course the number of columns of the identity matrix has to be the same as that of the elements in the vector.
```
x = np.random.randint(low=0, high=10, size=(3, 1))
x
I3@x
```
As said in the book, obtaining an inverse matrix is not always easy. I'll take a toy example here, where the the shape of the matrix is 2 by 2.
```
A = np.array([[3,1],
[1,2]])
```
We can use the below function to get the inverse matrix of $\pmb{A}$. The shape of the inverse matrix has to be the same as the original matrix.
```
A_inv = np.linalg.inv(A)
A_inv
```
A matrix multipled with its inverse matrix will give you an identitiy matrix In this special case, the matrix multiplication is actually commutative!
```
A @ A_inv
A_inv @ A
```
Inverse matrices can be used to solve a system of linear equations. As said in the book, this is more of a theoretical tool.
Solving the below linear equation can be achieved by using an inverse matrix.
$\begin{pmatrix}3 & 1 \\ 1 & 2\end{pmatrix}
\begin{pmatrix}x_1 \\ x_2\end{pmatrix}
= \begin{pmatrix}9 \\ 8\end{pmatrix}$
> $\begin{pmatrix}x_1 \\ x_2\end{pmatrix}
= \begin{pmatrix}3 & 1 \\ 1 & 2\end{pmatrix}^{-1}
\begin{pmatrix}9 \\ 8\end{pmatrix}$
```
A = np.array([[3,1], [1,2]])
b = np.array([9,8]).reshape(-1, 1)
np.linalg.inv(A) @ b
```
# 2.4 Linear Dependence and Span
```
import numpy as np
```
$\pmb{Ax}$, matrix $\pmb{A}$ multipled by vector $\pmb{x}$ can be seen as a linear combination.
```
A = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [4, 3, 2, 1]])
A
x = np.array([[0.1, 0.5, 0.2, 0.2]]).T
x
```
Try to think why below two cells output the same values.
```
A@x
np.sum([A[:, i].reshape(-1, 1) * x[i] for i in range(A.shape[1])], axis=0)
```
# 2.5 Norms
```
import numpy as np
```
[The link](https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html) shows the norm functions implemented by numpy.
```
x = np.array([0, 1, -1, 2, 3, -4])
l2_x = np.linalg.norm(x, 2)
l2_x
```
Let's confirm it with our calculation.`**` in python allows you to write superscript with which you can specify the exponent. It's equivalent to `^` in some other mathematical languages.
```
l2_x_ = (x @ x) **(1/2)
l2_x
```
Let's test $L^1$ norm
```
np.linalg.norm(x, 1)
np.abs(x).sum()
```
Let's test $L^0$ norm
```
np.linalg.norm(x, 0)
len(x[x != 0])
```
Let's test Frobenius norm
```
X = np.array([[0, 1, -2], [-1, 0, 2], [2, 3, 0]])
np.linalg.norm(X, 'fro')
(X * X).sum()**(1/2)
```
# 2.6 Special Kinds of Matrices and Vectors
```
import numpy as np
```
The simplest diagonal matrices are identity matrices.
```
np.identity(3)
```
The `diag()` function converts a vector into a diagonal matrix.
```
np.diag([1,2,3])
```
If a matrix is given as an input instead of a vector, then it outputs a vector whose elements are the diagonal of the matrix.
```
A = np.random.randint(low=0, high=10, size=(3, 3))
A
np.diag(A)
```
Let's see how diagonal matrix product can save computation time. Ipython (Jupyter) has some nice magic commands. One of them is called timeit, which can be used to measure cell execution time.
```
a = np.random.randint(low=-5, high=5, size=100)
A = np.diag(a)
x = np.random.randint(low=-5, high=5, size=100)
%%timeit -n 100 -r 10
A @ x
%%timeit -n 100 -r 10
a @ x
```
The cell below still takes less time to execute although it includes converting a matrix into a diagonal vector.
```
%%timeit -n 100 -r 10
np.diag(A) @ x
```
A square diagonal matrix can its inverse only if every diagonal entry is nonzero
```
A = np.array([[1, 0, 0], [0, -2, 0], [0, 0, 3]])
np.linalg.inv(A)
A = np.array([[1, 0, 0], [0, 0, 0], [0, 0, 3]])
np.linalg.inv(A)
```
Let's create a symmetric matrix using a simple function.
Let's say that $\pmb{x}$ is a vector whose element is the location from the origin (1D)
```
x = np.random.randint(low=-5, high=5, size=3)
x
```
We'll create a zero matrix $\pmb{A}$, and fill in the numbers.
```
A = np.zeros(shape=(3,3))
# We'll loop over the rows and columns of the matrix.
for i in range(3):
for j in range(3):
A[i, j] = np.abs(x[i] - x[j])
A
A.T
```
Any vector can be converted into a unit vector by dividing every element by the $L^2$ norm of the vector.
```
x = np.random.standard_normal(size=10)
x
l2 = np.linalg.norm(x, 2)
l2
x = x / l2
x
np.linalg.norm(x, 2)
```
Orthogonality can be easily explained by plotting vectors in the vector space We need python package `matplotlib` for plotting.
One of the amazing things about Jupyter notebooks is that it can handle GUI backends very nicely without you having to worry about them. I mean it's running on a web browser after all...
```
import matplotlib.pyplot as plt
```
Vector $\pmb{a}$ (red) and vector $\pmb{b}$ (blue) are orthogonal since they are at a 90 degree angle to eachother.
```
a = 0.8*np.array([1/np.sqrt(2), 1/np.sqrt(2)])
b = 1.3*np.array([1/-np.sqrt(2), 1/np.sqrt(2)])
plt.figure(figsize=(5,5));
plt.ylim(-1, 1);
plt.xlim(-1, 1);
plt.plot([0, a[0]], [0, a[1]], 'r-');
plt.plot([0, b[0]], [0, b[1]], 'b-');
```
Also becuase their dot product is zero
```
a @ b
```
If the vectors not only are orthogonal but also have unit norm, we call them orthonormal.
```
a = np.array([1/np.sqrt(2), 1/np.sqrt(2)])
b = np.array([1/-np.sqrt(2), 1/np.sqrt(2)])
plt.figure(figsize=(5,5));
plt.ylim(-1, 1);
plt.xlim(-1, 1);
plt.plot([0, a[0]], [0, a[1]], 'r-');
plt.plot([0, b[0]], [0, b[1]], 'b-');
np.linalg.norm(a, 2)
np.linalg.norm(b, 2)
a@b
```
Here's a sample orthogonal matrix. If you remember the definition, it's not that difficult to create one.
```
A = np.array([[0, 1, 0], [-1, 0, 0], [0, 0, -1]])
A
A @ A.T
A.T @ A
np.linalg.inv(A)
A.T
```
# 2.7 Eigendecomposition
```
import numpy as np
import matplotlib.pyplot as plt
```
We will create eigendecomposition with the below example.
```
v1 = np.array([1/np.sqrt(2), 1/np.sqrt(2)])
v2 = np.array([1/np.sqrt(2), -1/np.sqrt(2)])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5));
fig.suptitle('Effect of eigenvectors and eigenvalues')
ax1.set_title('Before multiplication');
ax1.axis(xmin=-2, xmax=2, ymin=-2, ymax=2);
ax1.plot([0, v1[0]], [0, v1[1]], 'k-');
ax1.plot([0, v2[0]], [0, v2[1]], 'k-');
ax1.set(xlabel='x_0', ylabel='x_1');
ld1 = 2.5
ld2 = 0.5
v1_ = ld1 * v1
v2_ = ld2 * v2
ax2.set_title('After multiplication');
ax2.axis(xmin=-2, xmax=2, ymin=-2, ymax=2);
ax2.plot([0, v1_[0]], [0, v1_[1]], 'k-');
ax2.plot([0, v2_[0]], [0, v2_[1]], 'k-');
ax2.set(xlabel='x_0', ylabel='x_1');
ld1, ld2
V = np.stack([v1, v2], axis=1)
V
A = V @ np.diag([ld1, ld2]) @ V.T
A
```
numpy has a built in function that does eigendecomposition.
```
(ld1_, ld2_), V_ = np.linalg.eig(A)
```
Let's see if the eigenvalues and the eigenvectors correspond to what we started with.
```
ld1_, ld2_
V_
```
[Note that floating point numbers can not be represented exactly in computers.](https://en.wikipedia.org/wiki/IEEE_754)
# 2.8 Singular Value Decomposition
```
import numpy as np
```
Below is the example from [the wikipedia page](https://en.wikipedia.org/wiki/Singular_value_decomposition)
```
M = np.array([[1, 0, 0, 0, 2],
[0, 0, 3, 0, 0],
[0, 0, 0, 0, 0],
[0, 2, 0, 0, 0]])
U, S, V_transposed = np.linalg.svd(M)
V = V_transposed.T
U
S
V
```
Check if U is an orthogonal matrix.
```
U@U.T
U.T@U
```
Check if V is an orthogonal matrix.
```
(V@V.T).round(10)
(V.T@V).round(10)
```
# 2.9 The Moore-Penrose Pseudoinverse
```
import numpy as np
```
numpy.linalg package has the function `pinv()` to compute Moore-Penrose Psuedoinverse.
In the cell below, we will solve the linear equation $\pmb{Ax} = \pmb{b}$ for $\pmb{x}$, when the matrix $\pmb{A}$ has more columns than rows.
```
A = np.array([[1, -1, 2],
[1, 2, 1]])
b = np.array([2, -1])
A_pinv = np.linalg.pinv(A)
x = A_pinv @ b
x
```
Let's check that $\pmb{x}$ found by the psuedoinverse satisfies $\pmb{Ax} = \pmb{b}$
```
A@x
```
Note that $\tilde{\pmb{x}}$ below also satisfies the equation.
```
x_tilde = np.array([1, -1, 0])
A @ x_tilde
```
However this has the biggger $L^2$ norm value than that of $\pmb{x}$ found by SVD.
```
np.linalg.norm(x, 2), np.linalg.norm(x_tilde, 2)
```
Below cell is a case where the matrix $\pmb{A}$ has more columns than rows. But all of the columns of $\pmb{A}$ are linearly dependent.
```
A = np.array([[1, 3, -1],
[1, 3, -1]])
b = np.array([2, -1])
A_pinv = np.linalg.pinv(A)
x = A_pinv @ b
x
```
See that x found by the psuedoinverse does **NOT** satisfies $\pmb{Ax} = \pmb{b}$
```
A@x
b
```
This is becuase the linear sum of the columns of $\pmb{A}$ cannot make $\pmb{b}$. Unless $\pmb{b}$ happens to be in the same line
Below cell is a case where the matrix $\pmb{A}$ has more rows than columns. But all of the columns of $\pmb{A}$ are linearly independent.
```
A = np.array([[1, 3],
[1, 3],
[1, -1]])
b = np.array([2, -1, 3])
A_pinv = np.linalg.pinv(A)
x = A_pinv @ b
x
```
See that $\mathbf{x}$ found by the psuedoinverse does **NOT** satisfies $\pmb{Ax} = \pmb{b}$
```
A @ x
b
```
This is becuase the linear sum of the columns of $\pmb{A}$ cannot make $\pmb{b}$. In this case, using the pseudoinverse gives us the $\pmb{x}$ for which $\pmb{Ax}$ is as close as possible to $\pmb{b}$ in terms of Euclidean norm $\left\Vert \pmb{Ax}-\pmb{b}\right\Vert^2$
# 2.10 The Trace Operator
```
import numpy as np
```
Let's create a random matrix.
```
A = np.random.randint(low=0, high=10, size=(3, 4))
A
```
numpy has a `trace()` function.
```
np.trace(A)
```
The traceoperator is invariant to the transposed
```
np.trace(A), np.trace(A.T)
```
Frobenius norm of a matrix is the square root of the trace of $\pmb{A} \pmb{A}^T$
```
np.linalg.norm(A, 'fro')
np.sqrt(np.trace(A @ A.T))
np.sqrt(np.trace(A.T @ A))
```
The trace of a square matrix composed of many factors is also invariant to moving the last factor into the first position
```
A = np.random.standard_normal(size=(3,4))
B = np.random.standard_normal(size=(4,5))
C = np.random.standard_normal(size=(5,3))
np.trace(A@B@C)
np.trace(C@A@B)
np.trace(B@C@A)
```
# 2.11 The Determinant
```
import numpy as np
```
Determinant of a matrix is only defined when the matrix is square.
```
A = np.random.standard_normal(size=(3,3))
np.linalg.det(A)
```
Otherwise numpy will throw a warning
```
A = np.random.standard_normal(size=(3,4))
np.linalg.det(A)
```
The determinant of a matrix is equal to the product of all the eigen values of the matrix.
```
A = np.random.standard_normal(size=(5,5))
w, V = np.linalg.eig(A)
np.linalg.det(A)
np.prod(w)
```
# 2.12 Example: Principal Components Analysis
The mathematical derviation of PCA is not that easy (especially the reason why we use SVD or eigendecomposition on the covariance matrix, although the intuition behind it and getting their values are pretty easy. [This](https://www.youtube.com/watch?v=rng04VJxUt4) is a great explanation of PCA by Andrew Ng.
```
import numpy as np
```
We'll use boston house-prices dataset as a toy example.
```
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
X_original = load_boston()['data']
```
The data has 506 samples and each sample has 13 features. In machine learning, we call this type of data "structured" data, where every data sample has a fixed dimensionaltiy (e.g. 13) and the features are somewhat self-explanatory.
```
X_original.shape
```
Let's try reducing the original number of dimensions (13) to something smaller, using with PCA
First step for PCA is to have every feature dimension be zero-mean and optionally feature scaling can be done. I normally do feature scaling too, to avoid some features from dominating the variance.
```
mean = X_original.mean(axis=0)
sigma = X_original.std(axis=0)
# z-scaling
X = (X_original -mean) / sigma
X.mean(axis=0)
X.std(axis=0)
X_original.shape, mean.shape, sigma.shape
```
When the mean value of each feature is 0, the covariance matrix is nothing but the matrix product of its transposed and itself. Actually the real covariance matrix should include scaling too (dividing by the number of observations), but we don't have to do that here.
```
cov_X = (X.T @ X)
cov_X.round()
cov_X.shape
```
The principal components can be found by computing the eigenvectors of the covariance matrix. You can use both eigendecomposition and SVD to achieve this. In the below example, we'll use SVD.
Let's say that the SVD of $\pmb{X}$ gives us $\pmb{UDV^{T}}$. Then the SVD of the covariance matrix, $\pmb{X^{T} X}$, will give us $\pmb{X^T X = V D^T D V^T}$. This looks a lot like the eigenvalue decomposition. We can now consider $\pmb{V}$ and $\pmb{D^{2}}$ as the the eigenvectors and squared eigenvalues corresopnding to their eigenvectors.
The proportion of the variance that each eigenvector represents can be calculated by dividing the eigenvalue corresponding to that eigenvector by the sum of all eigenvalues.
```
V, D_squared, V_transposed = np.linalg.svd(cov_X)
```
We can plot $\pmb{D}^{2}$ to get the eigenvalues, which explains the variance.
```
eigenvalues = D_squared
eigenvalues / eigenvalues.sum()
plt.plot(eigenvalues / eigenvalues.sum());
```
This means that first the new axis can already explain about 47% of the variance. As an exercise, when normalizing the original data, try removing the feature scaling and see what happens when we plot the eigenvalues.
The "*encoding*" of the original data can be simply done by matrix multiplication. We can create the encoder by taking the column vectors (eigenvectors of the covariance matrix). Below encoder will take the first 5 columns, which explains about 80% of the variances.
```
num_features = 5
Encoder = V[:, :num_features]
(eigenvalues / eigenvalues.sum())[:num_features].sum()
Encoder.shape
```
Below line will encode the data so that the number of features is reduced to 5. This means that every 13 dimensional data point will now have 5 dimensions (Each one of them is projected to a lower dimensional space)
```
X_encoded = X @ Encoder
X_encoded.shape
```
Reconstruction (decoding) can be done by below line.
```
Decoder = Encoder.T
X_decoded = X_encoded @ Decoder
X_decoded.shape
```
Since the encoding is lossy, the decoding cannot 100% reconstruct the original data. See and compare.
FYI, just because we did a dimensionality reduction of the data, it doesn't always mean that the encoding is lossy. There are many other encoding schemes where a dimensionality reduction is loseless. And of course, this can also depend on data.
```
X_decoded[0, :]
X[0, :]
```
Try changing the num_features to 13 and see what happens to the reconstruction.
PCA is very simple yet important concept in machine learning. It might not be as powerful as other encoder-decoders since it's only a linear transformation.
But the core concept and the reason why we do it already tells us a lot what and why we do machine learning.
PCA is already well implemented in many machine learning libraries. I'll show you how simple it is by using scikit-learn. The below codes are from [here](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html) and [here](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html)
We'll use boston house-prices dataset as a toy example.
```
from sklearn.datasets import load_boston
X_original = load_boston()['data']
# z-scaling
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_original)
X = scaler.transform(X_original)
X.mean(axis=0)
X.std(axis=0)
# PCA
from sklearn.decomposition import PCA
num_features = 5
pca = PCA(n_components=num_features)
pca.fit(X)
pca.explained_variance_ratio_.sum()
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
import os
import pickle
from glob import glob
import re
from concurrent.futures import ProcessPoolExecutor, as_completed
import numpy as np
import pandas as pd
#from tqdm import tqdm
from scipy import stats
from sklearn.metrics import pairwise_distances
import settings as conf
# from src.data import PhenoInfo, PhenoResults, get_all_tissues, get_genes
from results.multixcan import MXPhenoInfo, MXPhenoResults
from utils import is_number, chunker
# genes_associations_dir = os.path.join(constants.PREPROCESSED_BASED_DIR, 'gene_associations')
# smultixcan_gene_association_dirs = os.path.join(genes_associations_dir, 'mashr')
```
# Load metadata
```
with open(os.path.join(conf.GENES_METADATA_DIR, 'genes_mapping_simplified-0.pkl'), 'rb') as f:
genes_mapping_0 = pickle.load(f)
with open(os.path.join(conf.GENES_METADATA_DIR, 'genes_mapping_simplified-1.pkl'), 'rb') as f:
genes_mapping_1 = pickle.load(f)
```
# Load MultiXcan associations
```
genes_associations_filename = os.path.join(conf.GENE_ASSOC_DIR, 'smultixcan-mashr-pvalues.pkl.xz')
display(genes_associations_filename)
genes_associations = pd.read_pickle(genes_associations_filename)
display(genes_associations.shape)
display(genes_associations.head())
```
# Load PheWAS catalog
```
phewas_catalog = pd.read_csv(os.path.join(conf.DATA_DIR, 'phewas-catalog.csv.gz'), dtype={'phewas code': str})
phewas_catalog.shape
phewas_catalog[phewas_catalog['phewas code'].isna()].head()
phewas_catalog[phewas_catalog['gene_name'].isna()].head()
phewas_catalog[phewas_catalog['gene_name'].isna()].shape
phewas_catalog = phewas_catalog.dropna(subset=['gene_name', 'phewas code'])
phewas_catalog.shape
phewas_catalog['gene_name'].unique().shape
phewas_catalog['phewas code'].unique().shape
phewas_catalog = phewas_catalog.assign(gene_id=phewas_catalog['gene_name'].apply(lambda x: genes_mapping_1[x] if x in genes_mapping_1 else None))
phewas_catalog = phewas_catalog.dropna(subset=['gene_name', 'gene_id', 'phewas code'])
phewas_catalog.shape
phewas_catalog.head()
phewas_catalog.sort_values('phewas phenotype').head()
```
# Genes in common
```
shared_gene_ids = \
set(phewas_catalog['gene_id'].values)\
.intersection(genes_associations.index)
len(shared_gene_ids)
```
# HPO to MIM
```
hpo_to_mim = pd.read_csv(os.path.join(conf.DATA_DIR, 'hpo-to-omim-and-phecode.csv.gz'), dtype={'phecode': str})
hpo_to_mim.shape
hpo_to_mim.head()
```
# Load silver standard to map from UKB to MIM
```
omim_silver_standard = pd.read_csv(os.path.join(conf.DATA_DIR, 'omim_silver_standard.tsv'), sep='\t')
ukb_to_mim_map = omim_silver_standard[['trait', 'pheno_mim']].dropna()
ukb_to_mim_map.shape
ukb_to_mim_map.head()
```
# Read gwas2gene results
```
from glob import glob
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
pandas2ri.activate()
readRDS = robjects.r['readRDS']
f_files = glob(os.path.join(conf.OMIM_SILVER_STANDARD_GWAS_TO_GENE_DIR, '*.rds'))
display(len(f_files))
if len(f_files) != len(omim_silver_standard['trait'].unique()):
print(f'WARNING: some files are not there. {len(omim_silver_standard.trait.unique())} expected, {len(f_files)} found.')
gwas2genes_results = {}
for f in f_files:
f_base = os.path.basename(f)
f_code = f_base.split('.')[0]
#print(f_base)
rds_contents = readRDS(f)
if len(rds_contents[1]) > 0:
f_gene_list = list(rds_contents[1][0].iter_labels())
else:
print(f'{f_code}: empty')
f_gene_list = []
gwas2genes_results[f_code] = f_gene_list
gwas2gene_all_genes = []
for k in gwas2genes_results.keys():
gwas2gene_all_genes.extend(gwas2genes_results[k])
display(len(gwas2gene_all_genes))
gwas2gene_all_genes = set(gwas2gene_all_genes)
display(len(gwas2gene_all_genes))
gwas2gene_all_genes = shared_gene_ids.intersection(gwas2gene_all_genes)
display(len(gwas2gene_all_genes))
pd.Series(list(gwas2gene_all_genes)).head()
```
# Merge
```
# mim to phecode
_tmp = pd.merge(ukb_to_mim_map, hpo_to_mim[['phecode', 'dID']], left_on='pheno_mim', right_on='dID', how='inner').drop(columns=['dID'])
display(_tmp.shape)
# phecode to phewas catalog
_tmp = pd.merge(_tmp, phewas_catalog[['phewas code', 'gene_name', 'gene_id']], left_on='phecode', right_on='phewas code', how='inner').drop(columns=['phewas code'])
display(_tmp.shape)
_tmp.head()
# just wondering if this is the right way... but I don't think so, I want just a ukb-trait to gene map and see how many are significant
#_tmp.drop_duplicates(subset=['trait', 'phecode', 'gene_id']).shape
_tmp = _tmp.drop_duplicates(subset=['trait', 'gene_id'])
_tmp.shape
from entity import Trait
_tmp = _tmp.assign(ukb_code=[Trait(full_code=t).code for t in _tmp['trait'].values])
_tmp.head()
phewas_ukb_results = _tmp
```
### Keep genes per trait that we can find in GWAS
```
trait_genes_to_keep = []
# idx = 0
for trait, data in phewas_ukb_results.groupby(['trait']):
ukb_trait_code = data.ukb_code.unique()[0]
if ukb_trait_code in gwas2genes_results.keys():
ukb_traits_genes = gwas2genes_results[ukb_trait_code]
else:
print(f'WARNING: for ukb trait "{trait}", no genes were found')
continue
ukb_traits_genes = set(ukb_traits_genes)
ukb_traits_genes = ukb_traits_genes.intersection(gwas2gene_all_genes)
idx_to_keep = data[data['gene_id'].isin(ukb_traits_genes)].index.tolist()
trait_genes_to_keep.extend(idx_to_keep)
display(len(trait_genes_to_keep))
display(trait_genes_to_keep[:5])
phewas_ukb_results = phewas_ukb_results.loc[trait_genes_to_keep]
phewas_ukb_results.head()
phewas_ukb_results = phewas_ukb_results.assign(multixcan_pval=np.nan)
for i, d in phewas_ukb_results.iterrows():
gene_id = d['gene_id']
if gene_id not in genes_associations.index:
continue
ukb_fullcode = d['trait']
gene_trait_pval = genes_associations.loc[gene_id, ukb_fullcode]
phewas_ukb_results.loc[i, 'multixcan_pval'] = gene_trait_pval
phewas_ukb_results.shape
phewas_ukb_results = phewas_ukb_results.dropna(subset=['multixcan_pval'])
phewas_ukb_results.shape
phewas_ukb_results.head()
phewas_ukb_results.multixcan_pval.describe().apply(str)
phewas_ukb_results[phewas_ukb_results['trait'] == '1200-Sleeplessness_insomnia'].shape
```
### Count
```
total_phewas_catalog = phewas_ukb_results.shape[0]
display(total_phewas_catalog)
# 0.05
hits = phewas_ukb_results[phewas_ukb_results['multixcan_pval'] < 0.05].shape[0]
display(hits)
(hits / total_phewas_catalog) * 100.0
# 0.01
hits = phewas_ukb_results[phewas_ukb_results['multixcan_pval'] < 0.01].shape[0]
display(hits)
(hits / total_phewas_catalog) * 100.0
SIGNIFICANT_PVALUE = 0.05 / total_phewas_catalog
display(SIGNIFICANT_PVALUE)
# pvalue threshold
hits = phewas_ukb_results[phewas_ukb_results['multixcan_pval'] < SIGNIFICANT_PVALUE].shape[0]
display(hits)
(hits / total_phewas_catalog) * 100.0
```
| github_jupyter |
# 1. 2D Linear Convection
We consider the 1d linear Convection equation, under a constant velocity
$$
\partial_t u + \mathbf{a} \cdot \nabla u - \nu \nabla^2 u = 0
$$
```
# needed imports
from numpy import zeros, ones, linspace, zeros_like
from matplotlib.pyplot import plot, contourf, show, colorbar
%matplotlib inline
# Initial condition
import numpy as np
u0 = lambda x,y: np.exp(-(x-.3)**2/.05**2)*np.exp(-(y-.3)**2/.05**2)
ts = linspace(0., 1., 401)
x,y = np.meshgrid(ts,ts)
u = u0(x,y)
contourf(x,y, u); colorbar() ; show()
```
### Time scheme
$$\frac{u^{n+1}-u^n}{\Delta t} + \mathbf{a} \cdot \nabla u^{n+1} - \nu \nabla^2 u_{n+1} = 0 $$
$$ \left(I + \Delta t \mathbf{a} \cdot \nabla - \nu \nabla^2 \right) u^{n+1} = u^n $$
### Weak formulation
$$
\langle v, u^{n+1} \rangle + \Delta t ~ \langle v, \mathbf{a} \cdot \nabla u^{n+1} \rangle + \nu ~\Delta t~ \langle \nabla v, \nabla u^{n+1} \rangle = \langle v, u^n \rangle
$$
if we assume $\mathbf{a} = \left( a_1, a_2 \right)^T$ is a constant, then our weak formulation writes
$$
\langle v, u^{n+1} \rangle - \Delta t ~ \langle \mathbf{a} \cdot \nabla v , u^{n+1} \rangle + \nu ~ \Delta t~\langle \nabla v, \nabla u^{n+1} \rangle = \langle v, u^n \rangle
$$
expending $u^n$ over the fem basis, we get the linear system
$$A U^{n+1} = M U^n$$
where
$$
M_{ij} = \langle b_i, b_j \rangle
$$
$$
A_{ij} = \langle b_i, b_j \rangle - \Delta t ~ \langle \mathbf{a} \cdot \nabla b_i, b_j \rangle + \nu ~\Delta t~ \langle \nabla b_i , \nabla b_j \rangle
$$
## Abstract Model using SymPDE
```
from sympde.core import Constant
from sympde.expr import BilinearForm, LinearForm, integral
from sympde.topology import ScalarFunctionSpace, Square, element_of
from sympde.calculus import grad, dot
from sympy import Tuple
# ... abstract model
domain = Square()
V = ScalarFunctionSpace('V', domain)
x,y = domain.coordinates
u,v = [element_of(V, name=i) for i in ['u', 'v']]
a1 = Constant('a1')
a2 = Constant('a2')
dt = Constant('dt')
nu = Constant('nu')
a = Tuple(a1,a2)
# bilinear form
expr = v*u + dt* dot(a, grad(u))*v + nu*dt*dot(grad(u), grad(v))
a = BilinearForm((u,v), integral(domain , expr))
# bilinear form for the mass matrix
expr = u*v
m = BilinearForm((u,v), integral(domain , expr))
# linear form for initial condition
from sympy import exp
expr = exp(-(x-.3)**2/.05**2)*exp(-(y-.3)**2/.05**2)*v
l = LinearForm(v, integral(domain, expr))
```
## Discretization using Psydac
```
from psydac.api.discretization import discretize
a1 = 1. ; a2 = 0. # wavespeed
nu = .03 # viscosity
T = 0.2 # T final time
dt = 0.001
niter = int(T / dt)
degree = [3,3] # spline degree
ncells = [64,64] # number of elements
# Create computational domain from topological domain
domain_h = discretize(domain, ncells=ncells, comm=None)
# Discrete spaces
Vh = discretize(V, domain_h, degree=degree)
# Discretize the bilinear forms
ah = discretize(a, domain_h, [Vh, Vh])
mh = discretize(m, domain_h, [Vh, Vh])
# Discretize the linear form for the initial condition
lh = discretize(l, domain_h, Vh)
# assemble matrices and convert them to scipy
M = mh.assemble().tosparse()
A = ah.assemble(a1=a1, a2=a2, nu=nu, dt=dt).tosparse()
# assemble the rhs and convert it to numpy array
rhs = lh.assemble().toarray()
from scipy.sparse.linalg import gmres
# L2 projection of the initial condition
un, status = gmres(M, rhs, tol=1.e-8, maxiter=5000)
from utilities.plot import plot_field_2d
nbasis = [W.nbasis for W in Vh.spaces]
plot_field_2d(Vh.knots, Vh.degree, un.reshape(nbasis)) ; colorbar() ; show()
for i in range(0, niter):
b = M.dot(un)
un, status = gmres(A, b, tol=1.e-8, maxiter=5000)
nbasis = [W.nbasis for W in Vh.spaces]
plot_field_2d(Vh.knots, Vh.degree, un.reshape(nbasis)) ; colorbar() ; show()
```
| github_jupyter |
# Предсказание временных рядов
## Библиотеки
```
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import gridspec
from tqdm.notebook import tqdm
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import scipy
import json
import sys
import re
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import AgglomerativeClustering
from sklearn.manifold import MDS
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D
import scipy as sp
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook as tqdm
from scipy.special import softmax
import pandas as pd
from sklearn.preprocessing import scale
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.decomposition import PCA
from scipy.interpolate import interp1d
import math
```
### Вспомагательные функции
```
def RandomFunction(x, n=2):
N = np.arange(1, n + 1, 1)
A = np.random.randn(n)
B = np.random.randn(n)
A0 = np.random.randn(1)
y = 0.5*np.ones_like(x)*A0
for n, a, b in zip(N, A, B):
y += a*np.sin(n*x) + b*np.cos(n*x)
return y
def GenerateImpulses(n = 20, T = 2, k = 2, function = np.sin):
t = int(T)//2
x = np.linspace(start = 0, stop = T*np.pi, num = n)
List_y = []
for i in range(k):
y_temp = 5*np.random.randn()*function(x + np.random.rand()*2*np.pi)
List_y.append(y_temp)
y = np.array(List_y[0])
y2 = List_y[np.random.randint(0, k)]
for i in range(0, t):
if np.random.rand() < 0.1:
y2 = List_y[np.random.randint(0, k)]
ind = np.where(x <= 2*(i + 1)*np.pi)
ind = np.where(x[ind] > 2*i*np.pi)
y[ind] = y2[ind]
return y
def GeneratorOfTimeSeries(n = 100, m = 16384, k = 20):
T1 = []
T2 = []
T3 = []
for _ in range(m):
numPi = 80 + np.random.randint(0, 20)
numPi = n//k
function = np.sin
if np.random.rand() < -4*0.5:
function = RandomFunction
series = GenerateImpulses(n = n, T = numPi, k = np.random.randint(K, K+1), function=function)
T1.append(series + 0.5*np.random.randn(n))
T1 = np.asarray(T1)
return np.reshape(T1, [T1.shape[0], T1.shape[1], 1])
def return_h(input, i, l = 10):
return np.sum(input[:, i:i+l, :], axis = -1)
def return_phase_track(input, l = 10):
"""
input has a shape [batch_size, time_len, 1]
"""
phase_track = np.zeros([input.shape[0], input.shape[1] - l, l])
for i in range(0, input.shape[1] - l):
phase_track[:, i, :] = return_h(input, i, l)
return phase_track[0]
def local_basis(phase_track, m = 2, T = 20):
result_pca_1 = phase_track
List_of_basis_vector = []
List_of_basis_vector_s = []
List_of_basis_vector_c = []
model_pca = PCA(n_components=2)
for n in range(T, result_pca_1.shape[0] - T, 1):
if n-T >- 0:
arr = result_pca_1[n-T:n+T]
else:
arr = result_pca_1[:n]
model_pca_answ = model_pca.fit_transform(arr)
List_of_basis_vector_s.append(model_pca.singular_values_)
List_of_basis_vector_c.append(model_pca_answ[-1])
List_of_basis_vector.append(model_pca.components_)
List_of_basis_vector = np.array(List_of_basis_vector)
List_of_basis_vector_s = np.array(List_of_basis_vector_s)
List_of_basis_vector_c = np.array(List_of_basis_vector_c)
return List_of_basis_vector, List_of_basis_vector_s, List_of_basis_vector_c
def get_pairwise_matrix(List_of_basis_vector, List_of_basis_vector_s, List_of_basis_vector_c):
Volum = np.zeros([2, List_of_basis_vector.shape[0], List_of_basis_vector.shape[0]])
cos_beta = np.abs(List_of_basis_vector[:, 0, :]@List_of_basis_vector[:, 1, :].T)
cos_alpha = np.array(np.diagonal(cos_beta))
cos_gamma = np.abs(List_of_basis_vector[:, 1, :]@List_of_basis_vector[:, 1, :].T)
cos_beta[np.where(cos_beta > 1-10**(-10))] = 1-10**(-10)
cos_alpha[np.where(cos_alpha > 1-10**(-10))] = 1-10**(-10)
cos_gamma[np.where(cos_gamma > 1-10**(-10))] = 1-10**(-10)
cos_beta[np.where(cos_beta < 10**(-10))] = 0
cos_alpha[np.where(cos_alpha < 10**(-10))] = 0
cos_gamma[np.where(cos_gamma < 10**(-10))] = 0
temp_a = np.sqrt(1-cos_beta**2)
cos_A = np.abs((cos_alpha.reshape([-1,1]) - cos_gamma*cos_beta)/(np.sqrt(1-cos_gamma**2)*np.sqrt(1-cos_beta**2)))
h = temp_a*np.sqrt(1-cos_A**2)
Volum[0] = h* np.sqrt(1-cos_gamma**2)
cos_beta = np.abs(List_of_basis_vector[:, 0, :]@List_of_basis_vector[:, 0, :].T)
cos_gamma = np.abs(List_of_basis_vector[:, 1, :]@List_of_basis_vector[:, 0, :].T)
cos_alpha = np.array(np.diagonal(cos_gamma))
cos_beta[np.where(cos_beta > 1-10**(-10))] = 1-10**(-10)
cos_alpha[np.where(cos_alpha > 1-10**(-10))] = 1-10**(-10)
cos_gamma[np.where(cos_gamma > 1-10**(-10))] = 1-10**(-10)
cos_beta[np.where(cos_beta < 10**(-10))] = 0
cos_alpha[np.where(cos_alpha < 10**(-10))] = 0
cos_gamma[np.where(cos_gamma < 10**(-10))] = 0
temp_a = np.sqrt(1-cos_beta**2)
cos_A = (cos_alpha.reshape([-1,1]) - cos_gamma*cos_beta)/(np.sqrt(1-cos_gamma**2)*np.sqrt(1-cos_beta**2))
h = temp_a*np.sqrt(1-cos_A**2)
Volum[1] = h* np.sqrt(1-cos_gamma**2)
vol = np.max(Volum, axis = 0)
for i in range(vol.shape[0]):
for j in range(vol.shape[0]):
vol[i,j] = max(vol[i,j], vol[j,i])
dist = np.sqrt((List_of_basis_vector_s[:, :1] - List_of_basis_vector_s[:, :1].T)**2 + (List_of_basis_vector_s[:, 1:2] - List_of_basis_vector_s[:, 1:2].T)**2)
dist = dist/np.max(dist)
full_dist = np.sqrt(vol**2+dist**2)
return full_dist
def find_points(points, line_point):
"""
points have a shape [N x 2]
line_point has a shape [2 x 1]
"""
List_of_points_plus = []
List_of_points_minus = []
List_of_t_plus = []
List_of_t_minus = []
for i in range(len(points) - 1):
if (line_point[1]*points[i][0] - line_point[0]*points[i][1] < 0) and(line_point[1]*points[i+1][0] - line_point[0]*points[i+1][1] > 0):
List_of_points_plus.append(points[i])
List_of_t_plus.append(i)
if (line_point[1]*points[i][0] - line_point[0]*points[i][1] > 0) and(line_point[1]*points[i+1][0] - line_point[0]*points[i+1][1] < 0):
List_of_points_minus.append(points[i])
List_of_t_minus.append(i)
return np.array(List_of_points_plus), np.array(List_of_points_minus), np.array(List_of_t_plus), np.array(List_of_t_minus)
def find_distance(points, line_point):
"""
points have a shape [N x 2]
line_point has a shape [2 x 1]
"""
sum_distance = 0
normal = np.array([line_point[1], -line_point[0]])
normal = normal/np.sqrt((normal*normal).sum())
for p in points:
sum_distance += ((normal*p).sum())
return sum_distance
def find_segment(X, T):
phase_track = return_phase_track(X, T)
model = PCA(n_components=2)
ress = model.fit_transform(phase_track)
ress[:, 0] = ress[:, 0]/np.sqrt(((ress[:, 0]**2).mean()))
ress[:, 1] = ress[:, 1]/np.sqrt(((ress[:, 1]**2).mean()))
Phi = np.linspace(-np.pi, np.pi, 200)
All_List = np.array(list(map(lambda phi: find_points(ress, np.array([np.sin(phi), np.cos(phi)])), Phi)))
List_of_std = []
for l, phi in zip(All_List, Phi):
List_of_std.append(find_distance(np.vstack([l[0], l[1]]), np.array([np.sin(phi), np.cos(phi)])))
List_of_std = np.array(List_of_std)
phi = Phi[np.argmin(List_of_std)]
line_point = np.array([np.sin(phi), np.cos(phi)])
List_of_points_plus, List_of_points_minus, List_of_t_plus, List_of_t_minus = find_points(ress, line_point)
return List_of_points_plus, List_of_points_minus, List_of_t_plus, List_of_t_minus, line_point, ress
def segmentation(X_all, prediction_vector, T):
List_of_point = []
List_of_All = []
for t in np.unique(prediction_vector):
ind = np.where(prediction_vector == t)[0]
X = X_all[:, ind, :]
List_of_t = np.arange(0, X.shape[1], 1)
List_of_points_plus, List_of_points_minus, List_of_t_plus, List_of_t_minus, line_point, ress = find_segment(X, T)
List_of_All.append([X, List_of_t, List_of_points_plus, List_of_points_minus, List_of_t_plus, List_of_t_minus, line_point, ress])
List_of_point.append((np.where(prediction_vector == t)[0])[List_of_t_minus])
return List_of_All, List_of_point
def normalizer(x, t, n = None):
if n == None:
t_new = np.arange(np.min(t), np.max(t), 0.01)
else:
t_new = np.linspace(np.min(t), np.max(t), n, endpoint=True)
f = interp1d(t, x, kind='cubic')
return f(t_new)
def sort_prediction(prediction_vector):
prediction_vector += 1000
iterator = 0
need = np.where(prediction_vector >= 1000)[0]
while len(need) > 0:
prediction_vector[np.where(prediction_vector == prediction_vector[need[0]])] = iterator
iterator += 1
need = np.where(prediction_vector >= 1000)[0]
return prediction_vector
```
## Авторегрессия
Задан временной ряд:
$$
\mathbf{y} = [y_0, y_i, \cdots, y_t],
$$
где $t$ число известных точек временного ряда.
Требуется построить предсказательную модель:
$$
\hat{y}_{t+d} = f_{t, d}\bigr(\mathbf{y}, \mathbf{w}\bigr)
$$
Самое простое решение это линейная модель авторегрессии:
$$
\hat{y}_{t+1}\bigr(w\bigr) = \sum_{j=0}^{n-1}w_jy_{t-j}
$$
В чем плюсы? Легко решать! Простая задача линейной регрессии, а имено в качестве признакового описания:
$$
\mathbf{X} = \begin{bmatrix}
y_{t-1} & \cdots & y_{t-n}\\
\cdots & \cdots & \cdots\\
y_{n-1} & \cdots & y_{0}\\
\end{bmatrix}
$$
В качестве целевой переменной:
$$
\mathbf{y} = \begin{bmatrix}
y_{t}\\
\cdots\\
y_{n}\\
\end{bmatrix}
$$
Классичиская задача оптимизации:
$$
||\mathbf{X}\mathbf{w} - \mathbf{y}|| \to \min_{\mathbf{w}}
$$
```
fig = plt.figure(figsize=(20,4))
np.random.seed(0)
points = np.arange(400)
series = RandomFunction(points, n=100)
plt.plot(series, '-o')
plt.show()
n = 100
X = np.zeros(shape=(len(series)-n, n))
y = np.zeros(shape=(len(series)-n, 1))
y = series[n:len(series)]
for j in range(len(series)-n):
X[j] = series[j:j+n]
X_train = X[:-100]
y_train = y[:-100]
X_test = X[-100:]
y_test = y[-100:]
w = np.linalg.inv(X_train.T@X_train)@X_train.T@y_train
fig = plt.figure(figsize=(20,4))
plt.plot(points, series, '-.')
plt.plot(points[n:len(series)-100], X_train@w, '-o')
plt.plot(points[-100:], X_test@w, '-o')
plt.show()
```
#### Эксперимент по изменению $n$
```
for n in [30, 50, 100, 150, 200]:
X = np.zeros(shape=(len(series)-n, n))
y = np.zeros(shape=(len(series)-n, 1))
y = series[n:len(series)]
for j in range(len(series)-n):
X[j] = series[j:j+n]
X_train = X[:-100]
y_train = y[:-100]
X_test = X[-100:]
y_test = y[-100:]
w = np.linalg.inv(X_train.T@X_train)@X_train.T@y_train
fig = plt.figure(figsize=(20,4))
plt.plot(points, series, '-.')
plt.plot(points[n:len(series)-100], X_train@w, '-o')
plt.plot(points[-100:], X_test@w, '-o')
plt.title('$n={}$'.format(n))
plt.show()
```
Хм, почему так? Ответ - мультиколлинеарность!
## Экспоненциальное среднее
Модель:
$$
\hat{y}_{t+1} = \hat{y}_{t} + \alpha_t\left(y_t - \hat{y}_t\right).
$$
```
np.random.seed(0)
points = np.arange(400)
series = RandomFunction(points, n=100)
fig = plt.figure(figsize=(20,4))
plt.plot(series, '-o')
plt.show()
series_hat = [series[0]]
alpha = 0.3
for t in range(len(series)):
series_hat.append(series_hat[t] + alpha*(series[t]- series_hat[t]))
fig = plt.figure(figsize=(20,4))
plt.plot(series, '-')
plt.plot(series_hat, '-o')
plt.show()
for alpha in [0.1, 0.3, 0.5, 0.7, 1.0]:
series_hat = [series[0]]
for t in range(len(series)):
series_hat.append(series_hat[t] + alpha*(series[t]- series_hat[t]))
fig = plt.figure(figsize=(20,4))
plt.plot(series, '-')
plt.plot(series_hat, '-o')
plt.title('$\gamma={}$'.format(alpha))
plt.show()
```
## Кластеризация временных рядов
**Grabovoy A.V., Strijov V.V. Quasi-periodic time series clustering for human activity recognition // Lobachevskii Journal of Mathematics, 2020, 41 : 333-339**
Задан временной ряд
$$
\textbf{x} \in \mathbb{R}^{N},
$$
где $N$ число точек временного ряда. Он состоит из последовательности сегментов:
$$
\textbf{x} = [\textbf{v}_1, \textbf{v}_2, \cdots, \textbf{v}_M],
$$
где $\textbf{v}_i$ некоторый сегмент из множества сегментов $\mathbf{V},$ которые встречаются в данном ряде.
Причем для всех $i$ либо $[\textbf{v}_{i-1},\textbf{v}_{i}]$ либо $[\textbf{v}_{i},\textbf{v}_{i+1}]$ является цепочкой действий. Пусть множество $\mathbf{V}$ удовлетворяет следующим свойствам:
$$
\left|\mathbf{V}\right| = K, \quad \textbf{v} \in \mathbf{V}~\left|\textbf{v}\right| \leq T,
$$
где $\left|\mathbf{V}\right|$ число различных действий в множестве сегментов $\mathbf{V},$ $\left|\textbf{v}\right|$ длина сегмента, а $K$ и $T$ это число различных действий во временном ряде и длина максимального сегмента соответсвенно.
Рассматривается отображение
$$
a : t \to \mathbb{Y} = \{1,\cdots, K\},
$$
где $t \in \{1,\cdots, N\}$ некоторый момент времени, на котором задан временной ряд.
Требуется, чтобы отображение $a$ удовлетворяло следующим свойствам:
$$
\begin{cases}
a\left(t_1\right) = a\left(t_2\right), & \text{если в моменты } t_1, t_2 \text{ совершается один тип действий}\\
a\left(t_1\right) \not= a\left(t_2\right), & \text{если в моменты } t_1, t_2 \text{ совершаются разные типы действий }
\end{cases}
$$
### Визуализация основной идеи
```
data = pd.read_csv('https://raw.githubusercontent.com/andriygav/TimeSeriesClustering/master/code/SyntheticData/2_patern/1.csv')
X_intro = (data.values[1150:1600]).reshape([1,-1,1])
List_of_point = [np.array([15, 54, 95, 135, 175]), np.array([219, 259, 299, 339, 379, 419])]
phase_track_intro = return_phase_track(X_intro[:, 0:100, :], 20)
model = PCA(n_components=2)
basis_a = model.fit(phase_track_intro).components_
res_a = model.transform(phase_track_intro)
phase_track_intro = return_phase_track(X_intro[:, 300:400, :], 20)
model = PCA(n_components=2)
basis_b = model.fit(phase_track_intro).components_
res_b = model.transform(phase_track_intro)
alpha_1 = (basis_a[0]*basis_b[0]).sum()
alpha_2 = (basis_a[1]*basis_b[0]).sum()
beta_1 = (basis_a[0]*basis_b[1]).sum()
beta_2 = (basis_a[1]*basis_b[1]).sum()
a_1 = np.array([1, 0, 0])
a_2 = np.array([0, 1, 0])
b_1 = np.array([alpha_1, alpha_2, np.sqrt(1- alpha_1**2- alpha_2**2)])
b_1 = b_1/np.sqrt((b_1**2).sum())
b_2 = np.array([beta_1, beta_2, (-alpha_1*beta_1-alpha_2*beta_2)/np.sqrt(1- alpha_1**2- alpha_2**2)])
b_2 = b_2/np.sqrt((b_2**2).sum())
normal_1 = np.array([0,0,1])
normal_2 = np.cross(b_1, b_2)
point = np.array([1, 1, 1])
ress_a = res_a[:,0].reshape([-1,1])*a_1.reshape([1,-1]) + res_a[:,1].reshape([-1,1])*a_2.reshape([1,-1])
ress_b = res_b[:,0].reshape([-1,1])*b_1.reshape([1,-1]) + res_b[:,1].reshape([-1,1])*b_2.reshape([1,-1])
fig = plt.figure(figsize=(10,10));
marker = ['^', 's', 'v', 'D', 'P']
color = ['orange', 'green', 'red', 'yelow', 'blue']
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0], projection='3d');
xx, yy = np.meshgrid(range(-100, 100), range(-100, 100))
z_1 = (-normal_1[0] * xx - normal_1[1] * yy + point.dot(normal_1)) * 1./normal_1[2]
ax.plot_surface(xx, yy, z_1, alpha = 0.2, color = color[0])
ax.plot(ress_a[:,0] , ress_a[:,1] , ress_a[:,2], "-", marker = marker[0], color=color[0], label = 'Phase trajectory for type 1')
z_2 = (-normal_2[0] * xx - normal_2[1] * yy +point.dot(normal_2)) * 1./normal_2[2]
ax.plot_surface(xx, yy, z_2, alpha = 0.2, color = color[1])
ax.plot(ress_b[:, 0] , ress_b[:, 1] , ress_b[:, 2], "-", marker = marker[1], color=color[1], label = 'Phase trajectory for type 2')
ax.view_init(15, -50)
ax.legend(loc = 'best')
ax.xaxis.set_ticks(np.arange(-100, 101, 50))
ax.yaxis.set_ticks(np.arange(-100, 101, 50))
ax.zaxis.set_ticks(np.arange(-40, 41, 20))
ax.set_title('(b)', y=-0.25)
plt.subplots_adjust(wspace=0.05, hspace=0.2)
plt.show()
```
### Эксперимент по сегментации
```
data = pd.read_csv('https://raw.githubusercontent.com/andriygav/TimeSeriesClustering/master/code/RealData/2.csv')
T = 40
K = 2
X_test = data.values[100:1000, 2:3].reshape([1,-1,1])
List_of_x = np.arange(T, X_test[0].shape[0] - 2*T)
plt.figure(figsize=(12, 6))
_ = plt.plot(X_test[0], '-o')
plt.xlabel('Time $t$, $sec$')
plt.ylabel('Acceleration $x$, $m/sec^2$')
plt.grid()
plt.show()
phase_track = return_phase_track(X_test, T)
List_of_basis_vector, List_of_basis_vector_s, List_of_basis_vector_c = local_basis(phase_track, T = T)
M_pairwise = get_pairwise_matrix(List_of_basis_vector, List_of_basis_vector_s, List_of_basis_vector_c)
_ = plt.imshow(M_pairwise)
_ = plt.colorbar()
plt.xlabel('Time $t$, $sec$')
plt.ylabel('Time $t$, $sec$')
plt.show()
model = AgglomerativeClustering(n_clusters=K, affinity='precomputed', linkage='complete')
fitted = model.fit(M_pairwise)
prediction_vector = fitted.fit_predict(M_pairwise)
color = ['orange', 'green', 'red', 'yelow', 'blue']
plt.figure(figsize=(12, 6))
_ = plt.plot(X_test[0], '-')
for t in np.unique(prediction_vector):
ind = np.where(prediction_vector == t)
_ = plt.plot(List_of_x[ind]+T, X_test[0][2*T:X_test[0].shape[0]-T][ind], 'o', color = color[t], label = 'Type ' + str(t + 1))
plt.grid()
plt.legend(loc = 'best')
plt.xlabel('Time $t$, $sec$')
plt.ylabel('Acceleration $x$, $m/sec^2$')
plt.show()
List_of_All, List_of_point = segmentation(X_test[:, 2*T:X_test[0].shape[0]-T, :], prediction_vector, T)
color = ['orange', 'green', 'red', 'yelow', 'blue']
plt.figure(figsize=(12, 6))
_ = plt.plot(X_test[0], '-')
for t in np.unique(prediction_vector):
# _ = plt.plot(List_of_x[0] + T, 0, color = color[t], label = 'Type ' + str(t + 1))
ind = List_of_point[t] + T
for x in (List_of_x + T)[ind]:
_ = plt.axvline(x = x, color = color[t])
for t in np.unique(prediction_vector):
ind = np.where(prediction_vector == t)
_ = plt.plot(List_of_x[ind]+T, X_test[0][2*T:X_test[0].shape[0]-T][ind], 'o', color = color[t], label = 'Type ' + str(t + 1))
plt.grid()
plt.legend(loc = 'best')
plt.xlabel('Time $t$, $sec$')
plt.ylabel('Acceleration $x$, $m/sec^2$')
plt.show()
index = 1
_, _, List_of_points_plus, List_of_points_minus, List_of_t_plus, List_of_t_minus, line_point, ress = List_of_All[index]
_ = plt.plot(ress[:, 0], ress[:, 1], '-o', color = 'blue')
for point in List_of_points_plus:
_ = plt.plot(point[0], point[1], '*', color = 'orange')
for point in List_of_points_minus:
_ = plt.plot(point[0], point[1], '*', color = 'red')
x_line = np.array([-0.25, 0.25])
k = line_point[1]/line_point[0]
y_line = k*x_line
_ = plt.plot(x_line, y_line, '--', color = 'black')
plt.show()
```
## LSTM для предсказани точек временного ряда
```
class TimeSeriesPrediction(torch.nn.Module):
def __init__(self, emb_dim=2):
super(TimeSeriesPrediction, self).__init__()
self.lstm = torch.nn.LSTM(input_size=1,
hidden_size=emb_dim,
num_layers=1,
batch_first=True)
self.linear = torch.nn.Linear(emb_dim, 1)
def forward(self, x_batch, hidden=None):
r'''
:param x_batch: tensor of shape batch_size x 1 x 1 (момент времени t)
:return: tensor of shape batch_size x 1 x 1 (момент времени t+1)
'''
if hidden is None:
act, (h, c) = self.lstm(x_batch)
else:
act, (h, c) = self.lstm(x_batch, hidden)
return self.linear(act), (h, c)
data = torch.randn(8, 1, 1)
model = TimeSeriesPrediction()
res, (h, c) = model(data)
series = GeneratorOfTimeSeries()
X_train = torch.tensor(series).float()
loss_function = torch.nn.MSELoss()
optimiser = torch.optim.Adam(model.parameters())
for i in tqdm(range(len(X_train))):
optimiser.zero_grad()
x_batch_seq = X_train[i:i+64]
y_batch_seq = torch.zeros_like(x_batch_seq)
hidden = None
for j in range(x_batch_seq.shape[1]):
y_batch_seq[:, j:j+1, :], hidden = model(x_batch_seq[:, j:j+1, :], hidden)
loss = loss_function(y_batch_seq[:, :-1, :], x_batch_seq[:, 1:, :])
loss.backward()
optimiser.step()
```
| github_jupyter |
# **Coco Dataset Notebook and Inference Notebook**
https://www.kaggle.com/vexxingbanana/sartorius-coco-dataset-notebook
https://www.kaggle.com/vexxingbanana/mmdetection-neuron-inference
# **References**
https://www.kaggle.com/dschettler8845/sartorius-segmentation-eda-and-baseline
https://www.kaggle.com/ihelon/cell-segmentation-run-length-decoding
https://www.kaggle.com/stainsby/fast-tested-rle
https://www.kaggle.com/paulorzp/run-length-encode-and-decode
https://www.kaggle.com/awsaf49/sartorius-mmdetection-infer
https://www.kaggle.com/awsaf49/sartorius-mmdetection-train
https://www.kaggle.com/evancofsky/sartorius-torch-lightning-mask-r-cnn/notebook
# Notes
* Trying out more epochs, added more augmentations, increased batch size to 2, and using validation dataset.
* Added mixed precision, reduced epochs back to 12, removed CLAHE augmentation.
* Increased confidence on inference of bboxes to 0.5, removed validation.
* Trying out more epochs, added back 5% validation, changed normalization to the dataset, changed to 3 classes.
Please consider upvoting if you find this helpful. :)
# **Install MMDetection and MMDetection-Compatible Torch**
```
!pip install '/kaggle/input/pytorch-170-cuda-toolkit-110221/torch-1.7.0+cu110-cp37-cp37m-linux_x86_64.whl' --no-deps
!pip install '/kaggle/input/pytorch-170-cuda-toolkit-110221/torchvision-0.8.1+cu110-cp37-cp37m-linux_x86_64.whl' --no-deps
!pip install '/kaggle/input/pytorch-170-cuda-toolkit-110221/torchaudio-0.7.0-cp37-cp37m-linux_x86_64.whl' --no-deps
!pip install '/kaggle/input/mmdetectionv2140/addict-2.4.0-py3-none-any.whl' --no-deps
!pip install '/kaggle/input/mmdetectionv2140/yapf-0.31.0-py2.py3-none-any.whl' --no-deps
!pip install '/kaggle/input/mmdetectionv2140/terminal-0.4.0-py3-none-any.whl' --no-deps
!pip install '/kaggle/input/mmdetectionv2140/terminaltables-3.1.0-py3-none-any.whl' --no-deps
!pip install '/kaggle/input/mmdetectionv2140/mmcv_full-1_3_8-cu110-torch1_7_0/mmcv_full-1.3.8-cp37-cp37m-manylinux1_x86_64.whl' --no-deps
!pip install '/kaggle/input/mmdetectionv2140/pycocotools-2.0.2/pycocotools-2.0.2' --no-deps
!pip install '/kaggle/input/mmdetectionv2140/mmpycocotools-12.0.3/mmpycocotools-12.0.3' --no-deps
!rm -rf mmdetection
!cp -r /kaggle/input/mmdetectionv2140/mmdetection-2.14.0 /kaggle/working/
!mv /kaggle/working/mmdetection-2.14.0 /kaggle/working/mmdetection
%cd /kaggle/working/mmdetection
!pip install -e .
```
# **Import Libraries**
```
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torch.nn.functional as F
import sklearn
import torchvision
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
import PIL
import json
from PIL import Image, ImageEnhance
import albumentations as A
import mmdet
import mmcv
from albumentations.pytorch import ToTensorV2
import seaborn as sns
import glob
from pathlib import Path
import pycocotools
from pycocotools import mask
import numpy.random
import random
import cv2
import re
from mmdet.datasets import build_dataset
from mmdet.models import build_detector
from mmdet.apis import train_detector
from mmdet.apis import inference_detector, init_detector, show_result_pyplot, set_random_seed
%cd ..
IMG_WIDTH = 704
IMG_HEIGHT = 520
```
# **Helper Functions**
```
def rle_decode(mask_rle, shape):
'''
mask_rle: run-length as string formated (start length)
shape: (height,width) of array to return
Returns numpy array, 1 - mask, 0 - background
'''
s = mask_rle.split()
starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
starts -= 1
ends = starts + lengths
img = np.zeros(shape[0]*shape[1], dtype=np.uint8)
for lo, hi in zip(starts, ends):
img[lo:hi] = 1
return img.reshape(shape)
def rle_encode(img):
'''
img: numpy array, 1 - mask, 0 - background
Returns run length as string formated
'''
pixels = img.flatten()
pixels = np.concatenate([[0], pixels, [0]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(str(x) for x in runs)
def flatten_l_o_l(nested_list):
""" Flatten a list of lists """
return [item for sublist in nested_list for item in sublist]
def load_json_to_dict(json_path):
""" tbd """
with open(json_path) as json_file:
data = json.load(json_file)
return data
def get_img_and_mask(img_path, annotation, width, height):
""" Capture the relevant image array as well as the image mask """
img_mask = np.zeros((height, width), dtype=np.uint8)
for i, annot in enumerate(annotation):
img_mask = np.where(rle_decode(annot, (height, width))!=0, i, img_mask)
img = cv2.imread(img_path)[..., ::-1]
return img[..., 0], img_mask
def plot_img_and_mask(img, mask, invert_img=True, boost_contrast=True):
""" Function to take an image and the corresponding mask and plot
Args:
img (np.arr): 1 channel np arr representing the image of cellular structures
mask (np.arr): 1 channel np arr representing the instance masks (incrementing by one)
invert_img (bool, optional): Whether or not to invert the base image
boost_contrast (bool, optional): Whether or not to boost contrast of the base image
Returns:
None; Plots the two arrays and overlays them to create a merged image
"""
plt.figure(figsize=(20,10))
plt.subplot(1,3,1)
_img = np.tile(np.expand_dims(img, axis=-1), 3)
# Flip black-->white ... white-->black
if invert_img:
_img = _img.max()-_img
if boost_contrast:
_img = np.asarray(ImageEnhance.Contrast(Image.fromarray(_img)).enhance(16))
plt.imshow(_img)
plt.axis(False)
plt.title("Cell Image", fontweight="bold")
plt.subplot(1,3,2)
_mask = np.zeros_like(_img)
_mask[..., 0] = mask
plt.imshow(mask, cmap='rainbow')
plt.axis(False)
plt.title("Instance Segmentation Mask", fontweight="bold")
merged = cv2.addWeighted(_img, 0.75, np.clip(_mask, 0, 1)*255, 0.25, 0.0,)
plt.subplot(1,3,3)
plt.imshow(merged)
plt.axis(False)
plt.title("Cell Image w/ Instance Segmentation Mask Overlay", fontweight="bold")
plt.tight_layout()
plt.show()
def polygonFromMask(maskedArr, idx):
# adapted from https://github.com/hazirbas/coco-json-converter/blob/master/generate_coco_json.py
contours, _ = cv2.findContours(maskedArr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
segmentation = []
valid_poly = 0
for contour in contours:
# Valid polygons have >= 6 coordinates (3 points)
if contour.size >= 6:
segmentation.append(contour.astype(float).flatten().tolist())
valid_poly += 1
if valid_poly == 0:
raise ValueError(idx)
return [segmentation]
```
# **Data Visualizations**
```
train_df = pd.read_csv('/kaggle/input/sartorius-cell-instance-segmentation/train.csv')
train_df.head(2)
lines = []
for f in train_df.itertuples():
lines.append('/kaggle/input/sartorius-cell-instance-segmentation/train/' + f[1] + '.png')
lins = pd.Series(lines, name='img_path')
train_df = pd.concat([train_df, lins], axis=1)
tmp_df = train_df.drop_duplicates(subset=["id", "img_path"]).reset_index(drop=True)
tmp_df["annotation"] = train_df.groupby("id")["annotation"].agg(list).reset_index(drop=True)
train_df = tmp_df.copy()
train_df.head(2)
def plot_mask(idx):
im, mk = get_img_and_mask(**train_df[["img_path", "annotation", "width", "height"]].iloc[idx].to_dict())
print
plot_img_and_mask(im, mk)
plot_mask(0)
plot_mask(1)
plot_mask(2)
train_df, val_df = train_test_split(train_df, train_size=0.95, random_state=0)
train_df = train_df.reset_index(drop=True)
val_df = val_df.reset_index(drop=True)
%%writefile labels.txt
shsy5y
cort
astro
```
# **Model Config**
```
from mmcv import Config
# cfg = Config.fromfile('/kaggle/working/mmdetection/configs/htc/htc_x101_64x4d_fpn_dconv_c3-c5_mstrain_400_1400_16x1_20e_coco.py')
cfg = Config.fromfile('/kaggle/working/mmdetection/configs/ms_rcnn/ms_rcnn_x101_32x4d_fpn_1x_coco.py')
cfg1 = Config.fromfile('/kaggle/working/mmdetection/configs/ms_rcnn/ms_rcnn_x101_32x4d_fpn_1x_coco.py')
# cfg = Config.fromfile('/kaggle/working/mmdetection/configs/cascade_rcnn/cascade_mask_rcnn_r50_fpn_20e_coco.py')
print(cfg1.pretty_text)
!mkdir /kaggle/working/mmdetection/configs/sartorius/
# %%writefile /kaggle/working/mmdetection/configs/sartorius/mask_rcnn_r50_fpn.py
cfg.model = dict(
type='MaskScoringRCNN',
backbone=dict(
type='ResNeXt',
depth=101,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
init_cfg=dict(
type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d'),
groups=32,
base_width=4),
neck=dict(
type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
num_outs=5),
rpn_head=dict(
type='RPNHead',
in_channels=256,
feat_channels=256,
anchor_generator=dict(
type='AnchorGenerator',
scales=[8],
ratios=[0.5, 1.0, 2.0],
strides=[4, 8, 16, 32, 64]),
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0.0, 0.0, 0.0, 0.0],
target_stds=[1.0, 1.0, 1.0, 1.0]),
loss_cls=dict(
type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
loss_bbox=dict(type='L1Loss', loss_weight=1.0)),
roi_head=dict(
type='MaskScoringRoIHead',
bbox_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
bbox_head=dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=3,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0.0, 0.0, 0.0, 0.0],
target_stds=[0.1, 0.1, 0.2, 0.2]),
reg_class_agnostic=False,
loss_cls=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),
loss_bbox=dict(type='L1Loss', loss_weight=1.0)),
mask_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
mask_head=dict(
type='FCNMaskHead',
num_convs=4,
in_channels=256,
conv_out_channels=256,
num_classes=3,
loss_mask=dict(
type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)),
mask_iou_head=dict(
type='MaskIoUHead',
num_convs=4,
num_fcs=2,
roi_feat_size=14,
in_channels=256,
conv_out_channels=256,
fc_out_channels=1024,
num_classes=3)))
# model training and testing settings
cfg.train_cfg = dict(
rpn=dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.7,
neg_iou_thr=0.3,
min_pos_iou=0.3,
match_low_quality=True,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=256,
pos_fraction=0.5,
neg_pos_ub=-1,
add_gt_as_proposals=False),
allowed_border=-1,
pos_weight=-1,
debug=False),
rpn_proposal=dict(
nms_across_levels=False,
nms_pre=2000,
nms_post=1000,
max_num=1000,
nms_thr=0.7,
min_bbox_size=0),
rcnn=dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.5,
neg_iou_thr=0.5,
min_pos_iou=0.5,
match_low_quality=True,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
mask_size=28,
pos_weight=-1,
debug=False))
cfg.test_cfg = dict(
rpn=dict(
nms_across_levels=False,
nms_pre=1000,
nms_post=1000,
max_num=1000,
nms_thr=0.7,
min_bbox_size=0),
rcnn=dict(
score_thr=0.05,
nms=dict(type='nms', iou_threshold=0.5),
max_per_img=400,
mask_thr_binary=0.5))
# cfg.model.roi_head.mask_head.num_classes
!wget https://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_x101_32x4d_fpn_1x_coco/ms_rcnn_x101_32x4d_fpn_1x_coco_20200206-81fd1740.pth -P /kaggle/working/mmdetection/configs/sartorius/
cfg.dataset_type = 'CocoDataset'
cfg.classes = '/kaggle/working/labels.txt'
cfg.data_root = '/kaggle/working'
# for head in cfg.model.roi_head.bbox_head:
# head.num_classes = 3
# for head in cfg.model.roi_head.mask_head:
# head.num_classes = 3
# cfg.model.roi_head.mask_head.semantic_head.num_classes=3
# cfg.model.roi_head.mask_head.num_classes=3
cfg.data.test.type = 'CocoDataset'
cfg.data.test.classes = 'labels.txt'
cfg.data.test.data_root = '/kaggle/working'
cfg.data.test.ann_file = '../input/k/vexxingbanana/sartorius-coco-dataset-notebook/val_dataset.json'
cfg.data.test.img_prefix = ''
cfg.data.train.type = 'CocoDataset'
cfg.data.train.data_root = '/kaggle/working'
cfg.data.train.ann_file = '../input/k/vexxingbanana/sartorius-coco-dataset-notebook/train_dataset.json'
cfg.data.train.img_prefix = ''
cfg.data.train.classes = 'labels.txt'
cfg.data.val.type = 'CocoDataset'
cfg.data.val.data_root = '/kaggle/working'
cfg.data.val.ann_file = '../input/k/vexxingbanana/sartorius-coco-dataset-notebook/val_dataset.json'
cfg.data.val.img_prefix = ''
cfg.data.val.classes = 'labels.txt'
albu_train_transforms = [
dict(type='ShiftScaleRotate', shift_limit=0.0625,
scale_limit=0.15, rotate_limit=15, p=0.4),
dict(type='RandomBrightnessContrast', brightness_limit=0.2,
contrast_limit=0.2, p=0.5),
# dict(type='IAAAffine', shear=(-10.0, 10.0), p=0.4),
# dict(type='CLAHE', p=0.5),
dict(
type="OneOf",
transforms=[
dict(type="GaussianBlur", p=1.0, blur_limit=7),
dict(type="MedianBlur", p=1.0, blur_limit=7),
],
p=0.4,
),
]
cfg.train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
# dict(type='Resize', img_scale=[(440, 596), (480, 650), (520, 704), (580, 785), (620, 839)], multiscale_mode='value', keep_ratio=True),
# dict(type='Resize', img_scale=[(880, 1192), (960, 130), (1040, 1408), (1160, 1570), (1240, 1678)], multiscale_mode='value', keep_ratio=True),
dict(type='Resize', img_scale=[(1333, 800), (1690, 960)]),
# dict(type='Resize', img_scale=(1333, 800)),
dict(type='RandomFlip', flip_ratio=0.5),
dict(
type='Albu',
transforms=albu_train_transforms,
bbox_params=dict(
type='BboxParams',
format='pascal_voc',
label_fields=['gt_labels'],
min_visibility=0.0,
filter_lost_elements=True),
keymap=dict(img='image', gt_bboxes='bboxes', gt_masks='masks'),
update_pad_shape=False,
skip_img_without_anno=True),
dict(
type='Normalize',
mean=[128, 128, 128],
std=[11.58, 11.58, 11.58],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_masks', 'gt_labels'])
]
cfg.val_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
# img_scale=[(880, 1192), (960, 130), (1040, 1408), (1160, 1570), (1240, 1678)],
img_scale = [(1333, 800), (1690, 960)],
# img_scale=(1333, 800),
# img_scale = (520, 704),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(
type='Normalize',
mean=[128, 128, 128],
std=[11.58, 11.58, 11.58],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
])
]
cfg.test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=[(1333, 800), (1690, 960)],
# img_scale=(1333, 800),
# img_scale = (520, 704),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(
type='Normalize',
mean=[128, 128, 128],
std=[11.58, 11.58, 11.58],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
])
]
cfg.data.train.pipeline = cfg.train_pipeline
cfg.data.val.pipeline = cfg.val_pipeline
cfg.data.test.pipeline = cfg.test_pipeline
# cfg.model.test_cfg.rcnn.max_per_img = 300
# cfg.load_from = '../input/htc-checkpoint-resnext101/htc_x101_64x4d_fpn_dconv_c3-c5_mstrain_400_1400_16x1_20e_coco_20200312-946fd751.pth'
cfg.load_from = '/kaggle/working/mmdetection/configs/sartorius/ms_rcnn_x101_32x4d_fpn_1x_coco_20200206-81fd1740.pth'
# cfg.load_from = '../input/cascade-mask-rcnn-r50/cascade_mask_rcnn_r50_fpn_20e_coco_bbox_mAP-0.419__segm_mAP-0.365_20200504_174711-4af8e66e.pth'
cfg.work_dir = '/kaggle/working/model_output'
cfg.optimizer.lr = 0.02 / 8
cfg.lr_config = dict(
policy='CosineAnnealing',
by_epoch=False,
warmup='linear',
warmup_iters=125,
warmup_ratio=0.001,
min_lr=1e-07)
cfg.data.samples_per_gpu = 2
cfg.data.workers_per_gpu = 2
cfg.evaluation.metric = 'segm'
cfg.evaluation.interval = 1
cfg.checkpoint_config.interval = 1
cfg.runner.max_epochs = 12
cfg.log_config.interval = 144
# cfg.model.rpn_head.anchor_generator.base_sizes = [4, 9, 17, 31, 64]
# cfg.model.rpn_head.anchor_generator.strides = [4, 8, 16, 32, 64]
cfg.seed = 0
set_random_seed(0, deterministic=False)
cfg.gpu_ids = range(1)
cfg.fp16 = dict(loss_scale=512.0)
meta = dict()
meta['config'] = cfg.pretty_text
print(f'Config:\n{cfg.pretty_text}')
# dataset_type = 'CocoDataset'
# data_root = 'data/coco/'
# img_norm_cfg = dict(
# mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
# train_pipeline = [
# dict(type='LoadImageFromFile'),
# dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
# dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
# dict(type='RandomFlip', flip_ratio=0.5),
# dict(
# type='Normalize',
# mean=[123.675, 116.28, 103.53],
# std=[58.395, 57.12, 57.375],
# to_rgb=True),
# dict(type='Pad', size_divisor=32),
# dict(type='DefaultFormatBundle'),
# dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks'])
# ]
# test_pipeline = [
# dict(type='LoadImageFromFile'),
# dict(
# type='MultiScaleFlipAug',
# img_scale=(1333, 800),
# flip=False,
# transforms=[
# dict(type='Resize', keep_ratio=True),
# dict(type='RandomFlip'),
# dict(
# type='Normalize',
# mean=[123.675, 116.28, 103.53],
# std=[58.395, 57.12, 57.375],
# to_rgb=True),
# dict(type='Pad', size_divisor=32),
# dict(type='ImageToTensor', keys=['img']),
# dict(type='Collect', keys=['img'])
# ])
# ]
# data = dict(
# samples_per_gpu=2,
# workers_per_gpu=2,
# train=dict(
# type='CocoDataset',
# ann_file='data/coco/annotations/instances_train2017.json',
# img_prefix='data/coco/train2017/',
# pipeline=[
# dict(type='LoadImageFromFile'),
# dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
# dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
# dict(type='RandomFlip', flip_ratio=0.5),
# dict(
# type='Normalize',
# mean=[123.675, 116.28, 103.53],
# std=[58.395, 57.12, 57.375],
# to_rgb=True),
# dict(type='Pad', size_divisor=32),
# dict(type='DefaultFormatBundle'),
# dict(
# type='Collect',
# keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks'])
# ]),
# val=dict(
# type='CocoDataset',
# ann_file='data/coco/annotations/instances_val2017.json',
# img_prefix='data/coco/val2017/',
# pipeline=[
# dict(type='LoadImageFromFile'),
# dict(
# type='MultiScaleFlipAug',
# img_scale=(1333, 800),
# flip=False,
# transforms=[
# dict(type='Resize', keep_ratio=True),
# dict(type='RandomFlip'),
# dict(
# type='Normalize',
# mean=[123.675, 116.28, 103.53],
# std=[58.395, 57.12, 57.375],
# to_rgb=True),
# dict(type='Pad', size_divisor=32),
# dict(type='ImageToTensor', keys=['img']),
# dict(type='Collect', keys=['img'])
# ])
# ]),
# test=dict(
# type='CocoDataset',
# ann_file='data/coco/annotations/instances_val2017.json',
# img_prefix='data/coco/val2017/',
# pipeline=[
# dict(type='LoadImageFromFile'),
# dict(
# type='MultiScaleFlipAug',
# img_scale=(1333, 800),
# flip=False,
# transforms=[
# dict(type='Resize', keep_ratio=True),
# dict(type='RandomFlip'),
# dict(
# type='Normalize',
# mean=[123.675, 116.28, 103.53],
# std=[58.395, 57.12, 57.375],
# to_rgb=True),
# dict(type='Pad', size_divisor=32),
# dict(type='ImageToTensor', keys=['img']),
# dict(type='Collect', keys=['img'])
# ])
# ]))
# evaluation = dict(metric=['bbox', 'segm'])
# optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)
# optimizer_config = dict(grad_clip=None)
# lr_config = dict(
# policy='step',
# warmup='linear',
# warmup_iters=500,
# warmup_ratio=0.001,
# step=[8, 11])
# runner = dict(type='EpochBasedRunner', max_epochs=12)
# checkpoint_config = dict(interval=1)
# log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook')])
# custom_hooks = [dict(type='NumClassCheckHook')]
# dist_params = dict(backend='nccl')
# log_level = 'INFO'
# load_from = None
# resume_from = None
# workflow = [('train', 1)]
# print(cfg.pretty_text)
# !mkdir /kaggle/working/mmdetection/configs/sartorius/
cfg.dataset_type = 'CocoDataset'
cfg.classes = '/kaggle/working/labels.txt'
cfg.data_root = '/kaggle/working'
# for head in cfg.model.roi_head.bbox_head:
# head.num_classes = 3
# for head in cfg.model.roi_head.mask_head:
# head.num_classes = 3
# cfg.model.roi_head.mask_head.semantic_head.num_classes=3
cfg.model.roi_head.mask_head.num_classes=3
cfg.data.test.type = 'CocoDataset'
cfg.data.test.classes = 'labels.txt'
cfg.data.test.data_root = '/kaggle/working'
cfg.data.test.ann_file = '../input/k/vexxingbanana/sartorius-coco-dataset-notebook/val_dataset.json'
cfg.data.test.img_prefix = ''
cfg.data.train.type = 'CocoDataset'
cfg.data.train.data_root = '/kaggle/working'
cfg.data.train.ann_file = '../input/k/vexxingbanana/sartorius-coco-dataset-notebook/train_dataset.json'
cfg.data.train.img_prefix = ''
cfg.data.train.classes = 'labels.txt'
cfg.data.val.type = 'CocoDataset'
cfg.data.val.data_root = '/kaggle/working'
cfg.data.val.ann_file = '../input/k/vexxingbanana/sartorius-coco-dataset-notebook/val_dataset.json'
cfg.data.val.img_prefix = ''
cfg.data.val.classes = 'labels.txt'
albu_train_transforms = [
dict(type='ShiftScaleRotate', shift_limit=0.0625,
scale_limit=0.15, rotate_limit=15, p=0.4),
dict(type='RandomBrightnessContrast', brightness_limit=0.2,
contrast_limit=0.2, p=0.5),
# dict(type='IAAAffine', shear=(-10.0, 10.0), p=0.4),
# dict(type='CLAHE', p=0.5),
dict(
type="OneOf",
transforms=[
dict(type="GaussianBlur", p=1.0, blur_limit=7),
dict(type="MedianBlur", p=1.0, blur_limit=7),
],
p=0.4,
),
]
cfg.train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
# dict(type='Resize', img_scale=[(440, 596), (480, 650), (520, 704), (580, 785), (620, 839)], multiscale_mode='value', keep_ratio=True),
# dict(type='Resize', img_scale=[(880, 1192), (960, 130), (1040, 1408), (1160, 1570), (1240, 1678)], multiscale_mode='value', keep_ratio=True),
dict(type='Resize', img_scale=[(1333, 800), (1690, 960)]),
# dict(type='Resize', img_scale=(1333, 800)),
dict(type='RandomFlip', flip_ratio=0.5),
dict(
type='Albu',
transforms=albu_train_transforms,
bbox_params=dict(
type='BboxParams',
format='pascal_voc',
label_fields=['gt_labels'],
min_visibility=0.0,
filter_lost_elements=True),
keymap=dict(img='image', gt_bboxes='bboxes', gt_masks='masks'),
update_pad_shape=False,
skip_img_without_anno=True),
dict(
type='Normalize',
mean=[128, 128, 128],
std=[11.58, 11.58, 11.58],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_masks', 'gt_labels'])
]
cfg.val_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
# img_scale=[(880, 1192), (960, 130), (1040, 1408), (1160, 1570), (1240, 1678)],
img_scale = [(1333, 800), (1690, 960)],
# img_scale=(1333, 800),
# img_scale = (520, 704),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(
type='Normalize',
mean=[128, 128, 128],
std=[11.58, 11.58, 11.58],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
])
]
cfg.test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=[(1333, 800), (1690, 960)],
# img_scale=(1333, 800),
# img_scale = (520, 704),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(
type='Normalize',
mean=[128, 128, 128],
std=[11.58, 11.58, 11.58],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
])
]
cfg.data.train.pipeline = cfg.train_pipeline
cfg.data.val.pipeline = cfg.val_pipeline
cfg.data.test.pipeline = cfg.test_pipeline
cfg.model.test_cfg.rcnn.max_per_img = 300
# cfg.load_from = '../input/htc-checkpoint-resnext101/htc_x101_64x4d_fpn_dconv_c3-c5_mstrain_400_1400_16x1_20e_coco_20200312-946fd751.pth'
cfg.load_from = '/kaggle/working/mmdetection/configs/sartorius/ms_rcnn_x101_32x4d_fpn_1x_coco_20200206-81fd1740.pth'
# cfg.load_from = '../input/cascade-mask-rcnn-r50/cascade_mask_rcnn_r50_fpn_20e_coco_bbox_mAP-0.419__segm_mAP-0.365_20200504_174711-4af8e66e.pth'
cfg.work_dir = '/kaggle/working/model_output'
cfg.optimizer.lr = 0.02 / 8
cfg.lr_config = dict(
policy='CosineAnnealing',
by_epoch=False,
warmup='linear',
warmup_iters=125,
warmup_ratio=0.001,
min_lr=1e-07)
cfg.data.samples_per_gpu = 2
cfg.data.workers_per_gpu = 2
cfg.evaluation.metric = 'segm'
cfg.evaluation.interval = 1
cfg.checkpoint_config.interval = 1
cfg.runner.max_epochs = 12
cfg.log_config.interval = 144
# cfg.model.rpn_head.anchor_generator.base_sizes = [4, 9, 17, 31, 64]
# cfg.model.rpn_head.anchor_generator.strides = [4, 8, 16, 32, 64]
cfg.seed = 0
set_random_seed(0, deterministic=False)
cfg.gpu_ids = range(1)
cfg.fp16 = dict(loss_scale=512.0)
meta = dict()
meta['config'] = cfg.pretty_text
print(f'Config:\n{cfg.pretty_text}')
```
# **Training**
```
datasets = [build_dataset(cfg.data.train)]
model = build_detector(cfg.model, train_cfg=cfg.get('train_cfg'), test_cfg=cfg.get('test_cfg'))
model.CLASSES = datasets[0].CLASSES
mmcv.mkdir_or_exist(os.path.abspath(cfg.work_dir))
train_detector(model, datasets, cfg, distributed=False, validate=True, meta=meta)
cfg.load_from = '/kaggle/working/model_output/epoch_9.pth'
cfg.work_dir = '/kaggle/working/finetune_output'
cfg.optimizer.lr = 0.02 / 32
cfg.lr_config = dict(
policy='CosineAnnealing',
by_epoch=False,
warmup='linear',
warmup_iters=1,
warmup_ratio=0.001,
min_lr=1e-09)
cfg.runner.max_epochs = 6
model = build_detector(cfg.model, train_cfg=cfg.get('train_cfg'), test_cfg=cfg.get('test_cfg'))
model.CLASSES = datasets[0].CLASSES
mmcv.mkdir_or_exist(os.path.abspath(cfg.work_dir))
train_detector(model, datasets, cfg, distributed=False, validate=True, meta=meta)
```
| github_jupyter |
- [Lab 1: Principal Component Analysis](#Lab-1:-Principal-Component-Analysis)
- [Lab 2: K-Means Clustering](#Lab-2:-Clustering)
- [Lab 2: Hierarchical Clustering](#10.5.3-Hierarchical-Clustering)
- [Lab 3: NCI60 Data Example](#Lab-3:-NCI60-Data-Example)
# Chapter 10 - Unsupervised Learning
```
# %load ../standard_import.txt
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import scale
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from scipy.cluster import hierarchy
pd.set_option('display.notebook_repr_html', False)
%matplotlib inline
plt.style.use('seaborn-white')
```
## Lab 1: Principal Component Analysis
```
# In R, I exported the dataset to a csv file. It is part of the base R distribution.
df = pd.read_csv('Data/USArrests.csv', index_col=0)
df.info()
df.mean()
df.var()
X = pd.DataFrame(scale(df), index=df.index, columns=df.columns)
# The loading vectors
pca_loadings = pd.DataFrame(PCA().fit(X).components_.T, index=df.columns, columns=['V1', 'V2', 'V3', 'V4'])
pca_loadings
# Fit the PCA model and transform X to get the principal components
pca = PCA()
df_plot = pd.DataFrame(pca.fit_transform(X), columns=['PC1', 'PC2', 'PC3', 'PC4'], index=X.index)
df_plot
fig , ax1 = plt.subplots(figsize=(9,7))
ax1.set_xlim(-3.5,3.5)
ax1.set_ylim(-3.5,3.5)
# Plot Principal Components 1 and 2
for i in df_plot.index:
ax1.annotate(i, (-df_plot.PC1.loc[i], -df_plot.PC2.loc[i]), ha='center')
# Plot reference lines
ax1.hlines(0,-3.5,3.5, linestyles='dotted', colors='grey')
ax1.vlines(0,-3.5,3.5, linestyles='dotted', colors='grey')
ax1.set_xlabel('First Principal Component')
ax1.set_ylabel('Second Principal Component')
# Plot Principal Component loading vectors, using a second y-axis.
ax2 = ax1.twinx().twiny()
ax2.set_ylim(-1,1)
ax2.set_xlim(-1,1)
ax2.tick_params(axis='y', colors='orange')
ax2.set_xlabel('Principal Component loading vectors', color='orange')
# Plot labels for vectors. Variable 'a' is a small offset parameter to separate arrow tip and text.
a = 1.07
for i in pca_loadings[['V1', 'V2']].index:
ax2.annotate(i, (-pca_loadings.V1.loc[i]*a, -pca_loadings.V2.loc[i]*a), color='orange')
# Plot vectors
ax2.arrow(0,0,-pca_loadings.V1[0], -pca_loadings.V2[0])
ax2.arrow(0,0,-pca_loadings.V1[1], -pca_loadings.V2[1])
ax2.arrow(0,0,-pca_loadings.V1[2], -pca_loadings.V2[2])
ax2.arrow(0,0,-pca_loadings.V1[3], -pca_loadings.V2[3]);
# Standard deviation of the four principal components
np.sqrt(pca.explained_variance_)
pca.explained_variance_
pca.explained_variance_ratio_
plt.figure(figsize=(7,5))
plt.plot([1,2,3,4], pca.explained_variance_ratio_, '-o', label='Individual component')
plt.plot([1,2,3,4], np.cumsum(pca.explained_variance_ratio_), '-s', label='Cumulative')
plt.ylabel('Proportion of Variance Explained')
plt.xlabel('Principal Component')
plt.xlim(0.75,4.25)
plt.ylim(0,1.05)
plt.xticks([1,2,3,4])
plt.legend(loc=2);
```
## Lab 2: Clustering
### 10.5.1 K-Means Clustering
```
# Generate data
np.random.seed(2)
X = np.random.standard_normal((50,2))
X[:25,0] = X[:25,0]+3
X[:25,1] = X[:25,1]-4
```
#### K = 2
```
km1 = KMeans(n_clusters=2, n_init=20)
km1.fit(X)
km1.labels_
```
See plot for K=2 below.
#### K = 3
```
np.random.seed(4)
km2 = KMeans(n_clusters=3, n_init=20)
km2.fit(X)
pd.Series(km2.labels_).value_counts()
km2.cluster_centers_
km2.labels_
# Sum of distances of samples to their closest cluster center.
km2.inertia_
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(14,5))
ax1.scatter(X[:,0], X[:,1], s=40, c=km1.labels_, cmap=plt.cm.prism)
ax1.set_title('K-Means Clustering Results with K=2')
ax1.scatter(km1.cluster_centers_[:,0], km1.cluster_centers_[:,1], marker='+', s=100, c='k', linewidth=2)
ax2.scatter(X[:,0], X[:,1], s=40, c=km2.labels_, cmap=plt.cm.prism)
ax2.set_title('K-Means Clustering Results with K=3')
ax2.scatter(km2.cluster_centers_[:,0], km2.cluster_centers_[:,1], marker='+', s=100, c='k', linewidth=2);
```
### 10.5.3 Hierarchical Clustering
#### scipy
```
fig, (ax1,ax2,ax3) = plt.subplots(3,1, figsize=(15,18))
for linkage, cluster, ax in zip([hierarchy.complete(X), hierarchy.average(X), hierarchy.single(X)], ['c1','c2','c3'],
[ax1,ax2,ax3]):
cluster = hierarchy.dendrogram(linkage, ax=ax, color_threshold=0)
ax1.set_title('Complete Linkage')
ax2.set_title('Average Linkage')
ax3.set_title('Single Linkage');
```
## Lab 3: NCI60 Data Example
### § 10.6.1 PCA
```
# In R, I exported the two elements of this ISLR dataset to csv files.
# There is one file for the features and another file for the classes/types.
df2 = pd.read_csv('Data/NCI60_X.csv').drop('Unnamed: 0', axis=1)
df2.columns = np.arange(df2.columns.size)
df2.info()
X = pd.DataFrame(scale(df2))
X.shape
y = pd.read_csv('Data/NCI60_y.csv', usecols=[1], skiprows=1, names=['type'])
y.shape
y.type.value_counts()
# Fit the PCA model and transform X to get the principal components
pca2 = PCA()
df2_plot = pd.DataFrame(pca2.fit_transform(X))
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(15,6))
color_idx = pd.factorize(y.type)[0]
cmap = plt.cm.hsv
# Left plot
ax1.scatter(df2_plot.iloc[:,0], df2_plot.iloc[:,1], c=color_idx, cmap=cmap, alpha=0.5, s=50)
ax1.set_ylabel('Principal Component 2')
# Right plot
ax2.scatter(df2_plot.iloc[:,0], df2_plot.iloc[:,2], c=color_idx, cmap=cmap, alpha=0.5, s=50)
ax2.set_ylabel('Principal Component 3')
# Custom legend for the classes (y) since we do not create scatter plots per class (which could have their own labels).
handles = []
labels = pd.factorize(y.type.unique())
norm = mpl.colors.Normalize(vmin=0.0, vmax=14.0)
for i, v in zip(labels[0], labels[1]):
handles.append(mpl.patches.Patch(color=cmap(norm(i)), label=v, alpha=0.5))
ax2.legend(handles=handles, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
# xlabel for both plots
for ax in fig.axes:
ax.set_xlabel('Principal Component 1')
pd.DataFrame([df2_plot.iloc[:,:5].std(axis=0, ddof=0).as_matrix(),
pca2.explained_variance_ratio_[:5],
np.cumsum(pca2.explained_variance_ratio_[:5])],
index=['Standard Deviation', 'Proportion of Variance', 'Cumulative Proportion'],
columns=['PC1', 'PC2', 'PC3', 'PC4', 'PC5'])
df2_plot.iloc[:,:10].var(axis=0, ddof=0).plot(kind='bar', rot=0)
plt.ylabel('Variances');
fig , (ax1,ax2) = plt.subplots(1,2, figsize=(15,5))
# Left plot
ax1.plot(pca2.explained_variance_ratio_, '-o')
ax1.set_ylabel('Proportion of Variance Explained')
ax1.set_ylim(ymin=-0.01)
# Right plot
ax2.plot(np.cumsum(pca2.explained_variance_ratio_), '-ro')
ax2.set_ylabel('Cumulative Proportion of Variance Explained')
ax2.set_ylim(ymax=1.05)
for ax in fig.axes:
ax.set_xlabel('Principal Component')
ax.set_xlim(-1,65)
```
### § 10.6.2 Clustering
```
X= pd.DataFrame(scale(df2), index=y.type, columns=df2.columns)
fig, (ax1,ax2,ax3) = plt.subplots(1,3, figsize=(20,20))
for linkage, cluster, ax in zip([hierarchy.complete(X), hierarchy.average(X), hierarchy.single(X)],
['c1','c2','c3'],
[ax1,ax2,ax3]):
cluster = hierarchy.dendrogram(linkage, labels=X.index, orientation='right', color_threshold=0, leaf_font_size=10, ax=ax)
ax1.set_title('Complete Linkage')
ax2.set_title('Average Linkage')
ax3.set_title('Single Linkage');
plt.figure(figsize=(10,20))
cut4 = hierarchy.dendrogram(hierarchy.complete(X),
labels=X.index, orientation='right', color_threshold=140, leaf_font_size=10)
plt.vlines(140,0,plt.gca().yaxis.get_data_interval()[1], colors='r', linestyles='dashed');
```
##### KMeans
```
np.random.seed(2)
km4 = KMeans(n_clusters=4, n_init=50)
km4.fit(X)
km4.labels_
# Observations per KMeans cluster
pd.Series(km4.labels_).value_counts().sort_index()
```
##### Hierarchical
```
# Observations per Hierarchical cluster
cut4b = hierarchy.dendrogram(hierarchy.complete(X), truncate_mode='lastp', p=4, show_leaf_counts=True)
# Hierarchy based on Principal Components 1 to 5
plt.figure(figsize=(10,20))
pca_cluster = hierarchy.dendrogram(hierarchy.complete(df2_plot.iloc[:,:5]), labels=y.type.values, orientation='right', color_threshold=100, leaf_font_size=10)
cut4c = hierarchy.dendrogram(hierarchy.complete(df2_plot), truncate_mode='lastp', p=4,
show_leaf_counts=True)
# See also color coding in plot above.
```
| github_jupyter |
# Analysing model capacity
Author: Alexandre Gramfort, based on materials from Jake Vanderplas
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
```
The issues associated with validation and
cross-validation are some of the most important
aspects of the practice of machine learning. Selecting the optimal model
for your data is vital, and is a piece of the problem that is not often
appreciated by machine learning practitioners.
Of core importance is the following question:
**If our estimator is underperforming, how should we move forward?**
- Use simpler or more complicated model?
- Add more features to each observed data point?
- Add more training samples?
The answer is often counter-intuitive. In particular, **sometimes using a
more complicated model will give _worse_ results.** Also, **sometimes adding
training data will not improve your results.** The ability to determine
what steps will improve your model is what separates the successful machine
learning practitioners from the unsuccessful.
## Learning Curves and Validation Curves
One way to address this issue is to use what are often called **Learning Curves**.
The idea is to test the performance of your prediction pipeline as a function of the training samples.
To get a "robust" estimation of the model performance, the performance is evaluted multiple times for multiple random splits of the data.
What the right model for a dataset is depends critically on **how much data we have**. More data allows us to be more confident about building a complex model. Lets built some intuition on why that is. Look at the following datasets:
```
from sklearn import model_selection
rng = np.random.RandomState(0)
n_samples = 100
def f(X):
return X ** 3
X = np.sort(2. * (rng.rand(n_samples) - .5))
y = f(X) + .01 * rng.randn(n_samples)
X = X[:, None]
y = y
def plot(clf=None):
fig, axarr = plt.subplots(1, 3, figsize=(12, 4))
for ax, decim in zip(axarr, [45, 10, 1]):
ax.scatter(X[::decim], y[::decim])
ax.set_xlim((-3 * .5, 3 * .5))
ax.set_ylim((-1, 1))
xx = np.linspace(X.min(), X.max(), 100)
ax.plot(xx, f(xx), 'r--')
if clf is not None:
xx = np.linspace(-1.5, 1.5, 100)
clf.fit(X[::decim], y[::decim])
y_pred = clf.predict(xx[:, None])
ax.plot(xx, y_pred, 'g')
plt.show()
plot()
```
They all come from the same underlying process. But if you were asked to make a prediction, you would be more likely to draw a straight line for the left-most one, as there are only very few datapoints, and no real rule is apparent. For the dataset in the middle, some structure is recognizable, though the exact shape of the true function is maybe not obvious. With even more data on the right hand side, you would probably be very comfortable with drawing a curved line with a lot of certainty.
```
from sklearn.linear_model import LinearRegression
plot(LinearRegression())
from sklearn.svm import SVR
plot(SVR(kernel='rbf', gamma='auto'))
```
A great way to explore how a model fit evolves with different dataset sizes are learning curves.
A learning curve plots the validation error for a given model against different training set sizes.
But first, take a moment to think about what we're going to see:
**Questions:**
- **As the number of training samples are increased, what do you expect to see for the training error? For the validation error?**
- **Would you expect the training error to be higher or lower than the validation error? Would you ever expect this to change?**
We can run the following code to plot the learning curve for a ``kernel = linear`` model:
```
from sklearn.model_selection import learning_curve
from sklearn.svm import SVR
scoring = 'neg_mean_squared_error'
training_sizes, train_scores, test_scores = learning_curve(SVR(kernel='linear'), X, y, cv=10,
scoring=scoring,
train_sizes=[.6, .7, .8, .9, 1.])
# Use the negative because we want to maximize score
print(train_scores.mean(axis=1))
plt.plot(training_sizes, train_scores.mean(axis=1), label="training scores")
plt.plot(training_sizes, test_scores.mean(axis=1), label="test scores")
plt.legend(loc='best');
```
You can see that for the model with ``kernel = linear``, the validation score doesn't really improve as more data is given.
Notice that the validation error *generally improves* with a growing training set,
while the training error *generally gets worse* with a growing training set. From
this we can infer that as the training size increases, they will converge to a single
value.
From the above discussion, we know that `kernel = linear`
underfits the data. This is indicated by the fact that both the
training and validation errors are very poor. When confronted with this type of learning curve,
we can expect that adding more training data will not help matters: both
lines will converge to a relatively high error.
**When the learning curves have converged to a poor error, we have an underfitting model.**
An underfitting model can be improved by:
- Using a more sophisticated model (i.e. in this case, increase complexity of the ``kernel`` parameter)
- Gather more features for each sample.
- Decrease regularization in a regularized model.
A underfitting model cannot be improved, however, by increasing the number of training
samples (do you see why?)
Now let's look at an overfit model:
```
from sklearn.svm import SVR
training_sizes, train_scores, test_scores = learning_curve(SVR(kernel='rbf', gamma='auto'), X, y, cv=10,
scoring=scoring,
train_sizes=[.6, .7, .8, .9, 1.])
plt.plot(training_sizes, train_scores.mean(axis=1), label="training scores")
plt.plot(training_sizes, test_scores.mean(axis=1), label="test scores")
plt.legend(loc='best')
```
Here we show the learning curve for `kernel = rbf`. From the above
discussion, we know that `kernel = rbf` is an estimator
which mildly **overfits** the data. This is indicated by the fact that the
training error is **much** better than the validation error. As
we add more samples to this training set, the training error will
continue to worsen, while the cross-validation error will continue
to improve, until they meet in the middle. We can infer that adding more
data will allow the estimator to very closely match the best
possible cross-validation error.
**When the learning curves have not yet converged with our full training set, it indicates an overfit model.**
An overfitting model can be improved by:
- Gathering more training samples.
- Using a less-sophisticated model (i.e. in this case, make ``kernel`` less complex with ``kernel = poly``)
- Increasing regularization (parameter ``C`` for SVM/SVR).
In particular, gathering more features for each sample will not help the results.
## Summary
We’ve seen above that an under-performing algorithm can be due
to two possible situations: underfitting and overfitting.
Using the technique of learning curves, we can train on progressively
larger subsets of the data, evaluating the training error and
cross-validation error to determine whether our algorithm is overfitting or underfitting. But what do we do with this information?
### Underfitting
If our algorithm is **underfitting**, the following actions might help:
- **Add more features**. It may be helpful to make use of information as
additional features. For example, to predict housing prices
features such as the neighborhood
the house is in, the year the house was built, the size of the lot, etc.
can help the model by giving new dimensions to help differentiate
houses. Adding these features to the training and test sets can improve
the fit.
- **Use a more sophisticated model**. Adding complexity to the model can
help improve the fit. For a SVR fit, this can be accomplished
by increasing the kernel complexity (generally ``linear`` << ``poly`` << ``rbf``).
Each learning technique has its own methods of adding complexity.
- **Use fewer samples**. Though this will not improve the classification,
an underfitting algorithm can attain nearly the same error with a smaller
training sample. For algorithms which are computationally expensive,
reducing the training sample size can lead to very large improvements
in speed.
- **Decrease regularization**. Regularization is a technique used to impose
simplicity in some machine learning models, by adding a penalty term that
depends on the characteristics of the parameters. If a model is underfitting,
decreasing the regularization can lead to better results.
### Overfitting
If our algorithm shows signs of **overfitting**, the following actions might help:
- **Use fewer features**. Using a feature selection technique may be
useful, and decrease the overfitting of the estimator.
- **Use a simpler model**. Model complexity and overfitting go hand-in-hand.
For example, models like random forests tend to overfit
much more than linear models and SVMs.
- **Use more training samples**. Adding training samples can reduce
the effect of overfitting.
- **Increase Regularization**. Regularization is designed to prevent
overfitting. So increasing regularization
can lead to better results for overfitting models.
These choices become very important in real-world situations, as data collection usually
costs time and energy. If the model is underfitting, then spending weeks or months collecting
more data could be a colossal waste of time! However, more data (usually) gives us a better view
of the true nature of the problem, so these issues should always be carefully considered before
going on a "data foraging expedition".
| github_jupyter |
## Recap
Here's the code you've written so far.
```
# Code you have previously used to load data
import pandas as pd
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
# Path of the file to read
iowa_file_path = '../input/home-data-for-ml-course/train.csv'
home_data = pd.read_csv(iowa_file_path)
# Create target object and call it y
y = home_data.SalePrice
# Create X
features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']
X = home_data[features]
# Split into validation and training data
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)
# Specify Model
iowa_model = DecisionTreeRegressor(random_state=1)
# Fit Model
iowa_model.fit(train_X, train_y)
# Make validation predictions and calculate mean absolute error
val_predictions = iowa_model.predict(val_X)
val_mae = mean_absolute_error(val_predictions, val_y)
print("Validation MAE when not specifying max_leaf_nodes: {:,.0f}".format(val_mae))
# Using best value for max_leaf_nodes
iowa_model = DecisionTreeRegressor(max_leaf_nodes=100, random_state=1)
iowa_model.fit(train_X, train_y)
val_predictions = iowa_model.predict(val_X)
val_mae = mean_absolute_error(val_predictions, val_y)
print("Validation MAE for best value of max_leaf_nodes: {:,.0f}".format(val_mae))
# Set up code checking
from learntools.core import binder
binder.bind(globals())
from learntools.machine_learning.ex6 import *
print("\nSetup complete")
```
# Exercises
Data science isn't always this easy. But replacing the decision tree with a Random Forest is going to be an easy win.
## Step 1: Use a Random Forest
```
from sklearn.ensemble import RandomForestRegressor
# Define the model. Set random_state to 1
rf_model = ____
# fit your model
____
# Calculate the mean absolute error of your Random Forest model on the validation data
rf_val_mae = ____
print("Validation MAE for Random Forest Model: {}".format(rf_val_mae))
# Check your answer
step_1.check()
# The lines below will show you a hint or the solution.
# step_1.hint()
# step_1.solution()
#%%RM_IF(PROD)%%
from sklearn.ensemble import RandomForestRegressor
# Define the model. Set random_state to 1
rf_model = RandomForestRegressor(random_state=1)
# fit your model
rf_model.fit(train_X, train_y)
# Calculate the mean absolute error of your Random Forest model on the validation data
rf_val_predictions = rf_model.predict(val_X)
rf_val_mae = mean_absolute_error(rf_val_predictions, val_y)
print("Validation MAE for Random Forest Model: {:,.0f}".format(rf_val_mae))
step_1.assert_check_passed()
```
So far, you have followed specific instructions at each step of your project. This helped learn key ideas and build your first model, but now you know enough to try things on your own.
Machine Learning competitions are a great way to try your own ideas and learn more as you independently navigate a machine learning project.
#$KEEP_GOING$
| github_jupyter |
# Managing Device Data (C/C++)
#### Sections
- [Learning Objectives](#Learning-Objectives)
- [Data Offload](#Data-Offload)
- [Map Clause](#Map-Clause)
- _Code:_ [Lab Exercise: Map Clause](#Lab-Exercise:-Map-Clause)
- [Dynamically Allocated Data and Length Specification](#Dynamically-Allocated-Data-and-Length-Specification)
- [Target Data Region](#Target-Data-Region)
- _Code:_ [Lab Exercise: Target Data Region](#Lab-Exercise:-Target-Data-Region)
- [Mapping Global Variables to Device](#Mapping-Global-Variables-to-Device)
## Learning Objectives
* Use OpenMP* constructs to effectively manage data transfers to and from the device
* Be able to create a device data environment and map data to the device data environment
* Map global variables to OpenMP devices
### Prerequisites
Basic understanding of OpenMP constructs are assumed for this module. You also should have already went through the [Introduction to OpenMP Offload module](../intro/intro.ipynb) where the basics of using the Jupyter notebooks with the Intel® devcloud and an introduction to the OpenMP `target` constructs were discussed.
***
## Data Offload
The host and devices have separate memory spaces, so when parts of the code are offloaded, data needs to be mapped to the target device in order to be accessed inside the target region.
By default, variables accessed inside the target region are treated as follows:
|Type | Behavior |
|:----:|:----|
|Scalars | Treated as `firstprivate` |
|Static arrays | Copied to the device on entry and from the device to the host on exit |
|Dynamic arrays | Same as above, length must be specified |
In the following example, the compiler will identify all variables that are used in the target region (a, x, and y), and data will be transferred to the device based on the above rules.
```c
void saxpy() {
float a, x[ARRAY_SIZE], y[ARRAY_SIZE];
#pragma omp target
// On entry of target region, a, x, and y copied from host to the device
for (int i=0; i< ARRAY_SIZE; i++) {
y[i] = a * x[i] + y[i];
}
// Upon exit of the target region, both x and y are copied back to the host,
// even though x was not changed.
}
```
## Map Clause
To eliminate unnecessary data copies, use the `map` clause of the `target` directive to manually map variables to the device data environment.
```c
#pragma omp target map (map-type: list)
```
Available *map-type*s are
* `alloc`: Allocate storage for variable on target device, values not copied
* `to`: Allocate storage on target device and assign value **from original host variable to device** on target region entry
* `from`: Allocate storage on target device and assign value **from device to original host variable** on target region exit
* `tofrom`: default, both `to` and `from`
<img src="Assets/mapclause.jpg">
## Lab Exercise: Map Clause
In this exercise you will add a map clause to the saxpy ($y=a*x+y$) operation. The primary source file, main.cpp, is written for you. It includes saxpy_func.cpp that you will complete and write out to file in this Jupyter notebook. If you would like to see the contents of main.cpp, execute the following cell.
```
#Optional, see the contents of main.cpp
%pycat main.cpp
```
In the cell below, add the map clause that would map the x array to the target so that it won't be unnecessarily copied back. Also, add the clause `map(from:is_cpu)` so we'll know whether the code was executed on the GPU.
```
%%writefile lab/saxpy_func.cpp
// Add the target pragma with the map clauses here
{
is_cpu = omp_is_initial_device();
for (i = 0; i < ARRAY_SIZE; i++) {
y[i] = a * x[i] + y[i];
}
}
```
### Compile the Code
Next, compile the code using *compile_c.sh*. If you would like to see the contents of compile_c.sh execute the following cell.
```
# Optional: Run this cell to see the contents of compile_c.sh
%pycat compile_c.sh
```
Execute the following cell to perform the compilation
```
!chmod 755 compile_c.sh; ./compile_c.sh;
```
### Execute the code
Next, run the code using the script *run.sh*.
```
# Optional: Run this cell to see the contents of run.sh
%pycat run.sh
```
Execute the following cell to execute main.cpp. Look for the PASSED! message.
_If the Jupyter cells are not responsive or if they error out when you compile the samples, please restart the Kernel and compile the samples again_
```
! chmod 755 q; chmod 755 run.sh;if [ -x "$(command -v qsub)" ]; then ./q run.sh; else ./run.sh; fi
```
Execute the following cell to see the solution.
```
%pycat saxpy_func_solution.cpp
```
## Dynamically Allocated Data and Length Specification
For dynamically allocated arrays, when using the `target map` construct, the number of elements to be mapped must be explicitly specified. Partial arrays maybe specified.
```c
#pragma omp target map(to:array[start:length])
```
In the previous example, x and y are static arrays, so length specification is optional. If you wish you may go back to the previous example and specify the size of the array to map. Alternatively, you may run the following cell to see the solution.
```
%pycat saxpy_func_solution_length.cpp
```
***
## Target Data Region
When there are more than one target regions, it's often useful to create a larger target **data** region that encompasses all of the target regions to minimize data copy across target regions. There are two ways to create a target data region, using `target data` or using `target enter data` and `target exit data`.
### Target Data
The `target data` construct creates a scoped data environment and maps data to and from the device. When using this construct, the `alloc`, `to`, `from`, and `tofrom` map-types are available.
Note: `Target Data` does not create a target region that offloads execution. `target` constructs inside the data environment is needed to accomplishes that.
```c
#pragma omp target data map(tofrom: x)
// Device data environment created, x stays on the device through out the two target regions
{
#pragma omp target(to: y)
{
// First target region
}
host_update(y); // y must be mapped at each target region because it's being updated by the host
#pragma omp target(to: y)
{
// Second target region
}
}
```
### Target Enter/Exit Data and Update
`target enter/exit data` constructs can be used to explicitly mark the beginning and ending of the target data environment.
When using the `target enter data` construct, only the map-types of `alloc` and `to` are available. When using the `target exit data` construct, the `from`, `release`, and `delete` map-types are available.
The `target update` construct is used to issue data transfers to or from the existing data device environment.
Note: `target enter/exit/update data` constructs are not scoped and does not offload execution of code. `target` constructs are needed between enter and exit of data environment to accomplish that.
Example:
```c
#pragma omp target enter data map(to:y) map(alloc: x)
#pragma omp target
{ //First target region, device operations on x and y
}
#pragma omp target update from (y)
host_update(y);
#pragma omp target update to (y)
#pragma omp target
{ //2nd target region, device operations on x and y
}
#pragma omp target exit data map(from:x)
```
## Lab Exercise: Target Data Region
In this exercise, we have two target regions. x and y are static arrays of size ARRAY_SIZE, and they are used in the target regions. In addition, the value of y is updated by the host between the regions. For this program, *main_data_region.cpp* contains main and includes *target_data_region.cpp*, which is the file you will override.
Create a target data environment that encompasses both target regions, ensure `x` stays on the device across the region and make sure `y` is updated to the device after the host `init2` call. Test your code, and ensure the PASSED message is displayed.
There are two ways to solve this problem. You may choose to use either `target data` or `target enter/update/exit data`. Solution is provided for both.
```
#Examine main_data_region.cpp if you wish.
%pycat main_data_region.cpp
%%writefile lab/target_data_region.cpp
#pragma omp target
{
for (int i = 0; i < ARRAY_SIZE; i++) x[i] += y[i];
}
init2(y, ARRAY_SIZE);
#pragma omp target
{
for (int i = 0; i < ARRAY_SIZE; i++) x[i] += y[i];
}
```
### Compile the Code
```
# Optional: Examine the compile script if you choose
%pycat compile_data_c.sh
#Execute this cell to compile the program, ensure your porgram compiles correctly
! chmod 755 compile_data_c.sh; ./compile_data_c.sh;
```
### Execute the Code
```
# Optional: Examine the run script if you choose
%pycat run_data.sh
#Execute the program, if you see the "FAILED" message, go back and debug your code
! chmod 755 q; chmod 755 run_data.sh;if [ -x "$(command -v qsub)" ]; then ./q run_data.sh; else ./run_data.sh; fi
```
_If the Jupyter cells are not responsive or if they error out when you compile the samples, please restart the Kernel and compile the samples again_
```
#Examine both solutions
%pycat target_data_region_solution.cpp
```
## Mapping Global Variables to Device
With OpenMP, you also have the option to map a variable to the device for the duration of the program. Use the `declare target` directive to specify that variables and functions are mapped to a device. Here's an example.
```c
#pragma omp declare target
int a[N]
#pragma omp end declare target
...
//Host Code
init(a);
#pragma omp target
for (int i=0; i<N; i++) {
result[i]=process(a[i]);
}
```
# Summary
In this module, you have learned the following:
* How OpenMP handles data transfers to the device by default
* Explicitly specify data mapping in the `#pragma omp target` construct with the map clause
* Declare target data region with `target data` and `target enter/exit data` constructs
* Explicitly issue data transfers using the `target update` directive
* Map global variables to the target device
***
@Intel Corporation | [\*Trademark](https://www.intel.com/content/www/us/en/legal/trademarks.html)
| github_jupyter |
# References
Some of the notebooks included in this collection have been borrowed or adapted from the ones available in the [**Introduction to Python**](https://github.com/ehmatthes/intro_programming) project by [Eric Matthes](mailto:ehmatthes@gmail.com).
Documentation
---
For information related to Python programming, always refer to the [official Python documentation](https://docs.python.org/3/) (v3.5.1).
#### Exploring the Python Community
As I have said earlier, the Python community is incredibly rich and diverse. Here are a couple resources to look at, if you want to do some exploring.
- [The Python website](http://python.org/)
The main Python website is probably not of too much interest to you at this point, but it is a great resource to know about as you start to learn more.
<!-- -->
- [PyCon](https://us.pycon.org/)
The Python Conference (PyCon) is an incredible event, and the community is entirely welcoming to new programmers. They happen all over the world, throughout the year. If you can make your way to one of these conferences, you will learn a great deal and meet some really interesting people.
- [PyCon Italia](http://pycon.it)
PyCon Italia is the Italian Python conference where professionals, researchers and lovers of the most beautiful programming language, gather together.
<!-- -->
- [PyLadies](http://www.pyladies.com/)
Women and minorities are still under-represented in most technology fields, and the programming world is no different in this regard. That said, the Python community may well be the most welcoming and supportive programming community for women and minorities. There are a number of groups dedicated to bringing women and minorities together around programming in Python, and there are a number of explicit Codes of Conduct for Python-related events.
PyLadies is one of the most visible of these organizations. They are a great resource, so go see what they do and what they have to offer.
<!-- -->
- [Python User Groups](https://wiki.python.org/moin/LocalUserGroups)
Wherever there are a number of Python programmers, they will find a way to get together. Python user groups are regular meetings of Python users from a local area. Go take a look at the list of user groups, and see if there is one near you.
---
Resources
===
A preliminary list of tutorials, talks, and challenges is provided below. This page will be updated frequently.
Tutorials
--
- Google Python class - YouTube videos
[Part 1(1)](https://www.youtube.com/watch?v=tKTZoB2Vjuk) - Introduction to Python and strings
[Part 1(2)](https://www.youtube.com/watch?v=EPYupizJYQI) - Working with lists, tuples and sorting
[Part 1(3)](https://www.youtube.com/watch?v=haycL41dAhg) - Working with dictionaries and files
[Part 2(1)](https://www.youtube.com/watch?v=kWyoYtvJpe4) - Regular expressions
[Part 2(2)](https://www.youtube.com/watch?v=uKZ8GBKmeDM) - Using modules, system commands
[Part 2(3)](https://www.youtube.com/watch?v=Nn2KQmVF5Og) - Exceptions, parsing URLs
[Part 2(4)](https://www.youtube.com/watch?v=IcteAbMC1Ok) - List comprehensions
- [Guide for beginners who are non-programmers](https://wiki.python.org/moin/BeginnersGuide/NonProgrammers)
Python's wiki page lists several resources for beginners.
- [Python Tutor](http://pythontutor.com/)
Python Tutor visually helps understand how code executes on a computer.
---
Talks
--
Pyvideos - Videos related to Python programming in different events including [Pycon](http://www.pycon.org/), [Scipy](https://conference.scipy.org/).
Example: [Fast Python, Slow Python at Pycon 2014](http://pyvideo.org/video/2627/fast-python-slow-python)
---
Challenges
--
If you are equipped with basics of Python, taking up challenges is a great way to implement the skills.
- [Google Python class exercises](https://developers.google.com/edu/python/exercises/basic)
Four exercises are provided as part of the Python class by Google.
Level - Basic/intermediate
- [Project Euler](https://projecteuler.net/)
Project Euler is a project of mathematical/programming challenges aimed at designing efficient solutions. Project Euler is a good place to challenge your mathematical and programming skills. Most of the problems can be solved within few seconds provided you have an efficient solution.
Level - Advanced | Requires knowledge of mathematics.
- [Python Challenge](http://www.pythonchallenge.com/)
Level - Intermediate/Advanced
| github_jupyter |
# Feature: POS/NER Tag Similarity
Derive bag-of-POS-tag and bag-of-NER-tag vectors from each question and calculate their vector distances.
## Imports
This utility package imports `numpy`, `pandas`, `matplotlib` and a helper `kg` module into the root namespace.
```
from pygoose import *
import os
import warnings
from collections import Counter
from scipy.spatial.distance import cosine, euclidean, jaccard
import spacy
```
## Config
Automatically discover the paths to various data folders and compose the project structure.
```
project = kg.Project.discover()
```
Identifier for storing these features on disk and referring to them later.
```
feature_list_id = 'nlp_tags'
```
## Read Data
Original question datasets.
```
df_train = pd.read_csv(project.data_dir + 'train.csv').fillna('')
df_test = pd.read_csv(project.data_dir + 'test.csv').fillna('')
```
Preprocessed and tokenized questions.
We should not use lowercased tokens here because that would harm the named entity recognition process.
```
tokens_train = kg.io.load(project.preprocessed_data_dir + 'tokens_spellcheck_train.pickle')
tokens_test = kg.io.load(project.preprocessed_data_dir + 'tokens_spellcheck_test.pickle')
df_all_texts = pd.DataFrame(
[[' '.join(pair[0]), ' '.join(pair[1])] for pair in tokens_train + tokens_test],
columns=['question1', 'question2'],
)
```
Dependency parsing takes a lot of time and we don't use any features from it. Let's disable it in the pipeline.
If model loading fails, run `python -m spacy download en`
```
nlp = spacy.load('en', parser=False)
```
## Build Features
```
pos_tags_whitelist = ['ADJ', 'ADV', 'NOUN', 'PROPN', 'NUM', 'VERB']
ner_tags_whitelist = ['GPE', 'LOC', 'ORG', 'NORP', 'PERSON', 'PRODUCT', 'DATE', 'TIME', 'QUANTITY', 'CARDINAL']
num_raw_features = len(pos_tags_whitelist) + len(ner_tags_whitelist)
X1 = np.zeros((len(df_all_texts), num_raw_features))
X2 = np.zeros((len(df_all_texts), num_raw_features))
X1.shape, X2.shape
```
### Collect POS and NER tags
```
pipe_q1 = nlp.pipe(df_all_texts['question1'].values, n_threads=os.cpu_count())
pipe_q2 = nlp.pipe(df_all_texts['question2'].values, n_threads=os.cpu_count())
for i, doc in progressbar(enumerate(pipe_q1), total=len(df_all_texts)):
pos_counter = Counter(token.pos_ for token in doc)
ner_counter = Counter(ent.label_ for ent in doc.ents)
X1[i, :] = np.array(
[pos_counter[pos_tag] for pos_tag in pos_tags_whitelist] +
[ner_counter[ner_tag] for ner_tag in ner_tags_whitelist]
)
for i, doc in progressbar(enumerate(pipe_q2), total=len(df_all_texts)):
pos_counter = Counter(token.pos_ for token in doc)
ner_counter = Counter(ent.label_ for ent in doc.ents)
X2[i, :] = np.array(
[pos_counter[pos_tag] for pos_tag in pos_tags_whitelist] +
[ner_counter[ner_tag] for ner_tag in ner_tags_whitelist]
)
```
### Create tag feature sets
```
df_pos_q1 = pd.DataFrame(
X1[:, 0:len(pos_tags_whitelist)],
columns=['pos_q1_' + pos_tag.lower() for pos_tag in pos_tags_whitelist]
)
df_pos_q2 = pd.DataFrame(
X2[:, 0:len(pos_tags_whitelist)],
columns=['pos_q2_' + pos_tag.lower() for pos_tag in pos_tags_whitelist]
)
df_ner_q1 = pd.DataFrame(
X1[:, -len(ner_tags_whitelist):],
columns=['ner_q1_' + ner_tag.lower() for ner_tag in ner_tags_whitelist]
)
df_ner_q2 = pd.DataFrame(
X2[:, -len(ner_tags_whitelist):],
columns=['ner_q2_' + ner_tag.lower() for ner_tag in ner_tags_whitelist]
)
```
### Compute pairwise distances
```
def get_vector_distances(i):
return [
# POS distances.
cosine(X1[i, 0:len(pos_tags_whitelist)], X2[i, 0:len(pos_tags_whitelist)]),
euclidean(X1[i, 0:len(pos_tags_whitelist)], X2[i, 0:len(pos_tags_whitelist)]),
# NER distances.
euclidean(X1[i, -len(ner_tags_whitelist):], X2[i, -len(ner_tags_whitelist):]),
np.abs(np.sum(X1[i, -len(ner_tags_whitelist):]) - np.sum(X2[i, -len(ner_tags_whitelist):])),
]
warnings.filterwarnings('ignore')
X_distances = kg.jobs.map_batch_parallel(
list(range(len(df_all_texts))),
item_mapper=get_vector_distances,
batch_size=1000,
)
X_distances = np.array(X_distances)
df_distances = pd.DataFrame(
X_distances,
columns=[
'pos_tag_cosine',
'pos_tag_euclidean',
'ner_tag_euclidean',
'ner_tag_count_diff',
]
)
```
### Build master feature list
```
df_master = pd.concat(
[df_pos_q1, df_ner_q1, df_pos_q2, df_ner_q2, df_distances],
axis=1,
ignore_index=True,
)
df_master.columns = list(df_pos_q1.columns) + \
list(df_ner_q1.columns) + \
list(df_pos_q2.columns) + \
list(df_ner_q2.columns) + \
list(df_distances.columns)
df_master.describe().T
X_train = df_master[:len(tokens_train)].values
X_test = df_master[len(tokens_train):].values
print('X train:', X_train.shape)
print('X test: ', X_test.shape)
```
## Save Features
```
feature_names = list(df_master.columns)
project.save_features(X_train, X_test, feature_names, feature_list_id)
```
| github_jupyter |
# Activity Recognition using Machine Learning
In this project, I take the activity recognition dataset. The dataset includes sensor readings of 30 different individuals and the type of activity they were recorded for. Here, I'll use the dataset from Kaggle to classify various activities.
## Import libraries
Let's start by first importing all the necessary libraries. I import `numpy` and `pandas` for managing arrays and dataset. Then, matplotlib in included to be used to create visualisations. To use various machine learning algorithms, I import SVM, Logistic Regression, K Nearest Neighbors Classifier and Random Forest Classifier from sklearn. Also, included is `accuracy_score` to calculate accuracy.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
%matplotlib inline
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
```
## Understand dataset
I first import the dataset using the pandas method `read_csv` into `training_data` and `testing_data`.
```
training_data = pd.read_csv('train.csv')
testing_data = pd.read_csv('test.csv')
```
Next, I analyse the dataset shape to see the number of features and the total dataset records. Also, I check if there are any null values.
```
# For training data
print("Training Data: {}".format(training_data.shape))
print("Null values present in training data: {}".format(training_data.isnull().values.any()))
# For testing data
print("Testing Data: {}".format(testing_data.shape))
print("Null values present in testing data: {}".format(testing_data.isnull().values.any()))
```
There are total 7352 records in the training dataset that we can use. Further, there are no null values in the dataset. This is fortunate and thus, we need not write code to handle null values.
The testing dataset has 2947 records for testing our models. This dataset has no null values.
Next, I check the top 5 rows of train_data using the method `head(5)`.
```
training_data.head(5)
```
From the output above, I can see that there are set of accelerometer and gyroscope sensor values for each record. Further, the last two columns are `subject` which refers to subject number and `Activity` which defines the type of activity. `subject` is of no use to us, so I can drop it safely. The `Activity` column acts as the label `y` and all the rest columns are features `X`. We thus calculate the features and labels for both training and testing data.
```
# Get X and y for training data
y_train = training_data['Activity']
X_train = training_data.drop(columns = ['Activity', 'subject'])
# Get X and y for testing data
y_test = testing_data['Activity']
X_test = testing_data.drop(columns = ['Activity', 'subject'])
```
## Visualize the dataset
We will now visualise the training data to get a better understanding of the available dataset. We begin by visualizing the percentage of data for each type of activity.
```
count_of_each_activity = np.array(y_train.value_counts())
activities = sorted(y_train.unique())
# Plot a pie chart for different activities
plt.rcParams.update({'figure.figsize': [20, 20], 'font.size': 24})
plt.pie(count_of_each_activity, labels = activities, autopct = '%0.2f')
```
The percenage values show that the data size for each activity is comparable. The dataset is equally distributed and will prevent bias.
Next, on inspecting the dataset, we can see that there are many features. It's easy to identify that there are Accelerometer, Gyroscope and some other values in the dataset. We can check the share of each by plotting a bar graph of each type. Accelerometer values have `Acc` in them, Gyroscope values have `Gyro` and rest can be considered as others.
```
# Count for each type
acc = 0
gyro = 0
others = 0
for column in X_train.columns:
if 'Acc' in str(column):
acc += 1
elif 'Gyro' in str(column):
gyro += 1
else:
others += 1
# Show bar plot for the three types
plt.rcParams.update({'figure.figsize': [10, 10], 'font.size': 16})
plt.bar(['Accelerometer', 'Gyroscope', 'Others'], [acc, gyro, others], color = ('r', 'b', 'g'))
```
Accelerometer constitutes the maximum features, followed by Gyroscope. Other features are very less.
### Inspect a particular activity closely
Let's take the example of Standing. We select all rows which have the activity as `STANDING`. The dataset values are recorded as time series. So, we can add time series for each subject. We can then plot their movement as a line graph with X axis as time and Y axis as any specific feature, for example `angle(X,gravityMean)`.
```
standing_activity = training_data[training_data['Activity'] == 'STANDING']
# Reset the index for this dataframe
standing_activity = standing_activity.reset_index(drop=True)
# Set time series for each subject
time = 1
index = 0
time_series = np.zeros(standing_activity.shape[0])
for row_number in range(standing_activity.shape[0]):
if (row_number == 0
or standing_activity.iloc[row_number]['subject'] == standing_activity.iloc[row_number - 1]['subject']):
time_series[index] = time
time += 1
else:
time_series[index] = 1
time = 2
index += 1
# Combine the time_series with the standing_activity dataframe
time_series_df = pd.DataFrame({ 'Time': time_series })
standing_activity_df = pd.concat([standing_activity, time_series_df], axis = 1)
```
For each subject, we can now plot the graph of their angles with time. We use the `cm` subpackage of `matplotlib` to get a set of colors which shall be used for differentiating subjects.
```
colors = cm.rainbow(np.linspace(0, 1, len(standing_activity_df['subject'].unique())))
# Create plot for each subject, which will all be displayed overlapping on one plot
id = 0
for subject in standing_activity_df['subject'].unique():
plt.rcParams.update({'figure.figsize': [40, 30], 'font.size': 24})
plt.plot(standing_activity_df[standing_activity_df['subject'] == subject]['Time'],
standing_activity_df[standing_activity_df['subject'] == subject]['angle(X,gravityMean)'],
c = colors[id],
label = 'Subject ' + str(subject),
linewidth = 4)
plt.xlabel('Time')
plt.ylabel('Angle')
plt.title('Angle between X and mean Gravity v/s Time for various subjects')
plt.legend(prop = {'size': 24})
id += 1
```
Similarly, we can inspect other features as well and check their progress with time.
## Classify activities
To begin, I'll use various machine learning algorithms available inside the sklearn package that I have already imported. For each algorithm, I'll calculate the accuracy of prediction and identify the most accurate algorithm.
For now, I will keep the default values of parameters as defined in `sklearn` for each classifier.
```
accuracy_scores = np.zeros(4)
# Support Vector Classifier
clf = SVC().fit(X_train, y_train)
prediction = clf.predict(X_test)
accuracy_scores[0] = accuracy_score(y_test, prediction)*100
print('Support Vector Classifier accuracy: {}%'.format(accuracy_scores[0]))
# Logistic Regression
clf = LogisticRegression().fit(X_train, y_train)
prediction = clf.predict(X_test)
accuracy_scores[1] = accuracy_score(y_test, prediction)*100
print('Logistic Regression accuracy: {}%'.format(accuracy_scores[1]))
# K Nearest Neighbors
clf = KNeighborsClassifier().fit(X_train, y_train)
prediction = clf.predict(X_test)
accuracy_scores[2] = accuracy_score(y_test, prediction)*100
print('K Nearest Neighbors Classifier accuracy: {}%'.format(accuracy_scores[2]))
# Random Forest
clf = RandomForestClassifier().fit(X_train, y_train)
prediction = clf.predict(X_test)
accuracy_scores[3] = accuracy_score(y_test, prediction)*100
print('Random Forest Classifier accuracy: {}%'.format(accuracy_scores[3]))
```
We can plot a bar graph of the accuracies to compare them visually.
```
colors = cm.rainbow(np.linspace(0, 1, 4))
labels = ['Support Vector Classifier', 'Logsitic Regression', 'K Nearest Neighbors', 'Random Forest']
plt.bar(labels,
accuracy_scores,
color = colors)
plt.xlabel('Classifiers')
plt.ylabel('Accuracy')
plt.title('Accuracy of various algorithms')
```
We can clearly see that `Logistic Regression` performed the best with the highest accuracy.
## Conclusion
In this particular project, I explored the activity recognition dataset. I visualized the data using matplotlib. Then, I applied numerous machine learning algorithms and found out that `Logistic Regression` performed the best in classifying different activities.
| github_jupyter |
#### - Merge Cell painting & L1000 Level-4 data
- Merge both CP and L1000 based on the compounds present in both assays, and make sure the number of replicates for the compounds in both assays per treatment dose are the same, to be able to have an aligned dataset.
#### - Train/Test split the merged Level-4 data
```
import os
import pathlib
import pandas as pd
import numpy as np
import re
from os import walk
from collections import Counter
import random
# Load common compounds
common_file = pathlib.Path(
"..", "..", "6.paper_figures", "data", "significant_compounds_by_threshold_both_assays.tsv.gz"
)
common_df = pd.read_csv(common_file, sep="\t")
common_compounds = common_df.compound.unique()
print(len(common_compounds))
print(common_df.shape)
common_df.head(2)
data_path = '../0.download_cellpainting_L1000_data/data/'
cpd_split_path = '../1.compound_split_train_test/data'
data_path = '../../1.Data-exploration/Profiles_level4/cell_painting/cellpainting_lvl4_cpd_replicate_datasets/'
df_level4_cp = pd.read_csv(
os.path.join(data_path, 'cp_level4_cpd_replicates.csv.gz'),
compression='gzip',
low_memory = False
)
data_path = '../../1.Data-exploration/Profiles_level4/L1000/L1000_lvl4_cpd_replicate_datasets/'
df_level4_L1 = pd.read_csv(
os.path.join(data_path, 'L1000_level4_cpd_replicates.csv.gz'),
compression='gzip',
low_memory = False
)
df_cpds_moas_lincs = pd.read_csv(os.path.join(cpd_split_path, 'split_moas_cpds.csv'))
all_cpds = df_cpds_moas_lincs['pert_iname'].unique()
df_level4_cp = df_level4_cp.loc[df_level4_cp['pert_iname'].isin(all_cpds)].reset_index(drop=True)
df_level4_L1 = df_level4_L1.loc[df_level4_L1['pert_iname'].isin(all_cpds)].reset_index(drop=True)
df_level4_cp['moa'] = df_level4_cp['moa'].apply(lambda x: x.lower())
df_level4_L1['moa'] = df_level4_L1['moa'].apply(lambda x: x.lower())
##sanity check
for cpd in df_level4_cp['pert_iname'].unique():
if cpd not in df_level4_L1['pert_iname'].unique():
print('Some compounds in CP are not found in L1000!!')
len(df_level4_cp['pert_iname'].unique())
len(df_level4_cp['pert_iname'].unique())
df_level4_cp.rename({'Metadata_dose_recode':'dose'}, axis = 1, inplace = True)
##the same columns in Cell painting and L1000;
for col in df_level4_L1.columns:
if col in df_level4_cp.columns.tolist():
print(col)
df_level4_cp.shape
df_level4_L1.shape
def merge_cp_L1000_df(df_cp, df_L1000, all_cpds):
"""
This function merge Cell painting and L1000 level-4 data to one dataframe based on their compounds
args
df_cp: Cell painting Level-4 dataFrame
df_L1: L1000 Level-4 dataFrame
all_cpds: Compounds found in both Cell painting and L1000
return
df_lvl4: merged CP & L1000 dataframe
"""
df_level4_cp_rand = pd.DataFrame(columns = df_cp.columns)
df_level4_L1_rand = pd.DataFrame(columns = df_L1000.columns)
for idx, cpd in enumerate(all_cpds):
df_cpd = df_L1000[df_L1000['pert_iname'] == cpd]
for dose in df_cpd['dose'].unique():
df_dose = df_cpd[df_cpd['dose'] == dose].copy()
df_cpd_cp = df_cp[(df_cp['pert_iname'] == cpd) & (df_cp['dose'] == dose)]
if df_cpd_cp.shape[0] >= df_dose.shape[0]:
df_level4_cp_rand = pd.concat([df_level4_cp_rand,df_cpd_cp.sample(df_dose.shape[0])], ignore_index = True)
df_level4_L1_rand = pd.concat([df_level4_L1_rand,df_dose], ignore_index = True)
else:
df_level4_cp_rand = pd.concat([df_level4_cp_rand,df_cpd_cp], ignore_index = True)
df_level4_L1_rand = pd.concat([df_level4_L1_rand,df_dose.sample(df_cpd_cp.shape[0])], ignore_index = True)
df_level4_cp_rand.rename({'broad_id':'pert_id'}, axis = 1, inplace = True)
df_level4_cp_rand.drop(['dose', 'pert_iname', 'moa', 'pert_id', 'Metadata_broad_sample'], axis = 1, inplace = True)
df_lvl4 = pd.concat([df_level4_cp_rand,df_level4_L1_rand], axis = 1)
return df_lvl4
df_level4 = merge_cp_L1000_df(df_level4_cp, df_level4_L1, all_cpds)
df_level4.shape
def create_moa_targets(df):
"""Create the binary multi-label MOA targets for each compound"""
df['val'] = 1
df_moas_targets = pd.pivot_table(df, values=['val'], index='pert_iname',columns=['moa'], fill_value=0)
df_moas_targets.columns.names = (None,None)
df_moas_targets.columns = df_moas_targets.columns.droplevel(0)
df_moas_targets = df_moas_targets.reset_index().rename({'index':'pert_iname'}, axis = 1)
return df_moas_targets
df_cpds_moas = df_cpds_moas_lincs.copy()
df_moa_targets = create_moa_targets(df_cpds_moas)
df_level4 = df_level4.merge(df_moa_targets, on='pert_iname')
df_level4.shape
```
### - compounds split (80/20) based on MOAs -- based on split_moas_cpds
```
train_cpds = df_cpds_moas_lincs[df_cpds_moas_lincs['train']]['pert_iname'].unique()
test_cpds = df_cpds_moas_lincs[df_cpds_moas_lincs['test']]['pert_iname'].unique()
def train_test_split(train_cpds, test_cpds, df):
df_trn = df.loc[df['pert_iname'].isin(train_cpds)].reset_index(drop=True)
df_tst = df.loc[df['pert_iname'].isin(test_cpds)].reset_index(drop=True)
return df_trn, df_tst
df_level4_trn, df_level4_tst = train_test_split(train_cpds, test_cpds, df_level4)
df_level4_trn.shape
df_level4_tst.shape
```
### - Shuffle train data - 2nd train data
#### - Shuffle the target labels in the train data so that replicates of the same compound/MOA have different MOA labels
```
def create_shuffle_data(df_trn, target_cols):
"""Create shuffled train data where the replicates of each compound are given wrong target labels"""
df_trn_cpy = df_trn.copy()
df_trn_tgts = df_trn_cpy[target_cols].copy()
rand_df = pd.DataFrame(np.random.permutation(df_trn_tgts), columns =df_trn_tgts.columns.tolist())
df_trn_cpy.drop(target_cols, axis = 1, inplace = True)
df_trn_cpy = pd.concat([df_trn_cpy, rand_df], axis = 1)
return df_trn_cpy
target_cols = df_moa_targets.columns[1:]
df_lvl4_trn_shuf = create_shuffle_data(df_level4_trn, target_cols)
df_lvl4_trn_shuf.shape
def save_to_csv(df, path, file_name, compress=None):
"""saves dataframes to csv"""
if not os.path.exists(path):
os.mkdir(path)
df.to_csv(os.path.join(path, file_name), index=False, compression=compress)
L1_cp_level4_path = 'model_data/merged/'
save_to_csv(df_level4, L1_cp_level4_path, 'cp_L1000_lvl4_data.csv.gz', compress="gzip")
save_to_csv(df_level4_trn, L1_cp_level4_path, 'train_lvl4_data.csv.gz', compress="gzip")
save_to_csv(df_level4_tst, L1_cp_level4_path, 'test_lvl4_data.csv.gz', compress="gzip")
save_to_csv(df_lvl4_trn_shuf, L1_cp_level4_path, 'train_shuffle_lvl4_data.csv.gz', compress="gzip")
save_to_csv(df_moa_targets, L1_cp_level4_path, 'target_labels.csv')
```
| 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.
```
# Keras
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/keras"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />Читай на TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/ru/guide/keras.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Запусти в Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/ru/guide/keras.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />Изучай код на GitHub</a>
</td>
</table>
Note: Вся информация в этом разделе переведена с помощью русскоговорящего Tensorflow сообщества на общественных началах. Поскольку этот перевод не является официальным, мы не гарантируем что он на 100% аккуратен и соответствует [официальной документации на английском языке](https://www.tensorflow.org/?hl=en). Если у вас есть предложение как исправить этот перевод, мы будем очень рады увидеть pull request в [tensorflow/docs](https://github.com/tensorflow/docs) репозиторий GitHub. Если вы хотите помочь сделать документацию по Tensorflow лучше (сделать сам перевод или проверить перевод подготовленный кем-то другим), напишите нам на [docs-ru@tensorflow.org list](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ru).
Keras - это высокоуровневый API для создания моделей глубокого обучения.
Он используется для быстрого создания прототипов, сложных исследований,
а также для создания приложений. Три ключевые примущества Keras API:
- *Простота в использовании*<br>
Keras имеет простой интерфейс, оптимизированный для большинства
распространенных задач глубокого обучения. Также он дает конкретные подсказки как быстро
исправить возможные ошибки
- *Модульность*<br>
Модели Keras строятся при помощи объединения нескольких простых модулей, каждый из которых
может быть настроен независимо, и не накладывает каких либо значительных ограничений
- *Легко расширить модель*<br> Ты можешь создавать свои собственные модули,
чтобы свободно выражать свои идеи для исследования. Создавай новые слои,
функции потерь и разрабатывай современные модели глубокого обучения
## Импортируем tf.keras
`tf.keras` - это реализация [спецификации Keras API](https://keras.io){:.external} в TensorFlow.
Это высокоуровневый API для построения
моделей глубокого обучения с первоклассной поддержкой
функционала TensorFlow, например [eager execution](#eager_execution),
конвееры `tf.data` и алгоритмы оценки [Estimators](./estimators.md).
`tf.keras` делает TensorFlow простым в использовании, не теряя в гибкости и производительности.
Чтобы начать, просто импортируй `tf.keras` после TensorFlow в начале кода:
```
# Используй pyyaml если будешь сохранять в формате YAML
!pip install -q pyyaml
from __future__ import absolute_import, division, print_function, unicode_literals, unicode_literals
import tensorflow as tf
from tensorflow.keras import layers
print(tf.VERSION)
print(tf.keras.__version__)
```
`tf.keras` может запускать любой совместимый с Keras код, но тем не менее помни:
* Версия `tf.keras` в последнем релизе TensorFlow может быть не самой
последнией версией `keras`, доступной в PyPI. Всегда проверяй версию при помощи `tf.keras.__version__`
* Когда ты [сохраняешь только веса модели](#weights_only), `tf.keras` по умолчанию
сохраняет их в [формате контрольной точки](./checkpoints.md). Используй `save_format='h5'`
чтобы сохранять как HDF5
## Построим простую модель
### Последовательная модель
В Keras мы используем *слои* для построения *моделей*. Обычно модель - это граф, состоящий из нескольких слоев. Самый распространенный тип модели это стэк идущих друг за другом слоев - последовательная модель `tf.keras.Sequential`.
Для начала давай построим простую полносвязную сеть (или многослойный перцептрон):
```
model = tf.keras.Sequential()
# Добавим в нашу модель слой Dense из 64 блоков:
model.add(layers.Dense(64, activation='relu'))
# И еще один:
model.add(layers.Dense(64, activation='relu'))
# Также добавим слой softmax с 10 выводящими блоками:
model.add(layers.Dense(10, activation='softmax'))
```
### Конфигурация слоев
Существует много разных слоев `tf.keras.layers` с общими параметрами конфигурации:
* `activation`: Устанавливает функцию активации для данного слоя. Этот параметр должен указываться в имени встроенной функции или использоваться как вызываемый объект. По умолчанию активация не используется
* `kernel_initializer` и `bias_initializer`: Инициализация, которая создает веса данного слоя (ядро kernel и смещение bias). Этот параметр используется как имя или вызываемый объект. По умолчанию используется инициализатор `"Glorot uniform"`
* `kernel_regularizer` и `bias_regularizer`: Регуляризация, которая применяется к весам слоя (ядро kernel и смещение bias), например L1 или L2. По умолчанию не используется
Следующий код используется для построения `tf.keras.layers.Dense` с настройкой конфигурации каждого слоя:
```
# Создаем сигмоидный слой:
layers.Dense(64, activation='sigmoid')
# Или:
layers.Dense(64, activation=tf.sigmoid)
# Линейный слой с регуляризацией L1 с коэффицентом 0.01 примененная к ядру матрицы:
layers.Dense(64, kernel_regularizer=tf.keras.regularizers.l1(0.01))
# Линейный слой с регуляризацией L2 с коэффицентом 0.01 примененная к вектору смещения (bias):
layers.Dense(64, bias_regularizer=tf.keras.regularizers.l2(0.01))
# Линейный слой с ядром, инициализированным в случайной прямоугольный матрице:
layers.Dense(64, kernel_initializer='orthogonal')
# Линейный слой с вектором смещения, инициализированным с коэффицентом 2:
layers.Dense(64, bias_initializer=tf.keras.initializers.constant(2.0))
```
## Обучение и оценка
### Настроим конфигурацию обучения
После того как модель построена давай обозначим процесс обучения с помощью метода `compile`:
```
model = tf.keras.Sequential([
# Добавим в нашу модель слой `Dense` из 64 блоков:
layers.Dense(64, activation='relu', input_shape=(32,)),
# И еще один:
layers.Dense(64, activation='relu'),
# Также добавим слой softmax с 10 выводящими блоками:
layers.Dense(10, activation='softmax')])
model.compile(optimizer=tf.train.AdamOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
```
У `tf.keras.Model.compile` есть три важных аргумента:
* `optimizer`: Этот объект определяет процедуру обучения. Мы будем использовать оптимизаторы из модуля `tf.train`, например такие как `tf.train.AdamOptimizer`, `tf.train.RMSPropOptimizer` и `tf.train.GradientDescentOptimizer`
* `loss`: Эта функция минимизации для решения задач оптимизации. Самыми распространенными выборами этого аргумента являются среднеквадратическое отклонение (`mse`), `categorical_crossentropy`, и `binary_crossentropy`. Функции потерь обозначены по имени или используются как вызываемые объекты из модуля `tf.keras.losses`
* `metrics`: Используются для наблюдения за процессом обучения. Используются как строки или вызываемые объекты модуля `tf.keras.metrics`
Ниже пример конфигурации модели для обучения:
```
# Настраиваем регрессию модели, используем среднеквадратическое отклонение
model.compile(optimizer=tf.train.AdamOptimizer(0.01),
loss='mse', # среднеквадратическое отклонение
metrics=['mae']) # средняя абсолютная ошибка
# Настраиваем модель для классификации по категориям
model.compile(optimizer=tf.train.RMSPropOptimizer(0.01),
loss=tf.keras.losses.categorical_crossentropy,
metrics=[tf.keras.metrics.categorical_accuracy])
```
### Используем данные NumPy
При работе с небольшими датасетами мы будем использовать загружаемые в память массивы данных [NumPy](https://www.numpy.org/){:.external} для обучения и оценки моделей. Модель будет "подстраиваться" под тренировочные данные при помощи метода `fit`:
```
import numpy as np
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.fit(data, labels, epochs=10, batch_size=32)
```
У `tf.keras.Model.fit` есть три важных аргумента:
* `epochs`: Процесс обучения структурирован по *эпохам*. Эпоха означает один проход по всему набору входных данных, который происходит небольшими порциями в батчах
* `batch_size`: Когда мы используем массивы NumPy модель делит данные на небольшие батчи и затем выполняет указанное количество проходов. Это число определяет размер батча. Помни, что последний батч может быть меньше если общее количество образцов данных не делится на размер батча
* `validation_data`: Когда мы строим прототип модели, мы хотим легко наблюдать за ее точностью на проверочных данных. При помощи данного аргумента - обычно кортеж или метка - модель будет отображать потери и статистику в режиме выводов inference для прошедших через модель данных в конце каждой эпохи
Вот пример использования `validation_data`:
```
import numpy as np
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
val_data = np.random.random((100, 32))
val_labels = np.random.random((100, 10))
model.fit(data, labels, epochs=10, batch_size=32,
validation_data=(val_data, val_labels))
```
### Используем датасеты tf.data
Чтобы обучать модель на больших датасетах или на нескольких устройствах мы можем воспользоваться [Datasets API](./datasets.md). Просто добавь `tf.data.Dataset` к методу `fit`:
```
# Инициализируем пробную инстанцию датасета:
dataset = tf.data.Dataset.from_tensor_slices((data, labels))
dataset = dataset.batch(32)
dataset = dataset.repeat()
# Не забудь указать количество шагов в каждой эпохе `steps_per_epoch` при использовании метода `fit`
model.fit(dataset, epochs=10, steps_per_epoch=30)
```
Таким образом, метод `fit` использует аргумент `steps_per_epoch` - это количество шагов обучения, которые модель должна сделать прежде, чем перейти на следующую эпоху. Поскольку `Dataset` принимает батчи данных, то в этом примере кода нам не требуется указывать размер батча в `batch_size`.
Также `dataset` можно использовать для проверки точности модели:
```
dataset = tf.data.Dataset.from_tensor_slices((data, labels))
dataset = dataset.batch(32).repeat()
val_dataset = tf.data.Dataset.from_tensor_slices((val_data, val_labels))
val_dataset = val_dataset.batch(32).repeat()
model.fit(dataset, epochs=10, steps_per_epoch=30,
validation_data=val_dataset,
validation_steps=3)
```
### Оценка и предсказание
Методы `tf.keras.Model.evaluate` и `tf.keras.Model.predict` могут использовать данные NumPy и `tf.data.Dataset`.
Используй следующий пример кода для оценки потерь и других показателей предсказаний на использованных данных:
```
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.evaluate(data, labels, batch_size=32)
model.evaluate(dataset, steps=30)
```
Для *предсказания* вывода последнего слоя как массив NumPy, используй следующий код:
```
result = model.predict(data, batch_size=32)
print(result.shape)
```
## Построение сложных моделей
### Функциональный API
Последовательная модель `tf.keras.Sequential` представляет из себя обычное наложение или стек слоев, которые не могут представлять произвольные модели. Используй
[функциональный API Keras ](https://keras.io/getting-started/functional-api-guide/){:.external} для построения комплексных топологий моделей, например таких как:
* Модели с множественными входами данных
* Модели с множественными выводами данных
* Модели с общими слоями, где один и тот же слой вызывается несколько раз
* Модели с непоследовательным потоком данных, например где есть остаточные связи
Построение модели при помощи функционального API выглядит следующим образом:
1. Слой вызывается и возвращает тензор
2. Для определения `tf.keras.Model` используем входные и выводящие тензоры
3. Модель обучается точно так же, как и `Sequential`
Следующий пример показывает как использовать функциональный API для построения простой полносвязной сети:
```
# Возвращает тензор-"заполнитель", который мы используем в качестве примера
inputs = tf.keras.Input(shape=(32,))
# Вызываемый на тензор слой, возвращает тензор
x = layers.Dense(64, activation='relu')(inputs)
x = layers.Dense(64, activation='relu')(x)
predictions = layers.Dense(10, activation='softmax')(x)
```
Обозначим вход и вывод данных нашей модели:
```
model = tf.keras.Model(inputs=inputs, outputs=predictions)
# При помощи метода `compile` настраиваем конфигурацию обучения
model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
# Тренируем модель в течение 5 эпох
model.fit(data, labels, batch_size=32, epochs=5)
```
### Создание подклассов моделей
Также ты можешь создать модель с нуля при помощи подклассов в `tf.keras.Model` и определения собственных прямых проходов. Создавай слои в методе `__init__` и установи их как атрибуты класса. Прямой проход должен быть указан в методе `call`.
Создание подклассов моделей особенно полезно, когда активирован [eager execution](./eager.md), так как прямой проход в этом случае всегда будет записан.
Ключевой момент: всегда используй правильный API для решения конкретной задачи. Поскольку создание подклассов модели предполагает определенную гибкость, эта гибкость осложняет определение структуры и может повлечь больше ошибок у пользователя. Если возможно, то всегда старайся использовать функциональный API.
Смотри следующий пример кода, в котором мы будем использовать подклассы `tf.keras.Model` и собственный прямой проход:
```
class MyModel(tf.keras.Model):
def __init__(self, num_classes=10):
super(MyModel, self).__init__(name='my_model')
self.num_classes = num_classes
# Здесь определим слои
self.dense_1 = layers.Dense(32, activation='relu')
self.dense_2 = layers.Dense(num_classes, activation='sigmoid')
def call(self, inputs):
# А здесь укажем прямой проход,
# используя указанные выше слои (в `__init__`).
x = self.dense_1(inputs)
return self.dense_2(x)
def compute_output_shape(self, input_shape):
# Если ты хочешь использовать подклассы модели
# в функциональном стиле, тогда эта функция будет переписана
# во время запуска кода. В остальных случаях этот метод необязателен.
shape = tf.TensorShape(input_shape).as_list()
shape[-1] = self.num_classes
return tf.TensorShape(shape)
```
Укажем класс новой модели:
```
model = MyModel(num_classes=10)
# При помощи метода `compile` настраиваем конфигурацию обучения
model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
# Обучаем в течение 5 эпох
model.fit(data, labels, batch_size=32, epochs=5)
```
### Создание собственных слоев
Чтобы создать свой собственный слой при помощи подклассов `tf.keras.layers.Layer` нам потребуются следующие методы:
* `build`: Создает веса слоя. Чтобы добавить веса в модель используй метод `add_weight`
* `call`: Определяет прямой проход
* `compute_output_shape`: Определяет как вычислить выводящую форму слоя для данной входной формы
* Также слой можно сериализировать при помощи метода `get_config` и метода класса `from_config`
Вот пример использования нового слоя, в котором мы использовали `matmul` входа с матрицей ядра `kernel`:
```
class MyLayer(layers.Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
shape = tf.TensorShape((input_shape[1], self.output_dim))
# Создаем обучаемую переменную весов для этого слоя
self.kernel = self.add_weight(name='kernel',
shape=shape,
initializer='uniform',
trainable=True)
# Обязательно вызови метод `build` в конце
super(MyLayer, self).build(input_shape)
def call(self, inputs):
return tf.matmul(inputs, self.kernel)
def compute_output_shape(self, input_shape):
shape = tf.TensorShape(input_shape).as_list()
shape[-1] = self.output_dim
return tf.TensorShape(shape)
def get_config(self):
base_config = super(MyLayer, self).get_config()
base_config['output_dim'] = self.output_dim
return base_config
@classmethod
def from_config(cls, config):
return cls(**config)
```
Теперь создадим модель, используя наш новый слой:
```
model = tf.keras.Sequential([
MyLayer(10),
layers.Activation('softmax')])
# При помощи метода `compile` настраиваем конфигурацию обучения
model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
# Обучаем в течение 5 эпох
model.fit(data, labels, batch_size=32, epochs=5)
```
## Функции обратного вызова
Функция обратного вызова `callback` - это объект, который передается модели для обработки и расширения ее поведения во время обучения. Ты можешь написать свою собственную функцию callback, или использовать готовые `tf.keras.callbacks` в которые входят:
* `tf.keras.callbacks.ModelCheckpoint`: Сохраняет контрольные точки твоей модели через заданный интервал
* `tf.keras.callbacks.LearningRateScheduler`: Замедляет темп обучения `learning rate` для получения лучших результатов точности
* `tf.keras.callbacks.EarlyStopping`: Останавливает обучение как только точность перестает увеличиваться
* `tf.keras.callbacks.TensorBoard`: Следит за поведением модели при помощи [TensorBoard](./summaries_and_tensorboard.md)
Чтобы использовать `tf.keras.callbacks.Callback` просто передай его в метод `fit` своей модели:
```
callbacks = [
# Прерывает обучение если потери при проверке `val_loss` перестают
# уменьшаться после 2 эпох
tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),
# Записываем логи TensorBoard в папку `./logs`
tf.keras.callbacks.TensorBoard(log_dir='./logs')
]
model.fit(data, labels, batch_size=32, epochs=5, callbacks=callbacks,
validation_data=(val_data, val_labels))
```
<a id='weights_only'></a>
## Сохранение и загрузка
### Сохраняем веса
Ты можешь сохранять и загружать веса модели при помощи `tf.keras.Model.save_weights`:
```
model = tf.keras.Sequential([
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')])
model.compile(optimizer=tf.train.AdamOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
# Сохраняем веса в контрольную точку формата TensorFlow
model.save_weights('./weights/my_model')
# Восстанавливаем состояние модели,
# требуется использование модели с точно такой же архитектурой
model.load_weights('./weights/my_model')
```
По умолчанию, веса модели сохраняются в формате [контрольой точки TensorFlow](./checkpoints.md). Веса также могут быть сохранены в формате Keras HDF5, который является стандартным в бэкенд структуре Keras:
```
# Сохраняем веса в файл HDF5
model.save_weights('my_model.h5', save_format='h5')
# Загружаем текущее состояние модели
model.load_weights('my_model.h5')
```
### Сохраняем конфигурацию
Конфигурация модели также может быть сохранена: такой метод сериализирует архитектуру модели без сохранения весов.
Сохраненная конфигурация можеть быть загружена и инициализирована как оригинальная модель, даже без кода изначальной модели.
Keras поддерживает форматы сериализации данных JSON и YAML:
```
# Сериализация модели в формат JSON
json_string = model.to_json()
json_string
import json
import pprint
pprint.pprint(json.loads(json_string))
```
Давай воссоздадим только что инициализированную модель из JSON:
```
fresh_model = tf.keras.models.model_from_json(json_string)
```
Сериализация модели в формат YAML требуется установки `pyyaml` *до импорта TensorFlow*:
```
yaml_string = model.to_yaml()
print(yaml_string)
```
Восстановим модель из формата YAML:
```
fresh_model = tf.keras.models.model_from_yaml(yaml_string)
```
Важно: модели с подклассами не могут быть сериализированы, потому что их архитектура определяется кодом Python в методе `call`.
### Сохраняем модель полностью
Мы можем сохранить модель целиком в один файл, который будет содержать веса, конфигурацию модели и даже настройки оптимизатора. Это позволяет сохранить модель как контрольную точку и продолжить обучение позже - ровно с того же момента и без доступа к исходному коду.
```
# Создаем простую модель
model = tf.keras.Sequential([
layers.Dense(10, activation='softmax', input_shape=(32,)),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(data, labels, batch_size=32, epochs=5)
# Сохраняем модель целиком в один файл формата HDF5
model.save('my_model.h5')
# Восстаналиваем ту же самую модель, включая веса и оптимизатор
model = tf.keras.models.load_model('my_model.h5')
```
## Eager execution
[Eager execution](./eager.md) - это окружение императивного программирования, в котором все операции вычисляются мгновенно. В нем не требуется Keras, однако `tf.keras` поддерживается и оказывается весьма полезен для проверки программы и отладки кода.
Все API `tf.keras` для построения моделей совместимы с eager execution. В то время как функциональный API и `Sequential` могут быть использованы и здесь, наибольшее преимущество получат *модели с подклассами* и *модели с собственными слоями* - это именно те API, в которых тебе необходимо указать прямой проход в виде кода (вместо тех API, которые создают модели посредством сборки существующих слоев).
Смотри [Руководство по eager execution](./eager.md#build_a_model) для ознакомления с примерами использования моделей Keras с уникальными циклами обучения `tf.GradientTape`.
## Распределенное обучение
### Алгоритмы оценки Estimators
API [Estimators](./estimators.md) используется для обучения моделей в распределенном окружении. Он необходим для решения задач распределенного обучения на больших датасетах например для экспорта модели в продакшен.
`tf.keras.Model` может обучаться с API `tf.estimator` посредством конвертации модели в объект `tf.estimator.Estimator` при помощи `tf.keras.estimator.model_to_estimator`. Читай больше в статье [Создание Estimators из моделей Keras](./estimators.md#creating_estimators_from_keras_models).
```
model = tf.keras.Sequential([layers.Dense(10,activation='softmax'),
layers.Dense(10,activation='softmax')])
model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
estimator = tf.keras.estimator.model_to_estimator(model)
```
Совет: используй [eager execution](./eager.md) для отладки
[функций входа Estimator](./premade_estimators.md#create_input_functions) и проверки данных.
### Обучение на нескольких GPU
Модели `tf.keras` могут обучаться на нескольких GPU при помощи
`tf.contrib.distribute.DistributionStrategy`. Этот API обеспечивает распределенное обучение на нескольких GPU почти без изменений основного кода модели.
В настоящее время `tf.contrib.distribute.MirroredStrategy` является единственной поддерживаемой стратегией распределенного обучения. `MirroredStrategy` выполняет внутриграфную репликацию с синхронным обучением, используя функцию all-reduce на одном устройстве. Чтобы использовать `DistributionStrategy` вместе с Keras, конвертируй модель `tf.keras.Model` в `tf.estimator.Estimator` при помощи `tf.keras.estimator.model_to_estimator`, а затем обучи получившийся estimator.
В следующем примере мы посмотрим как распределить `tf.keras.Model` на нескольких GPU на одном устройстве.
Для начала определим простую модель:
```
model = tf.keras.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10,)))
model.add(layers.Dense(1, activation='sigmoid'))
optimizer = tf.train.GradientDescentOptimizer(0.2)
model.compile(loss='binary_crossentropy', optimizer=optimizer)
model.summary()
```
Затем определим функцию *загрузки и обработки данных*. Функция `Input_fn` возвращает объект `tf.data.Dataset`, который используется для распределения данных на нескольких устройствах, где каждый GPU обрабатывает свой входящий батч.
```
def input_fn():
x = np.random.random((1024, 10))
y = np.random.randint(2, size=(1024, 1))
x = tf.cast(x, tf.float32)
dataset = tf.data.Dataset.from_tensor_slices((x, y))
dataset = dataset.repeat(10)
dataset = dataset.batch(32)
return dataset
```
Далее, создадим `tf.estimator.RunConfig` и передадим аргумент `train_distribute`
к `tf.contrib.distribute.MirroredStrategy`. При создании
`MirroredStrategy` ты можешь определить список устройств или передать аргумент `num_gpus` с заданным количеством GPU для обучения. По умолчанию используются все доступные GPU как в следующем примере:
```
strategy = tf.contrib.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(train_distribute=strategy)
```
Конвертируем модель Keras в `tf.estimator.Estimator`:
```
keras_estimator = tf.keras.estimator.model_to_estimator(
keras_model=model,
config=config,
model_dir='/tmp/model_dir')
```
Наконец, обучаем `Estimator`, передав аргументы `input_fn` и `steps`:
```
keras_estimator.train(input_fn=input_fn, steps=10)
```
| github_jupyter |
# Initializing a fiber with custom spectroscopy
This short example demonstrates how you can initialize a fiber with your own absorption and emission cross section data. In practice, this example uses the same spectroscopy files for Yb germano-silicate as the demonstration classes YbDopedFiber and YbDopedDoubleCladFiber. You can find the sample files in "pyfiberamp/spectroscopies/fiber_spectra/", which will be in your Python installation's site-packages folder if you have installed PyFiberAmp. It might be easier to locate the files on the [GitHub page](https://github.com/Jomiri/pyfiberamp) instead. Your own files should follow the same format, i.e. be readable with [numpy.loadtxt](https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html) when default parameters are used. The first column in the files should contain wavelength in nanometers and the second column the cross section in m^2. Both "," and "." are accepted as decimal separators.
## Imports
```
from pyfiberamp.spectroscopies import Spectroscopy
from pyfiberamp.fibers import ActiveFiber, DoubleCladFiber
from pyfiberamp.parameters import YB_ABSORPTION_CS_FILE, YB_EMISSION_CS_FILE
```
## 1) Creating a spectroscopy object
```
path_to_absorption_cross_section_file = YB_ABSORPTION_CS_FILE # replace with your own file
path_to_emission_cross_section_file = YB_EMISSION_CS_FILE # replace with your own file
upper_state_lifetime = 1e-3
yb_spectroscopy = Spectroscopy.from_files(
absorption_cross_section_file=path_to_absorption_cross_section_file,
emission_cross_section_file=path_to_emission_cross_section_file,
upper_state_lifetime=upper_state_lifetime,
interpolate='spline') # alternatively: interpolate='linear'
```
## 2) Checking that the spectra and especially the interpolates look correct
Spline interpolation is smoother but does not work well with large gaps in the data. If the interpolates look bad, you can switch to linear interpolation or try to add more data points in the spectrum files. In the case of the sample cross section files, the spline interpolates the data points really well.
```
yb_spectroscopy.plot_gain_and_absorption_spectrum()
```
## 3 a) Initializing a core-pumped fiber with this spectroscopy
```
fiber = ActiveFiber(spectroscopy=yb_spectroscopy,
ion_number_density=1e25,
length=1,
core_radius=3e-6,
core_na=0.10,
background_loss=0)
```
## 3 b) Initializing a double-clad fiber with this spectroscopy
```
double_clad_fiber = DoubleCladFiber(spectroscopy=yb_spectroscopy,
ion_number_density=1e25,
length=1,
core_radius=3e-6,
core_na=0.10,
background_loss=0,
ratio_of_core_and_cladding_diameters=1/10)
```
### The fibers are now ready for use in simulations!
| github_jupyter |
# Machine Learning GridSearch Pipeline
```
# Import libraries
import os
import sys
# cpu_count returns the number of CPUs in the system.
from multiprocessing import cpu_count
import numpy as np
import pandas as pd
# Import metrics
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
# Import preprocessing methods from sklearn
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import MinMaxScaler
# Import PCA
from sklearn.decomposition import PCA
# Import feature_selection tools
from sklearn.feature_selection import VarianceThreshold
# Import models from sklearn
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
# Import XGBClassifier
from xgboost.sklearn import XGBClassifier
# Import from sklearn
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.externals import joblib
from sklearn.base import TransformerMixin
from sklearn.base import BaseEstimator
# Import plotting libraries
import matplotlib.pyplot as plt
# Modify notebook settings
pd.options.display.max_columns = 150
pd.options.display.max_rows = 150
%matplotlib inline
plt.style.use('ggplot')
```
### Create paths to data file, append `src` directory to sys.path
```
# Create a variable for the project root directory
proj_root = os.path.join(os.pardir)
# Save path to the processed data file
# "dataset_processed.csv"
processed_data_file = os.path.join(proj_root,
"data",
"processed",
"dataset_processed.csv")
# add the 'src' directory as one where we can import modules
src_dir = os.path.join(proj_root, "src")
sys.path.append(src_dir)
```
### Create paths to data file, append `src` directory to sys.path
```
# Save the path to the folder that will contain
# the figures for the final report:
# /reports/figures
figures_dir = os.path.join(proj_root,
"reports",
"figures")
```
### Read in the processed data
```
# Read in the processed credit card client default data set.
df = pd.read_csv(processed_data_file,
index_col=0)
df.head()
```
### Train test split
```
# Extract X and y from df
X = df.drop('y', axis=1).values
#y = df[['y']].values
y = df['y'].values
# Train test split
X_train, X_test, y_train, y_test = \
train_test_split(X, y, test_size=0.3, random_state=42)
# Define a function`namestr` to access the name of a variable
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj][0]
# Print the shape of X, y, X_train, X_test, y_train, and y_test
for var in [X, y, X_train, X_test, y_train, y_test]:
print(namestr(var, globals()),
'shape:\t',
var.shape)
```
### Make pipeline
```
df_X = df.drop('y', axis=1)
def create_binary_feature_list(df=df_X,
return_binary_features=True):
"""
Docstring ...
"""
# Create boolean maskDrop the column with the target values
binary_mask = df.isin([0, 1]).all()
# If return_binary_features=True,
# create a list of the binary features.
# If return_binary_features=False,
# create a list of the nonbinary features.
features_list = list(binary_mask[binary_mask == \
return_binary_features].index)
return features_list
def binary_feature_index_list(df=df_X,
features_list=None):
"""
Docstring ...
"""
feature_index_list = [df.columns.get_loc(c) for c \
in df.columns if c in features_list]
return feature_index_list
binary_features = create_binary_feature_list(df=df_X,
return_binary_features=True)
non_binary_features = create_binary_feature_list(df=df_X,
return_binary_features=False)
binary_index_list = \
binary_feature_index_list(df=df_X,
features_list=binary_features)
non_binary_index_list = \
binary_feature_index_list(df=df_X,
features_list=non_binary_features)
print('Binary features:\n')
print(''.join('{:2s}: {:40s}'.format(str(i), col) \
for i, col in zip(binary_index_list,
binary_features)))
print('\n')
print('Non-binary features:\n')
print(''.join('{:2s}: {:40s}'.format(str(i), col) \
for i, col in zip(non_binary_index_list,
non_binary_features)))
```
#### User defined preprocessors
```
class NonBinary_PCA(BaseEstimator, TransformerMixin):
def __init__(self):
self.scaler = PCA(n_components=None, random_state=42)
# Fit PCA only on the non-binary features
def fit(self, X, y):
self.scaler.fit(X[:, non_binary_index_list], y)
return self
# Transform only the non-binary features with PCA
def transform(self, X):
X_non_binary = \
self.scaler.transform(X[:, non_binary_index_list])
X_recombined = X_non_binary
binary_index_list.sort()
for col in binary_index_list:
X_recombined = np.insert(X_recombined,
col,
X[:, col],
1)
return X_recombined
class NonBinary_RobustScaler(BaseEstimator, TransformerMixin):
def __init__(self):
self.scaler = RobustScaler()
# Fit RobustScaler only on the non-binary features
def fit(self, X, y):
self.scaler.fit(X[:, non_binary_index_list], y)
return self
# Transform only the non-binary features with RobustScaler
def transform(self, X):
X_non_binary = \
self.scaler.transform(X[:, non_binary_index_list])
X_recombined = X_non_binary
binary_index_list.sort()
for col in binary_index_list:
X_recombined = np.insert(X_recombined,
col,
X[:, col],
1)
return X_recombined
class NonBinary_StandardScaler(BaseEstimator, TransformerMixin):
def __init__(self):
self.scaler = StandardScaler()
# Fit StandardScaler only on the non-binary features
def fit(self, X, y):
self.scaler.fit(X[:, non_binary_index_list], y)
return self
# Transform only the non-binary features with StandardScaler
def transform(self, X):
X_non_binary = \
self.scaler.transform(X[:, non_binary_index_list])
X_recombined = X_non_binary
binary_index_list.sort()
for col in binary_index_list:
X_recombined = np.insert(X_recombined,
col,
X[:, col],
1)
return X_recombined
class NonBinary_MinMaxScaler(BaseEstimator, TransformerMixin):
def __init__(self):
self.scaler = MinMaxScaler()
# Fit MinMaxScaler only on the non-binary features
def fit(self, X, y):
self.scaler.fit(X[:, non_binary_index_list], y)
return self
# Transform only the non-binary features with MinMaxScaler
def transform(self, X):
X_non_binary = \
self.scaler.transform(X[:, non_binary_index_list])
X_recombined = X_non_binary
binary_index_list.sort()
for col in binary_index_list:
X_recombined = np.insert(X_recombined,
col,
X[:, col],
1)
return X_recombined
```
#### Define the pipeline
```
# Set a high threshold for removing near-zero variance features
#thresh_prob = 0.999
thresh_prob = 0.99
threshold = (thresh_prob * (1 - thresh_prob))
# Create pipeline
pipe = Pipeline([('preprocessing_1', VarianceThreshold(threshold)),
('preprocessing_2', None),
('preprocessing_3', None),
('classifier', DummyClassifier(strategy='most_frequent',
random_state=42))])
# Create parameter grid
param_grid = [
{'classifier': [LogisticRegression(random_state=42)],
'preprocessing_1': [None, NonBinary_RobustScaler()],
'preprocessing_2': [None, NonBinary_PCA()],
'preprocessing_3': [None, VarianceThreshold(threshold)],
'classifier__C': [0.01, 0.1],
'classifier__penalty': ['l1','l2']},
{'classifier': [XGBClassifier(objective='binary:logistic', n_estimators=1000)],
'preprocessing_1': [None, VarianceThreshold(threshold)],
'preprocessing_2': [None],
'preprocessing_3': [None],
'classifier__n_estimators': [1000],
'classifier__learning_rate': [0.01, 0.1],
'classifier__gamma': [0.01, 0.1],
'classifier__max_depth': [3, 4],
'classifier__min_child_weight': [1, 3],
'classifier__subsample': [0.8],
# 'classifier__colsample_bytree': [0.8, 1.0],
'classifier__reg_lambda': [0.1, 1.0],
'classifier__reg_alpha': [0, 0.1]}]
# Set the number of cores to be used
cores_used = cpu_count() - 1
cores_used
cores_used = 1
# Set verbosity
verbosity = 1
# Execute Grid search
grid = GridSearchCV(pipe, param_grid, cv=5, scoring='roc_auc',
verbose=verbosity, n_jobs=cores_used)
grid.fit(X_train, y_train)
print("Best params:\n{}\n".format(grid.best_params_))
print("Best cross-validation score: {:.2f}".format(grid.best_score_))
```
#### Save the grid search object as a pickle file
```
# Save path to the `models` folder
models_folder = os.path.join(proj_root,
"models")
# full_gridsearch_file_name = 'gridsearch_pickle_20171029.pkl'
full_gridsearch_file_name = 'gridsearch_pickle.pkl'
full_gridsearch_path = os.path.join(models_folder,
full_gridsearch_file_name)
joblib.dump(grid, full_gridsearch_path)
# best_pipeline_file_name = 'pipeline_pickle_20171029.pkl'
best_pipeline_file_name = 'pipeline_pickle.pkl'
best_pipeline_path = os.path.join(models_folder,
best_pipeline_file_name)
joblib.dump(grid.best_estimator_, best_pipeline_path)
```
### Grid search for best *logistic regression* model
```
# Create parameter grid
param_grid = [
{'classifier': [LogisticRegression(random_state=42)],
'preprocessing_1': [None], # [VarianceThreshold(threshold)],
'preprocessing_2': [NonBinary_RobustScaler()],
'preprocessing_3': [None, NonBinary_PCA(), VarianceThreshold(threshold)],
'classifier__C': [0.001, 0.01, 0.1, 1, 10, 100],
'classifier__penalty': ['l1','l2']}]
# Set the number of cores to be used
cores_used = cpu_count() - 1
cores_used
cores_used = 1
# Set verbosity
verbosity = 1
# Execute Grid search
logreg_grid = GridSearchCV(pipe, param_grid, cv=5, scoring='roc_auc',
verbose=verbosity, n_jobs=cores_used)
logreg_grid.fit(X_train, y_train)
print("Best logistic regression params:\n{}\n".format(logreg_grid.best_params_))
print("Best cross-validated logistic regression score: {:.2f}".format(logreg_grid.best_score_))
# Save the grid search object as a pickle file
models_folder = os.path.join(proj_root,
"models")
logreg_gridsearch_file_name = 'logreg_gridsearch_pickle.pkl'
logreg_gridsearch_path = os.path.join(models_folder,logreg_gridsearch_file_name)
joblib.dump(logreg_grid, logreg_gridsearch_path)
best_logreg_pipeline_file_name = 'best_logreg_pipeline_pickle.pkl'
best_logreg_pipeline_path = os.path.join(models_folder,
best_logreg_pipeline_file_name)
joblib.dump(logreg_grid.best_estimator_, best_logreg_pipeline_path)
```
#### Read in the best pipeline
```
# best_pipeline_file_name = 'pipeline_pickle_20171029.pkl'
best_pipeline_file_name = 'pipeline_pickle.pkl'
best_pipeline_path = os.path.join(models_folder,
best_pipeline_file_name)
clf = joblib.load(best_pipeline_path)
```
#### Read in the best logistic regression pipeline
```
best_logreg_pipeline_file_name = 'best_logreg_pipeline_pickle.pkl'
best_logreg_pipeline_path = os.path.join(models_folder,
best_logreg_pipeline_file_name)
logreg_clf = joblib.load(best_logreg_pipeline_path)
```
#### Check AUC scores
```
cross_val_results = cross_val_score(clf,
X_train,
y_train,
scoring="roc_auc",
cv=5,
n_jobs=1)
results_mean = np.mean(cross_val_results)
print("Best pipeline:")
print("Mean Cross validation AUC:\n{:.3f}\n".format(results_mean))
cross_val_results_logreg = cross_val_score(logreg_clf,
X_train,
y_train,
scoring="roc_auc",
cv=5,
n_jobs=1)
results_mean_logreg = np.mean(cross_val_results_logreg)
print("Best logistic regression pipeline:")
print("Mean Cross validation AUC:\n{:.3f}\n".format(results_mean_logreg))
```
Best logistic regression pipeline:
Mean Cross validation AUC:
0.771
```
clf.fit(X_train, y_train)
auc_train = roc_auc_score(y_train, clf.predict_proba(X_train)[:,1])
print("Train AUC:\n{:.3f}\n".format(auc_train))
auc_test = roc_auc_score(y_test, clf.predict_proba(X_test)[:,1])
print("Test AUC:\n{:.3f}\n".format(auc_test))
dummy_clf = DummyClassifier(strategy='most_frequent',
random_state=42)
dummy_clf.fit(X_train, y_train)
dummy_auc_train = roc_auc_score(y_train,
dummy_clf.predict_proba(X_train)[:,1])
print("Dummy Train AUC:\n{:.3f}\n".format(dummy_auc_train))
dummy_auc_test = roc_auc_score(y_test,
dummy_clf.predict_proba(X_test)[:,1])
print("Dummy Test AUC:\n{:.3f}\n".format(dummy_auc_test))
```
#### Plot the Receiver Operating Characteristic Curves
```
probs = clf.predict_proba(X_test)
preds = probs[:,1]
fpr, tpr, threshold = roc_curve(y_test, preds)
#roc_auc = auc(fpr, tpr)
roc_auc = roc_auc_score(y_test, preds)
plt.plot(fpr, tpr, 'b', label = 'XGBoost Test AUC = %0.3f' % roc_auc)
probs = logreg_clf.predict_proba(X_test)
preds = probs[:,1]
fpr, tpr, threshold = roc_curve(y_test, preds)
#roc_auc = auc(fpr, tpr)
roc_auc = roc_auc_score(y_test, preds)
plt.plot(fpr, tpr, 'g', label = 'Logistic Regression\nTest AUC = %0.3f' % roc_auc)
#plt.plot([0, 1], [0, 1],'k', label = 'Baseline AUC = 0.500' )
probs = dummy_clf.predict_proba(X_test)
preds = probs[:,1]
fpr, tpr, threshold = roc_curve(y_test, preds)
#roc_auc = auc(fpr, tpr)
roc_auc = roc_auc_score(y_test, preds)
plt.plot(fpr, tpr, 'r--', label = 'Dummy Model AUC = %0.3f' % roc_auc)
plt.title('Receiver Operating Characteristic')
plt.legend(loc = 'lower right')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
# figure file_name
fig_file_name = 'roc_curve'
# figure file_path
fig_path = os.path.join(figures_dir,
fig_file_name)
# Save the figure
plt.savefig(fig_path, dpi = 300)
plt.plot([0, 1], [0, 1],'k', label = 'Baseline AUC = 0.50' )
probs = clf.predict_proba(X_train)
preds = probs[:,1]
fpr, tpr, threshold = roc_curve(y_train, preds)
#roc_auc = auc(fpr, tpr)
roc_auc = roc_auc_score(y_train, preds)
plt.plot(fpr, tpr, 'b', label = 'Train AUC = %0.2f' % roc_auc)
probs = clf.predict_proba(X_test)
preds = probs[:,1]
fpr, tpr, threshold = roc_curve(y_test, preds)
#roc_auc = auc(fpr, tpr)
roc_auc = roc_auc_score(y_test, preds)
plt.plot(fpr, tpr, 'g', label = 'Test AUC = %0.2f' % roc_auc)
probs = dummy_clf.predict_proba(X_test)
preds = probs[:,1]
fpr, tpr, threshold = roc_curve(y_test, preds)
#roc_auc = auc(fpr, tpr)
roc_auc = roc_auc_score(y_test, preds)
plt.plot(fpr, tpr, 'r--', label = 'Dummy Model AUC = %0.2f' % roc_auc)
plt.title('Receiver Operating Characteristic')
plt.legend(loc = 'lower right')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.savefig('roc_curve.png', dpi = 300)
```
#### Check accuracy scores
```
cross_val_accuracy = cross_val_score(clf,
X_train,
y_train,
scoring="accuracy",
cv=5,
n_jobs=1,
verbose=1)
accuracy_mean = np.mean(cross_val_accuracy)
print("Mean Cross validation accuracy:\n{:.3f}\n".format(accuracy_mean))
dummy_cross_val_accuracy = cross_val_score(dummy_clf,
X_train,
y_train,
scoring="accuracy",
cv=5,
n_jobs=1)
dummy_accuracy_mean = np.mean(dummy_cross_val_accuracy)
print("Baseline accuracy:\n{:.3f}\n".format(dummy_accuracy_mean))
accuracy_train = accuracy_score(y_train,
clf.predict(X_train))
print("Train Accuracy:\n{:.3f}\n".format(accuracy_train))
print("Train Error Rate:\n{:.3f}\n".format(1 - accuracy_train))
accuracy_test = accuracy_score(y_test,
clf.predict(X_test))
print("Test Accuracy:\n{:.3f}\n".format(accuracy_test))
print("Test Error Rate:\n{:.3f}\n".format(1 - accuracy_test))
```
### Save the trained model object as a pickle file
```
clf.fit(X_train, y_train)
# trained_model = 'trained_model_20171029.pkl'
trained_model = 'trained_model.pkl'
trained_model_path = os.path.join(models_folder,
trained_model)
joblib.dump(clf, trained_model_path)
```
# Load trained model
```
# Save path to the `models` folder
models_folder = os.path.join(proj_root,
"models")
trained_model = 'trained_model.pkl'
trained_model_path = os.path.join(models_folder,
trained_model)
clf = joblib.load(trained_model_path)
clf
```
# Lift Charts
```
def lift_chart_area_ratio(clf, X, y):
"""
"""
# Create an array of classification thresholds
# ranging from 0 to 1.
thresholds = np.arange(0.0, 1.0001, 0.0001)[np.newaxis, :]
true_actual = (y == 1)[:, np.newaxis]
false_actual = (y != 1)[:, np.newaxis]
predicted_probabilities = clf.predict_proba(X)[:,1][:, np.newaxis]
predicted_true = np.greater(predicted_probabilities, thresholds)
tp = true_actual * predicted_true
fp = false_actual * predicted_true
true_positive_count = np.sum(tp, axis=0)
false_positive_count = np.sum(fp, axis=0)
total = true_positive_count + false_positive_count
# Theoretically best curve
tp_best = np.clip(total, 0, np.max(true_positive_count))
#Calculate area ratio
area_best = np.abs(np.trapz(tp_best, total))
area_model = np.abs(np.trapz(true_positive_count, total))
area_baseline = np.max(total) * np.max(true_positive_count) / 2
area_ratio = (area_model - area_baseline) / \
(area_best - area_baseline)
return area_ratio, true_positive_count, total, tp_best
def plot_lift_chart(total,
true_positive_count,
tp_best,
title,
fname):
"""
"""
plt.plot(total,
true_positive_count,
'r',
label = 'Model Curve')
plt.plot(total,
tp_best,
'b',
label = 'Theoretically Best Curve')
plt.plot([0, np.max(total)],
[0, np.max(true_positive_count)],
'k',
label = 'Baseline Curve' )
plt.title(title)
plt.legend(loc = 'lower right')
plt.xlim(xmin=0)
plt.ylim(ymin=0)
plt.ylabel('True Positives')
plt.xlabel('True Positives + False Positives')
plt.savefig(fname, dpi = 300)
```
#### Train Set Lift Chart Area Ratio
```
area_ratio_train, true_positive_count_train, \
total_train, tp_best_train = \
lift_chart_area_ratio(clf, X_train, y_train)
title = 'Lift Chart - Training Set\n' + \
'(Area Ratio = {:.3f})'.format(area_ratio_train)
# figure file_name
fig_file_name = 'lift_chart_train'
# figure file_path
fig_path = os.path.join(figures_dir,
fig_file_name)
plot_lift_chart(total_train,
true_positive_count_train,
tp_best_train,
title,
fig_path)
print("Area ratio:\t",
"{:.3f}".format(area_ratio_train))
area_ratio_test, true_positive_count_test, \
total_test, tp_best_test = \
lift_chart_area_ratio(clf, X_test, y_test)
title = 'Lift Chart - Test Set\n' + \
'(Area Ratio = {:.3f})'.format(area_ratio_test)
# figure file_name
fig_file_name = 'lift_chart_test'
# figure file_path
fig_path = os.path.join(figures_dir,
fig_file_name)
plot_lift_chart(total_test,
true_positive_count_test,
tp_best_test,
title,
fig_path)
print("Area ratio:\t",
"{:.3f}".format(area_ratio_test))
```
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Классификация текстов обзоров фильмов с Keras и TensorFlow Hub
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/keras/text_classification_with_hub"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />Смотрите на TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ru/tutorials/keras/text_classification_with_hub.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Запустите в Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ru/tutorials/keras/text_classification_with_hub.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />Изучайте код на GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ru/tutorials/keras/text_classification_with_hub.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Скачайте ноутбук</a>
</td>
</table>
Note: Вся информация в этом разделе переведена с помощью русскоговорящего Tensorflow сообщества на общественных началах. Поскольку этот перевод не является официальным, мы не гарантируем что он на 100% аккуратен и соответствует [официальной документации на английском языке](https://www.tensorflow.org/?hl=en). Если у вас есть предложение как исправить этот перевод, мы будем очень рады увидеть pull request в [tensorflow/docs](https://github.com/tensorflow/docs) репозиторий GitHub. Если вы хотите помочь сделать документацию по Tensorflow лучше (сделать сам перевод или проверить перевод подготовленный кем-то другим), напишите нам на [docs-ru@tensorflow.org list](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ru).
В этом уроке мы будем классифицировать обзоры фильмов как *позитивные* или *негативные*, используя текст обзора. Это пример *бинарной* или двуклассовой классификации, важный и широко применяющийся тип задач машинного обучения.
Учебное руководство демонстрирует применение переноса обучения (transfer learning) с использованием TensorFlow Hub и Keras.
Мы будем использовать [набор данных IMDB](https://www.tensorflow.org/api_docs/python/tf/keras/datasets/imdb) содержащий тексты 50,000 обзоров фильмов из [Internet Movie Database](https://www.imdb.com/). Они разделены на 25,000 обзоров для обучения, и 25,000 обзоров для проверки модели. Обучающая и тестовая выборка *сбалансированы*, т.е. содержат одинаковое количество позитивных и негативных обзоров.
Здесь мы будем использовать [tf.keras](https://www.tensorflow.org/guide/keras), высокоуровневый API для построения и обучения моделей в TensorFlow и [TensorFlow Hub](https://www.tensorflow.org/hub), библиотека и платформа для переноса обучения. Для более продвинутого руководства по классификации текстов с использованием `tf.keras`, см. [Руководство по классификации текстов MLCC](https://developers.google.com/machine-learning/guides/text-classification/).
```
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.experimental.list_physical_devices("GPU") else "NOT AVAILABLE")
```
## Скачайте датасет IMDB
Датасет IMDB доступен в [датасетах TensorFlow](https://github.com/tensorflow/datasets). Следующий код скачивает датасет IMDB на ваш компьютер (или в среду выполнения Colab):
```
# Разобьем обучающую выборку в пропорции 60% на 40%, и у нас будет 15,000 примеров
# для обучения, 10,000 примеров для валидации и 25,000 примеров для проверки.
train_validation_split = tfds.Split.TRAIN.subsplit([6, 4])
(train_data, validation_data), test_data = tfds.load(
name="imdb_reviews",
split=(train_validation_split, tfds.Split.TEST),
as_supervised=True)
```
## Исследуйте данные
Давайте уделим немного времени, чтобы разобраться в формате данных. Каждый пример представляет собой предложение являющееся обзором фильма и соответствующую метку. Предложение никак не предобработано. Метка является целым числом, 0 или 1, где 0 - это отрицательный отзыв, а 1 - положительный.
Выведем первые 10 примеров.
```
train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))
train_examples_batch
```
Также напечатаем первые 10 меток.
```
train_labels_batch
```
## Постройте модель
Нейронная сеть создается послойно - это требует три основных архитектурных решения:
* Как представить текст?
* Сколько слоев использовать в модели?
* Сколько *скрытых нейронов* использовать в каждом слое?
В этом примере, входные данные состоят из предложений. Метки которые нужно предсказать являются 0 либо 1.
Одним из способов представления текста является преобразование предложений в векторные представления слов. Мы можем использовать предварительно обученное векторное представление текста в качестве первого слоя. Это имеет три преимущества:
* нам не нужно беспокоиться о препроцессинге текста,
* мы можем извлечь выгоду из переноса обучения,
* векторное представление фиксированного размера, поэтому его проще обрабатывать.
Для этого примера мы используем **предобученную модель векторного представления текста** из [TensorFlow Hub](https://www.tensorflow.org/hub) называемую [google/tf2-preview/gnews-swivel-20dim/1](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1).
Есть еще три другие предварительно обученных модели подходящие для этого руководства:
* [google/tf2-preview/gnews-swivel-20dim-with-oov/1](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim-with-oov/1) - аналогичная [google/tf2-preview/gnews-swivel-20dim/1](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1), но с 2.5% словаря конвертированного в OOV buckets. Это может помочь, если словарь задачи и словарь модели не полностью совпадают.
* [google/tf2-preview/nnlm-en-dim50/1](https://tfhub.dev/google/tf2-preview/nnlm-en-dim50/1) - Намного большая модель с размером словаря ~1M и размерностью вложения 50.
* [google/tf2-preview/nnlm-en-dim128/1](https://tfhub.dev/google/tf2-preview/nnlm-en-dim128/1) - Еще большая модель с размером словаря ~1M и размерностью вложения 128.
Давайте сначала создадим слой Keras, который использует модель TensorFlow Hub для векторного представления предложений, и опробуем его на нескольких входных примерах. Обратите внимание, что независимо от длины входного текста, размерность векторного представления будет следующей: `(num_examples, embedding_dimension)`
```
embedding = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(embedding, input_shape=[],
dtype=tf.string, trainable=True)
hub_layer(train_examples_batch[:3])
```
Давайте построим полную модель:
```
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
model.summary()
```
Для построения классификатора зададим слои последовательно:
1. Первый слой это слой TensorFlow Hub. Этот слой использует предобученную Saved Model, отображающую предложения в векторные представления. Предобученная модель векторного представления слов которую мы используем ([google/tf2-preview/gnews-swivel-20dim/1](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1)) разбивает предложение на токены, встраивает каждый токен и затем объединяет вложения. В результате получаются размерности: `(num_examples, embedding_dimension)`.
2. Получившийся в результате вектор фиксированной длины пропускается сквозь полносвязный (`Dense`) слой состоящий из 16 скрытых нейронов.
3. Последний слой плотно связан с единственным выходным нейроном. С использованием функции активации `сигмоида`, значение получается между 0 и 1, представляя вероятность или уровень доверия.
Давайте скомпилируем модель.
### Функция потерь и оптимизатор
Для модели нам необходимо указать функцию потерь и оптимизатор для обучения. Поскольку мы решаем задачу бинарной классификации и на выходе модели будут вероятности (слой из единственного элемента с сигмоидой в качестве функции активации), то мы воспользуемся функцией потерь binary_crossentropy (пер. "Перекрестная энтропия").
Это не единственный выбор для функции потерь: Вы можете, например, выбрать `mean_squared_error`. Но обычно `binary_crossentropy` лучше справляется с вероятностями - она измеряет "дистанцию" между распределениями вероятностей, или, как в нашем случае, между истинным распределением и предсказаниями.
Далее, когда мы исследуем задачи регрессии (например, предсказание цен на недвижимость), мы посмотрим как использовать другую функцию потерь, которая называется среднеквадратическая ошибка (MSE).
А сейчас настроим модель с использованием оптимизатора и функции потерь:
```
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
```
## Обучите модель
Обучите модель за 20 эпох в мини-батчах по 512 образцов. Это 20 итераций по всем образцам данных в тензорах `x_train` и `y_train`. Во время обучениЯ следите за функцией потерь и точностью на 10 000 примеров из проверочного набора данных:
```
history = model.fit(train_data.shuffle(10000).batch(512),
epochs=20,
validation_data=validation_data.batch(512),
verbose=1)
```
## Оцените модель
Давайте посмотрим как работает модель. Она будет возвращать два значения. Потери (число, показывающее нашу ошибку, меньшие значения - лучше) и точность (accuracy).
```
results = model.evaluate(test_data.batch(512), verbose=2)
for name, value in zip(model.metrics_names, results):
print("%s: %.3f" % (name, value))
```
Этот довольно наивный подход достиг точности около 87%. С более продвинутыми методами модель бы приблизилась к 95%.
## Для дальнейшего чтения
Для более общего способа работы со строковыми входными данными и более подробного анализа прогресса точности и потерь во время обучения, взгляните [сюда](https://www.tensorflow.org/tutorials/keras/basic_text_classification).
| github_jupyter |
<p><img src="https://oceanprotocol.com/static/media/banner-ocean-03@2x.b7272597.png" alt="drawing" width="800" align="center"/>
<h1><center>Ocean Protocol - Manta Ray project</center></h1>
<h3><center>Decentralized Data Science and Engineering, powered by Ocean Protocol</center></h3>
<p>Version 0.6.6 - beta</p>
<p>Package compatibility: squid-py v0.9.2, keeper-contracts 0.13.2, utilities 0.3.0,
<p>Component compatibility (Nile): Brizo v0.9.4, Aquarius v1.0.7, Nile testnet smart contracts 0.13.2</p>
<p><a href="https://github.com/oceanprotocol/mantaray">mantaray on Github</a></p>
<p>
# Getting Underway - Publishing assets
In this notebook, we will explore how to publish an Asset using Ocean Protocol. An Asset consists of several files
which are kept private, and optionally other links which are open (samples, descriptions, etc.).
A publisher will require access to two services;
1. A service to store the MetaData of the asset (part of the DDO) - 'Aquarius'
1. A service to manage permissioned access to the assets - 'Brizo'
The publishing of an asset consists of;
1. Preparing the asset files locally
1. Preparing the metadata of the asset
1. Uploading assets or otherwise making them available as URL's
1. Registering the metadata and service endpoints into Aquarius
1. Registering the asset into the Blockchain (into the DID Registry)
<p><img src="https://raw.githubusercontent.com/oceanprotocol/mantaray/develop/doc/img/jupyter_cell.png" alt="drawing" width="400" align="center"/></p>
<p><b>Overall client and service architecture</b></p>
### Section 0: Import modules, connect the Ocean Protocol API
```
# Standard imports
import json
import logging
import os
from pathlib import Path
from time import sleep
# Import mantaray and the Ocean API (squid)
import random
import squid_py
from mantaray_utilities.user import create_account
from ocean_keeper.web3_provider import Web3Provider
from ocean_utils.did import did_to_id
from squid_py.ocean.ocean import Ocean
from squid_py.config import Config
from mantaray_utilities import logging as manta_logging, config
from mantaray_utilities.misc import get_metadata_example
from pprint import pprint
# Setup logging
manta_logging.logger.setLevel('INFO')
print("squid-py Ocean API version:", squid_py.__version__)
# Get the configuration file path for this environment
OCEAN_CONFIG_PATH = Path(os.path.expanduser(os.environ['OCEAN_CONFIG_PATH']))
assert OCEAN_CONFIG_PATH.exists(), "{} - path does not exist".format(OCEAN_CONFIG_PATH)
logging.critical("Configuration file selected: {}".format(OCEAN_CONFIG_PATH))
logging.critical("Deployment type: {}".format(config.get_deployment_type()))
logging.critical("Squid API version: {}".format(squid_py.__version__))
# Instantiate Ocean with the default configuration file.
configuration = Config(OCEAN_CONFIG_PATH)
squid_py.ConfigProvider.set_config(configuration)
ocn = Ocean(configuration)
faucet_url = ocn.config.get('keeper-contracts', 'faucet.url')
```
### Section 1: A publisher account in Ocean
```
# Get a publisher account
publisher_acct = create_account(faucet_url, wait=True)
print("Publisher account address: {}".format(publisher_acct.address))
print("Publisher account Testnet 'ETH' balance: {:>6.1f}".format(ocn.accounts.balance(publisher_acct).eth/10**18))
print("Publisher account Testnet Ocean balance: {:>6.1f}".format(ocn.accounts.balance(publisher_acct).ocn/10**18))
```
Your account will need some Ocean Token to make real transactions, let's ensure that you are funded!
```
# ensure Ocean token balance
# if ocn.accounts.balance(publisher_acct).ocn == 0:
# ocn.accounts.request_tokens(publisher_acct, 100)
```
### Section 2: Create the Metadata for your asset
The metadata is a key-value set of attributes which describe your asset
A more complex use case is to manually generate your metadata conforming to Ocean standard, but for demonstration purposes,
a utility in squid-py is used to generate a sample Meta Data dictionary.
```
# Get a simple example of Meta Data from the library directly
metadata = get_metadata_example()
print('Name of asset:', metadata['main']['name'])
# Print the entire (JSON) dictionary
pprint(metadata)
```
Note that the price is included in the Metadata! This will be purchase price you are placing on the asset. You can
Alter the metadata object at any time before publishing.
```
print("Price of Asset:", metadata['main']['price'])
metadata['main']['price'] = "9" # Note that price is a string
print("Updated price of Asset:", metadata['main']['price'])
```
Let's inspect another important component of your metadata - the actual asset files. The files of an asset are
described by valid URL's. You are responsible for ensuring the URL's are alive. Files may have additional
information, including a checksum, length, content type, etc.
```
for i, file in enumerate(metadata['main']['files']):
print("Asset link {}: {}".format( i, file['url']))
```
## Section 3 Publish the asset
With this metadata object prepared, we are ready to publish the asset into Ocean Protocol.
The result will be an ID string (DID) registered into the smart contract, and a DID Document stored in Aquarius.
The asset URLS's are encrypted upon publishing.
```
ddo = ocn.assets.create(metadata, publisher_acct)
registered_did = ddo.did
print("New asset registered at", registered_did)
```
Inspect the new DDO. We can retrieve the DDO as a dictionary object, feel free to explore the DDO in the cell below!
```
ddo_dict = ddo.as_dictionary()
print("DID:", ddo.did)
print("Services within this DDO:")
for svc in ddo_dict['service']:
print(svc['type'], svc['serviceEndpoint'])
```
Note that the 'files' attribute has been modified - all URL's are now removed, and a new 'encryptedFiles'
attribute is created to store the actual URLs.
```
for file_attrib in ddo.metadata['main']['files']:
assert 'url' not in file_attrib
print("Encrypted files decrypt on purchase! Cipher text: [{}...] . ".format(ddo.metadata['encryptedFiles'][:50]))
```
## Section 4: Verify your asset
Now, let's verify that this asset exists in the MetaData storage.
A call to assets.resolve() will call the Aquarius service and retrieve the DID Document
```
#+attr_jupyter: some cell metadata stuff
#+attr_jupyter: some other metadata stuff
# TODO: Better handling based on reciept
print("Wait for the transaction to complete!")
sleep(10)
web3 = Web3Provider.get_web3()
event = ocn.keeper.did_registry.subscribe_to_event(
ocn.keeper.did_registry.DID_REGISTRY_EVENT_NAME,
30,
{'_did': web3.toBytes(hexstr=ddo.asset_id)},
from_block=0,
wait=True
)
ddo = ocn.assets.resolve(registered_did)
print("Asset '{}' resolved from Aquarius metadata storage: {}".format(ddo.did, ddo.metadata['main']['name']))
```
Similarly, we can verify that this asset is registered into the blockchain, and that you are the owner.
```
# We need the pure ID string as in the DID registry (a DID without the prefixes)
asset_id = did_to_id(registered_did)
owner = ocn.keeper.did_registry.contract_concise.getDIDOwner(asset_id)
print("Asset ID", asset_id, "owned by", owner)
assert str.lower(owner) == str.lower(publisher_acct.address)
```
Congratulations on publishing an Asset into Ocean Protocol!
Next, let's search for our assets in Ocean Protocol
| github_jupyter |
# Symmetric Interior Penalty for the Poisson Equation
## What's new
- Symmetric Interior Penalty method (SIP)
- investigating matrix properties
## Prerequisites
- basics SIP method
- spatial operator, chapter corresponding to the SpatialOperator
- implementing numerical fluxes and convergence study, chapter corresponding to the NumericalFluxex
## Problem statement
We consider the 2D Poisson problem:
$$ \Delta u = f(x,y) $$
where $f(x,y) \neq 0$ is an arbitrary function of $x$ and/or $y$.
Within this exercise, we are going to investigate the Symmetric Interior Penalty discretization method (SIP) for the Laplace operator
$$a_{\text{sip}}(u,v)
= \int_{\Omega} \underbrace{\nabla u \cdot \nabla v}_{\text{Volume\ term}}dV
- \oint_{\Gamma \setminus \Gamma_{N }} \underbrace{
M(\nabla u) \cdot n_{\Gamma}J(v)
}_{\text{consistency term}} + \underbrace{
M(\nabla v) \cdot \vec{n}_{\Gamma} J(u)
}_{\text{symmetry term}} dA
+ \oint_{\Gamma \setminus \Gamma_{N}} \underbrace{
\eta J(u)J(v)
}_{\text{penalty term}} dA$$
Where $M$ shall denote the Mean and $J$ the Jump operator. The use of these fluxes including a penalty term stabilizes the DG-discretization for the Laplace operator.
## Solution within the **BoSSS** framework
First, we initialize the new worksheet;
Note:
1. This tutorial can be found in the source code repository as as `sip.ipynb`.
One can directly load this into Jupyter to interactively work with the following code examples.
2. **In the following line, the reference to `BoSSSpad.dll` is required**.
You must either set `#r "BoSSSpad.dll"` to something which is appropirate for your computer
(e.g. `C:\Program Files (x86)\FDY\BoSSS\bin\Release\net5.0\BoSSSpad.dll` if you installed the binary distribution),
or, if you are working with the source code, you must compile `BoSSSpad` and put it side-by-side to this worksheet file
(from the original location in the repository, you can use the scripts `getbossspad.sh`, resp. `getbossspad.bat`).
```
#r "BoSSSpad.dll"
using System;
using System.Collections.Generic;
using System.Linq;
using ilPSP;
using ilPSP.Utils;
using BoSSS.Platform;
using BoSSS.Foundation;
using BoSSS.Foundation.Grid;
using BoSSS.Foundation.Grid.Classic;
using BoSSS.Foundation.IO;
using BoSSS.Solution;
using BoSSS.Solution.Control;
using BoSSS.Solution.GridImport;
using BoSSS.Solution.Statistic;
using BoSSS.Solution.Utils;
using BoSSS.Solution.Gnuplot;
using BoSSS.Application.BoSSSpad;
using BoSSS.Application.XNSE_Solver;
using static BoSSS.Application.BoSSSpad.BoSSSshell;
Init();
```
We need the following packages:
```
using ilPSP.LinSolvers;
using ilPSP.Connectors.Matlab;
```
BoSSScmdSilent BoSSSexeSilent
```
using NUnit.Framework;
```
## Implementation of the SIP fluxes
We are going to implement the SIP-form
$$
a_{\text{sip}}(u,v)
= \int_{\Omega} \underbrace{\nabla u \cdot \nabla v}_{\text{volume\ term}}dV
- \oint_{\Gamma \setminus \Gamma_{N }} \underbrace{
M {\nabla u} \cdot n_{\Gamma}J(v)
}_{\text{consistency term}} + \underbrace{
M{\nabla v} \cdot \vec{n}_{\Gamma} J(u)
}_{\text{symmetry term}} dA
+ \oint_{\Gamma \setminus \Gamma_{N}} \underbrace{
\eta J(u)J(v)
}_{\text{penalty term}} dA
$$
First, we need a class in which the integrands are defined.
This also includes some technical aspects like the *TermActivationFlags*.
```
public class SipLaplace :
BoSSS.Foundation.IEdgeForm, // edge integrals
BoSSS.Foundation.IVolumeForm, // volume integrals
IEquationComponentCoefficient // update of coefficients (e.g. length scales) required for penalty parameters
{
/// We do not use parameters (e.g. variable viscosity, ...)
/// at this point: so this can be null
public IList<string> ParameterOrdering {
get { return new string[0]; }
}
/// but we have one argument variable, $u$ (our trial function)
public IList<String> ArgumentOrdering {
get { return new string[] { "u" }; }
}
/// The \code{TermActivationFlags} tell \BoSSS which kind of terms,
/// i.e. products of u, v, \nabla u, and \nabla v
/// the VolumeForm(...) actually contains.
/// This additional information helps to improve the performance.
public TermActivationFlags VolTerms {
get {
return TermActivationFlags.GradUxGradV;
}
}
/// activation flags for the 'InnerEdgeForm(...)'
public TermActivationFlags InnerEdgeTerms {
get {
return (TermActivationFlags.AllOn);
// if we do not care about performance, we can activate all terms.
}
}
public TermActivationFlags BoundaryEdgeTerms {
get {
return TermActivationFlags.AllOn;
}
}
/// For the computation of the penalty factor $\eta$,
/// we require
/// some length scale for each cell and
/// the polynomial degree of the DG approximation.
MultidimensionalArray cj;
double penalty_base; // base factor must be scaled by polynomial degree
/// The additional scaling of the penalty by polynomial degree
/// and in depencence of geometry can be obtained through
/// impmenting the \code{IEquationComponentCoefficient} interface:
public void CoefficientUpdate(CoefficientSet cs, int[] DomainDGdeg, int TestDGdeg) {
int D = cs.GrdDat.SpatialDimension;
double _D = D;
double _p = DomainDGdeg.Max();
double penalty_deg_tri = (_p + 1) * (_p + _D) / _D; // formula for triangles/tetras
double penalty_deg_sqr = (_p + 1.0) * (_p + 1.0); // formula for squares/cubes
penalty_base = Math.Max(penalty_deg_tri, penalty_deg_sqr); // the conservative choice
//Console.WriteLine("Setting penalty base factor for deg " + _p + " to " + penalty_base);
cj = ((GridData)(cs.GrdDat)).Cells.cj;
}
/// The safety factor for the penalty factor should be in the order of 1.
/// A very large penalty factor increases the condition number of the
/// system, but without affecting stability.
/// A very small penalty factor yields to an unstable discretization.
public double PenaltySafety = 2.2;
/// The actual computation of the penalty factor, which should be
/// used in the \code{InnerEdgeForm} and \code{BoundaryEdgeForm} functions.
/// Hint: for the parameters \code{jCellIn}, \code{jCellOut} and \code{g},
/// take a look at
/// \code{CommonParams} and \code{CommonParamsBnd}.
double PenaltyFactor(int jCellIn, int jCellOut) {
double cj_in = cj[jCellIn];
double eta = penalty_base * cj_in * PenaltySafety;
if(jCellOut >= 0) {
double cj_out = cj[jCellOut];
eta = Math.Max(eta, penalty_base * cj_out * PenaltySafety);
}
return eta;
}
/// The following functions cover the actual math.
/// For any discretization of the Laplace operator, we have to specify:
///
/// - a volume integrand,
/// - an edge integrand for inner edges, i.e. on $\Gamma_i$,
/// - an edge integrand for boundary edges, i.e. on $\partial \Omega$.
///
/// The integrand for the volume integral:
public double VolumeForm(ref CommonParamsVol cpv,
double[] U, double[,] GradU, // the trial-function u
// (i.e. the function we search for) and its gradient
double V, double[] GradV // the test function;
) {
double acc = 0;
for(int d = 0; d < cpv.D; d++)
acc += GradU[0, d] * GradV[d];
return acc;
}
/// The integrand for the integral on the inner edges,
///
/// -( M{\nabla u} J{v}) \cdot \vec{n}_{\Gamma}
/// -( M{\nabla v} J{u}) \cdot \vec{n}_{\Gamma}
/// + \eta J{u} J{v} :
///
public double InnerEdgeForm(ref CommonParams inp,
double[] U_IN, double[] U_OT, double[,] GradU_IN, double[,] GradU_OT,
double V_IN, double V_OT, double[] GradV_IN, double[] GradV_OT) {
double eta = PenaltyFactor(inp.jCellIn, inp.jCellOut);
double Acc = 0.0;
for(int d = 0; d < inp.D; d++) { // loop over vector components
// consistency term: -({{ \/u }} [[ v ]])*Normal
// index d: spatial direction
Acc -= 0.5 * (GradU_IN[0, d] + GradU_OT[0, d])*(V_IN - V_OT)
* inp.Normal[d];
// symmetry term: -({{ \/v }} [[ u ]])*Normal
Acc -= 0.5 * (GradV_IN[d] + GradV_OT[d])*(U_IN[0] - U_OT[0])
* inp.Normal[d];
}
// penalty term: eta*[[u]]*[[v]]
Acc += eta*(U_IN[0] - U_OT[0])*(V_IN - V_OT);
return Acc;
}
/// The integrand on boundary edges, i.e. on $\partial \Omega$, is
///
/// -( M{\nabla u} J{v}) \cdot \vec{n}_{\Gamma}
/// -( M{\nabla v} J{u}) \cdot \vec{n}_{\Gamma}
/// + \eta J{u} J{v} .
///
/// For the boundary we have to consider the special definition for
/// the mean-value operator $M{-}$ and the jump operator
/// $J{-}$ on the boundary.
public double BoundaryEdgeForm(ref CommonParamsBnd inp,
double[] U_IN, double[,] GradU_IN, double V_IN, double[] GradV_IN) {
double eta = PenaltyFactor(inp.jCellIn, -1);
double Acc = 0.0;
for(int d = 0; d < inp.D; d++) { // loop over vector components
// consistency term: -({{ \/u }} [[ v ]])*Normale
// index d: spatial direction
Acc -= (GradU_IN[0, d])*(V_IN) * inp.Normal[d];
// symmetry term: -({{ \/v }} [[ u ]])*Normale
Acc -= (GradV_IN[d])*(U_IN[0]) * inp.Normal[d];
}
// penalty term: eta*[[u]]*[[v]]
Acc += eta*(U_IN[0])*(V_IN);
return Acc;
}
}
/*
// An alternative implementation which derives from the build-in, pre-defined SIP implementation:
public class SipLaplace : BoSSS.Solution.NSECommon.SIPLaplace {
public SipLaplace() : base(2.2, "u") { }
public double PenaltySafety {
get { return base.m_penalty_base; }
set { base.m_penalty_base = value; }
}
protected override bool IsDirichlet(ref CommonParamsBnd inp) {
if(Math.Abs(Math.Abs(inp.X.y) - 1.0) < 1.0e-8)
return false; // Neumann b.c. @ y == +1,-1
else
return true; // Dirichlet b.c. @ x = +1,-1
}
override public double Nu(double[] x, double[] p, int jCell) {
return -1.0;
}
}*/
```
## Evaluation of the Poisson operator in 1D
We consider the following problem:
$$
\Delta u = 2,\quad -1<x<1,\quad u(-1)=u(1)=0.
$$
The solution is $u_{ex}(x) = 1 - x^2$. Since this is quadratic, we can represent it **exactly** in a DG space of order 2.
As usual, we have to set up a grid, a basis and a right-hand-side.:
```
var grd1D = Grid1D.LineGrid(GenericBlas.Linspace(-1,1,10));
var DGBasisOn1D = new Basis(grd1D, 2);
var RHS = new SinglePhaseField(DGBasisOn1D, "RHS");
RHS.ProjectField((double x) => 2);
var i_SipLaplace = new SipLaplace();
var Operator_SipLaplace = i_SipLaplace.Operator();
```
We now want to calculate the residual after inserting the exact solution as well as a wrong solution.
The implementation of the exact solution:
```
var u_ex = new SinglePhaseField(DGBasisOn1D, "$u_{ex}$");
u_ex.ProjectField((double x) => 1.0 - x*x);
```
The implementation of a spurious, i.e. a wrong solution; we take the exact solution and add random values in each cell:
```
var u_wrong = new SinglePhaseField(DGBasisOn1D, "$u_{wrong}$");
u_wrong.ProjectField((double x) => 1.0 - x*x);
Random R = new Random();
for(int j = 0; j < grd1D.GridData.Cells.NoOfLocalUpdatedCells; j++){
double ujMean = u_wrong.GetMeanValue(j);
ujMean += R.NextDouble();
u_wrong.SetMeanValue(j, ujMean);
}
```
Evaluating the Laplace operator using the different solutions:
```
var Residual = new SinglePhaseField(DGBasisOn1D,"Resi1");
var ResidualNorm = new List<double>();
foreach(var u in new DGField[] {u_ex, u_wrong}) {
Residual.Clear();
Operator_SipLaplace.Evaluate(u, Residual); // evaluate
Residual.Acc(-1.0, RHS);
double ResiNorm = Residual.L2Norm();
ResidualNorm.Add(ResiNorm);
Console.WriteLine("Residual for " + u.Identification + " = " + ResiNorm);
}
/// tests BoSSScmdSilent
Assert.LessOrEqual(ResidualNorm[0], 1e-10);
Assert.GreaterOrEqual(ResidualNorm[1], 1e-1);
```
## The matrix of the Poisson Operator
If we do not know the exact solution, we have to solve a linear system.
Therefore, we not only need to evaluate the operator,
but we need its matrix.
The *Mapping* controls which degree-of-freedom of the DG approximation
is mapped to which row, resp. column of the matrix.
```
var Mapping = new UnsetteledCoordinateMapping(DGBasisOn1D);
var Matrix_SipLaplace = Operator_SipLaplace.ComputeMatrix(Mapping,null,Mapping);
Matrix_SipLaplace.NoOfCols
Matrix_SipLaplace.NoOfRows
```
We see that the matrix has 27 rows and columns.
### Matrix rank and determinant of the matrix
**Matrix\_SipLaplace**:
Use the functions *rank* and *det* to analyze the matrix (warning: this can get costly
for larger matrices!).
Interpret the results:
- What does it mean, when a matrix has full rank?
- How many solutions can a linear system have?
```
double rank = Matrix_SipLaplace.rank();
Console.WriteLine("Matrix rank = " + rank);
double det = Matrix_SipLaplace.det();
Console.WriteLine("Determinante = " + det);
```
So the matrix of the SIP discretization has a unique solution.
```
/// tests BoSSScmdSilent
Assert.AreEqual(rank, Matrix_SipLaplace.NoOfCols);
Assert.Greater(det, 1.0);
```
## Advanced topics
### The penalty parameter of the SIP and stability in 2D
We define a two-dimensional grid:
```
var grd2D = Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-1,1,21),
GenericBlas.Linspace(-1,1,16));
var DGBasisOn2D = new Basis(grd2D, 5);
var Mapping2D = new UnsetteledCoordinateMapping(DGBasisOn2D);
```
We are going to choose the **PenaltySafety** for the **SipLaplace**
from the following list
```
double[] SFs = new double[]
{0.001, 0.002, 0.01, 0.02, 0.1, 0.2, 1, 2, 10, 20, 100};
```
and compute the condition number as well as the determinate.
We consider the example
$$
-\Delta u = \pi^2 (a_x^2 + a_y^2)/4 \cos(a_x \pi x/2) \cos(a_y \pi y/2)
\text{ with }
(x,y) \in (-1,1)^2
$$
and $u = 0$ on the boundary.
The exact solution is $u_{Ex}(x,y) = \cos(a_x \pi x/2) \cos(a_x \pi y/2)$, where $a_x$ and $a_y$ must be odd numbers
to comply with homogeneous bounary condition.
```
double ax = 1.0; // must be an even number to comply with homogeneous Dirichlet boundary condition
double ay = 3.0; // must be an odd number to comply with homogeneous Dirichlet boundary condition
Func<double[], double> exSol =
(X => Math.Cos(X[0]*ax*Math.PI*0.5)*Math.Cos(X[1]*ay*Math.PI*0.5));
Func<double[], double> exRhs =
(X => ((ax.Pow2() + ay.Pow2())/4.0)*Math.PI.Pow2()
*Math.Cos( X[0]*ax*Math.PI*0.5 )*Math.Cos( X[1]*ay*Math.PI*0.5 )); // == - /\ exSol
SinglePhaseField RHS = new SinglePhaseField(DGBasisOn2D, "RHS");
RHS.ProjectField(exRhs);
double[] RHSvec = RHS.CoordinateVector.ToArray();
```
We check our discretization once more in 2D; the residual should be low,
but not exactly (resp. up to $10^{-12}$) since the solution is not
polynomial and cannot be fulfilled exactly.
```
SinglePhaseField u = new SinglePhaseField(DGBasisOn2D,"u");
u.ProjectField(exSol);
var Matrix_SIP_sf = Operator_SipLaplace.ComputeMatrix(Mapping2D,
null,
Mapping2D);
SinglePhaseField Residual = new SinglePhaseField(DGBasisOn2D,"Residual");
Residual.Acc(1.0, RHS);
Matrix_SIP_sf.SpMV(-1.0, u.CoordinateVector, 1.0, Residual.CoordinateVector);
Console.WriteLine("Residual L2 norm: " + Residual.L2Norm());
```
We also check that the matrix is symmetric:
```
var checkMatrix = Matrix_SIP_sf - Matrix_SIP_sf.Transpose();
checkMatrix.InfNorm()
/// tests BoSSScmdSilent
Assert.LessOrEqual(checkMatrix.InfNorm(), 1e-8);
```
### Matrix properties for different penalty factors
Now, we assemble the matrix of the SIP for different
**PenaltySafety**-factors. We also try to solve the linear system
using an iterative method.
As Matlab is called multiple times during this
command, it can take some minutes until it is done.
```
int cnt = 0;
var Results = new List<(double safetyFactor, double condNumber, int NoOfIterations, double L2errror, bool isDefinite)>();
foreach(double sf in SFs) {
cnt++;
i_SipLaplace.PenaltySafety = sf;
var Matrix_SIP_sf = Operator_SipLaplace.ComputeMatrix(
Mapping2D, null, Mapping2D);
double condNo1 = Matrix_SIP_sf.condest();
bool definite = Matrix_SIP_sf.IsDefinite();
/// We solve the system
///
/// Matrix\_SIP\_sf \cdot u = RHS
///
/// using a an iterative solver, the so-called
/// conjugate gradient (CG) method.
/// CG requires a positive definite matrix.
/// The function \code{Solve\_CG} returns the number of iterations.
SinglePhaseField u = new SinglePhaseField(DGBasisOn2D,"u");
u.InitRandom();
int NoOfIter = Matrix_SIP_sf.Solve_CG(u.CoordinateVector, RHSvec);
SinglePhaseField Error = new SinglePhaseField(DGBasisOn2D,"Error");
Error.ProjectField(exSol);
Error.Acc(-1.0, u);
double L2err = u.L2Error(exSol);
Console.WriteLine(sf + "\t" + condNo1.ToString("0.#E-00")
+ "\t" + NoOfIter
+ "\t" + L2err.ToString("0.#E-00")
+ "\t" + definite);
Results.Add((sf, condNo1, NoOfIter, L2err, definite));
}
/// tests BoSSScmdSilent
foreach(var r in Results) {
if(r.safetyFactor >= 1 && r.safetyFactor <= 20) {
Assert.LessOrEqual(r.condNumber, 1e7); // cond No.
Assert.LessOrEqual(r.NoOfIterations, 7000); // iter
Assert.LessOrEqual(r.L2errror, 1e-4); // L2 err
Assert.IsTrue(r.isDefinite); // definite
}
if(r.Item1 <= 0.1) {
Assert.IsFalse(r.isDefinite); // indefinite
}
}
```
### Plotting
Plot the number of conjugate gradient iterations versus the
**PenaltySafety**.
```
var xValues = Results.Select(r => r.safetyFactor).ToArray();
var yValues = Results.Select(r => ((double)(r.NoOfIterations))).ToArray();
var plt = new Plot2Ddata();
plt.AddDataGroup(xValues, yValues);
/// A logarithmic scale is used for the horizontal axis.
plt.LogX = true;
/// Set Format
plt.dataGroups[0].Format = new PlotFormat(lineColor: LineColors.Blue,
pointSize: 2,
dashType: DashTypes.DotDashed,
Style: Styles.LinesPoints,
pointType:PointTypes.OpenCircle);
// Show!
plt.PlotNow()
```
### Convergence study, indefinite vs. definite.
We are going to solve the SIP-system for different grid resolutions,
comparing an insufficient penalty to a penalty which is large enough.
```
double[] Resolution = new double[] { 2, 4, 8, 16, 32, 64 };
List<double> L2Error_indef = new List<double>();
List<double> L2Error_posdef = new List<double>();
int cnt = 0;
foreach(int Res in Resolution) {
cnt++;
//var grd2D = Grid2D.UnstructuredTriangleGrid(GenericBlas.Linspace(-1,1,(int)Res + 1),
// GenericBlas.Linspace(-1,1,(int)Res + 1));
var grd2D = Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-1,1,(int)Res + 1),
GenericBlas.Linspace(-1,1,(int)Res + 1));
var gdata2D = new GridData(grd2D);
var DGBasisOn2D = new Basis(gdata2D, 2);
var Mapping2D = new UnsetteledCoordinateMapping(DGBasisOn2D);
SinglePhaseField RHS = new SinglePhaseField(DGBasisOn2D, "RHS");
RHS.ProjectField(exRhs);
SinglePhaseField uEx = new SinglePhaseField(
new Basis(gdata2D, DGBasisOn2D.Degree*2),
"Error");
uEx.ProjectField(exSol);
i_SipLaplace.PenaltySafety = 0.01;
var Matrix_SIP_indef = Operator_SipLaplace.ComputeMatrix(
Mapping2D,null,Mapping2D);
SinglePhaseField u_indef = new SinglePhaseField(DGBasisOn2D,"u_indef");
Matrix_SIP_indef.Solve_Direct(u_indef.CoordinateVector,
RHS.CoordinateVector);
var Error_indef = uEx.CloneAs();
Error_indef.AccLaidBack(-1.0, u_indef);
L2Error_indef.Add(Error_indef.L2Norm());
/// In order to have a positive definite system, we are
/// using PenaltySafety = 2!
i_SipLaplace.PenaltySafety = 2.0;
var Matrix_SIP_posdef = Operator_SipLaplace.ComputeMatrix(
Mapping2D, null, Mapping2D);
SinglePhaseField u_posdef = new SinglePhaseField(DGBasisOn2D,"u_posdef");
Matrix_SIP_posdef.Solve_Direct(u_posdef.CoordinateVector,
RHS.CoordinateVector);
var Error_posdef = uEx.CloneAs();
Error_posdef.AccLaidBack(-1.0, u_posdef);
L2Error_posdef.Add(Error_posdef.L2Norm());
//Tecplot("ConvStudy-" + cnt, uEx, u_posdef, u_indef); // activate this line for plotting!
Console.WriteLine(L2Error_indef.Last().ToString("0.#E-00")
+ "\t" + L2Error_posdef.Last().ToString("0.#E-00"));
}
```
### Convergence Plot and Conclusions
The convergence plot should unveil that there is something wrong if the
penalty factor is set too low.
Unfortunately, **it does not**, so this is some kind of **anti-example**;
It is in this tutorial anyway **to illustrate the difficulties of numerical testing**.
Interested readers migth check out the source code and
try to modify the test `BoSSS.Application.SipPoisson.Tests.TestProgram.TestOperatorConvergence3D(2)`
so that it fails.
The reason why the indefinite matrix still gives a solution convergence
is very likely that the solver which is used in BoSSS is also (sometimes) capable
of solving singular or close-to-singular systems, i.e. systems without a unique solution.
In those cases, it selects a solution with a minimal solution norm.
Since BoSSS uses an orthonormal basis the $L^2$ norm of the DG-Field is identical to the $l_2$ norm of the
coordinate vector (Parseval's identity).
Therefore, the solver by chance adds additional stability which is not part of the (instable) discretization.
~~While the solution of the indefinite system may look right at the first
glance, we see that we do not obtain grid convergence for
*Error\_indef*.~~
The error of the positive definite system, *Error\_posdef*, where the
penalty is chosen sufficiently large converges with the expected
rate.
```
var plt = new Plot2Ddata();
plt.AddDataGroup("indef mtx", Resolution, L2Error_indef);
plt.AddDataGroup("pos def mtx", Resolution, L2Error_posdef);
/// A double-logarithmic scale is used:
plt.LogX = true;
plt.LogY = true;
/// Set Format
plt.dataGroups[0].Format = new PlotFormat(lineColor: LineColors.Red,
pointSize: 2,
dashType: DashTypes.DotDashed,
Style: Styles.LinesPoints,
pointType:PointTypes.OpenCircle);
plt.dataGroups[1].Format = new PlotFormat("Blue-.o"); // altenatively, using MATLAB-like format strings
plt.dataGroups[1].Format.PointSize = 2;
// Show!
plt.PlotNow()
```
Finally, we are going to compute the convergence rate of the SIP
discretization.
We compute the slope of the log-log plot:
```
double dk = Resolution.LogLogRegression(L2Error_posdef);
dk
/// tests BoSSScmdSilent
Assert.LessOrEqual(dk, -2.9);
```
### Visualization of minimal Eigenvectors
An alternative way of identifying problems with the discretization is the investigation
of minimal Eigenvalues (in absolute value) and the respective Eigenvectors/Eigensolutions.
This very often unveils stability issues on rather coarse meshes.
```
var grd2D = Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-1,1,11),
GenericBlas.Linspace(-1,1,11));
var DGBasisOn2D = new Basis(grd2D, 2);
var Mapping2D = new UnsetteledCoordinateMapping(DGBasisOn2D);
i_SipLaplace.PenaltySafety = 0.01;
var Matrix_SIP_indef = Operator_SipLaplace.ComputeMatrix(Mapping2D,null,Mapping2D);
i_SipLaplace.PenaltySafety = 4.0;
var Matrix_SIP_posdef = Operator_SipLaplace.ComputeMatrix(Mapping2D,null,Mapping2D);
```
For both matrixes (indefinite and positive definite) one can determine the respective Eigenvectors (for the minimal Eigenvalue).
Since Eigenvectors represent solution to the matrix for a RHS that is a multiple of the Eigenvector itself,
it makes sense to interpret the Eigenvecor as a DG field.
```
(var lmin_indef, var EvectMin_indef) = Matrix_SIP_indef.MinimalEigen();
DGField dg_EvectMin_indef = new SinglePhaseField(DGBasisOn2D, "MinimaEvect-indef");
dg_EvectMin_indef.CoordinateVector.SetV(EvectMin_indef);
lmin_indef
(var lmin_posdef, var EvectMin_posdef) = Matrix_SIP_posdef.MinimalEigen();
DGField dg_EvectMin_posdef = new SinglePhaseField(DGBasisOn2D, "MinimaEvect-posdef");
dg_EvectMin_posdef.CoordinateVector.SetV(EvectMin_posdef);
lmin_posdef
```
In many cases, the visualization of Eigenvalues unveils spurious solutions, resp. instabilities
which are hidden in the operator discretization.
Compare the Visualization of both Eigenvectors, e.g. in Tecplot or Visit:
```
Tecplot("Eigenvectors", dg_EvectMin_indef, dg_EvectMin_posdef);
```
## Further reading
- DiPietroErn2011
- Arnold_1982
| github_jupyter |
# Part 5 - Intro to Encrypted Programs
Believe it or not, it is possible to compute with encrypted data. In other words, it's possible to run a program where ALL of the variables in the program are encrypted!
In this tutorial, we're going to walk through very basic tools of encrypted computation. In particular, we're going to focus on one popular approach called Secure Multi-Party Computation. In this lesson, we'll learn how to build an encrypted calculator which can perform calculations on encrypted numbers.
Authors:
- Andrew Trask - Twitter: [@iamtrask](https://twitter.com/iamtrask)
References:
- Morten Dahl - [Blog](https://mortendahl.github.io) - Twitter: [@mortendahlcs](https://twitter.com/mortendahlcs)
# Step 1: Encryption Using Secure Multi-Party Computation
SMPC is at first glance a rather strange form of "encryption". Instead of using a public/private key to encrypt a variable, each value is split into multiple "shares", each of which operate like a private key. Typically, these "shares" will be distributed amongst 2 or more "owners". Thus, in order to decrypt the variable, all owners must agree to allow the decryption. In essence, everyone has a private key.
### Encrypt()
So, let's say we wanted to "encrypt" a varible "x", we could do so in the following way.
```
Q = 1234567891011
x = 25
import random
def encrypt(x):
share_a = random.randint(0,Q)
share_b = random.randint(0,Q)
share_c = (x - share_a - share_b) % Q
return (share_a, share_b, share_c)
encrypt(x)
```
As you can see here, we have split our variable "x" into 3 different shares, which could be sent to 3 different owners.
### Decrypt()
If we wanted to decrypt these 3 shares, we could simply sum them together and take the modulus of the result (mod Q).
```
def decrypt(*shares):
return sum(shares) % Q
a,b,c = encrypt(25)
decrypt(a, b, c)
```
Importantly, notice that if we try to decrypt with only two shares, the decryption does not work!
```
decrypt(a, b)
```
Thus, we need all of the owners to participate in order to decrypt the value. It is in this way that the "shares" act like private keys, all of which must be present in order to decrypt a value.
# Step 2: Basic Arithmetic Using SMPC
However, the truly extraordinary property of Secure Multi-Party Computation is the ability to perform computation **while the variables are still encrypted**. Let's demonstrate simple addition below.
```
x = encrypt(25)
y = encrypt(5)
def add(x, y):
z = list()
# the first worker adds their shares together
z.append((x[0] + y[0]) % Q)
# the second worker adds their shares together
z.append((x[1] + y[1]) % Q)
# the third worker adds their shares together
z.append((x[2] + y[2]) % Q)
return z
decrypt(*add(x,y))
```
### Success!!!
And there you have it! If each worker (separately) adds their shares together, then the resulting shares will decrypt to the correct value (25 + 5 == 30).
As it turns out, SMPC protocols exist which can allow this encrypted computation for the following operations:
- addition (which we've just seen)
- multiplication
- comparison
and using these basic underlying primitives, we can perform arbitrary computation!!!
In the next section, we're going to learn how to use the PySyft library to perform these operations!
# Step 3: SMPC Using PySyft
In the previous sections, we outlined some basic intuitions around SMPC is supposed to work. However, in practice we don't want to have to hand-write all of the primitive operations ourselves when writing our encrypted programs. So, in this section we're going to walk through the basics of how to do encrypted computation using PySyft. In particualr, we're going to focus on how to do the 3 primitives previously mentioned: addition, multiplication, and comparison.
First, we need to create a few Virtual Workers (which hopefully you're now familiar with given our previous tutorials).
```
import syft as sy
hook = sy.TorchHook()
bob = sy.VirtualWorker(id="bob")
alice = sy.VirtualWorker(id="alice")
bill = sy.VirtualWorker(id="bill")
```
### Basic Encryption/Decryption
Encryption is as simple as taking any PySyft tensor and calling .share(). Decryption is as simple as calling .get() on the shared variable
```
x = sy.LongTensor([25])
encrypted_x = x.share(bob, alice, bill)
encrypted_x.get()
```
### Introspecting the Encrypted Values
If we look closer at Bob, Alice, and Bill's workers, we can see the shares that get created!
```
bob._objects
x = sy.LongTensor([25]).share(bob, alice,bill)
bob._objects
# Bob's share
bobs_share = list(bob._objects.values())[0].parent[0]
bobs_share
# Alice's share
alices_share = list(alice._objects.values())[0].parent[0]
alices_share
# Bill's share
bills_share = list(bill._objects.values())[0].parent[0]
bills_share
```
And if we wanted to, we could decrypt these values using the SAME approach we talked about earlier!!!
```
Q = sy.spdz.spdz.field
(bobs_share + alices_share + bills_share) % Q
```
As you can see, when we called .share() it simply split the value into 3 shares and sent one share to each of the parties!
# Encrypted Arithmetic
And now you see that we can perform arithmetic on the underlying values! The API is constructed so that we can simply perform arithmetic like we would with regular PyTorch tensors.
Note: for comparison, it returns boolean outputs (True/False) in the form of Integers (1/0). 1 corresponds to True. 0 corresponds to False.
```
x = sy.LongTensor([25]).share(bob,alice)
y = sy.LongTensor([5]).share(bob,alice)
z = x + y
z.get()
z = x * y
z.get()
z = x > y
z.get()
z = x < y
z.get()
z = x == y
z.get()
z = x == y + 20
z.get()
```
# Congratulations!!! - Time to Join the Community!
Congraulations on completing this notebook tutorial! If you enjoyed this and would like to join the movement toward privacy preserving, decentralized ownership of AI and the AI supply chain (data), you can do so in the following ways!
### Star PySyft on Github
The easiest way to help our community is just by starring the Repos! This helps raise awareness of the cool tools we're building.
- [Star PySyft](https://github.com/OpenMined/PySyft)
### Join our Slack!
The best way to keep up to date on the latest advancements is to join our community! You can do so by filling out the form at [http://slack.openmined.org](http://slack.openmined.org)
### Join a Code Project!
The best way to contribute to our community is to become a code contributor! At any time you can go to PySyft Github Issues page and filter for "Projects". This will show you all the top level Tickets giving an overview of what projects you can join! If you don't want to join a project, but you would like to do a bit of coding, you can also look for more "one off" mini-projects by searching for github issues marked "good first issue".
- [PySyft Projects](https://github.com/OpenMined/PySyft/issues?q=is%3Aopen+is%3Aissue+label%3AProject)
- [Good First Issue Tickets](https://github.com/OpenMined/PySyft/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
### Donate
If you don't have time to contribute to our codebase, but would still like to lend support, you can also become a Backer on our Open Collective. All donations go toward our web hosting and other community expenses such as hackathons and meetups!
[OpenMined's Open Collective Page](https://opencollective.com/openmined)
| github_jupyter |
# <font color="Red"><h3 align="center">Table of Contents</h3></font>
1. Introduction and Installation
2. DataFrame Basics
3. Read Write Excel CSV File
4. Different Ways Of Creating DataFrame
5. Handle Missing Data: fillna, dropna, interpolate
6. Handle Missing Data: replace function
7. Concat Dataframes
8. Pivot table
9. Pandas Crosstab
# <font color="Blue"><h3 align="center">1.Introduction and Installation</h3></font>
```
from IPython.display import Image
Image(filename='pandas.png')
```
> [Pandas](https://pandas.pydata.org/pandas-docs/stable/) is the typical tool a data scientist grabs first. It is based around a lot of the [NumPy package](https://docs.scipy.org/doc/numpy/reference/) so a familiarity with NumPy will help understand how to use Pandas. However, Pandas has a lot of specific extras that can be very useful to a data scientist!
>
>Pandas is also a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series. It is free software released under the three-clause BSD license.
```
!pip install pandas
```
# <font color="Green"><h3 align="center">2.DataFrame Basics</h3></font>
> Dataframe is most commonly used object in pandas. It is a table like datastructure containing rows and columns similar to excel spreadsheet
```
import pandas as pd
weather_data = {
'day': ['1/1/2017','1/2/2017','1/3/2017','1/4/2017','1/5/2017','1/6/2017'],
'temperature': [32,35,28,24,32,31],
'windspeed': [6,7,2,7,4,2],
'event': ['Rain', 'Sunny', 'Snow','Snow','Rain', 'Sunny']
}
df = pd.DataFrame(weather_data)
df
df.shape # rows, columns shape
```
## <font color='blue'>Rows</font>
```
df.head()
df.tail()
df[1:3]
```
## <font color='blue'>Columns</font>
```
df.columns
df['day']
type(df['day'])
df[['day','temperature']]
```
## <font color='blue'>Operations On DataFrame</font>
```
df['temperature'].max()
df.temperature.max()
df[df['temperature']>32]
df['day'][df['temperature'] == df['temperature'].max()] # doing SQL in pandas
df[df['temperature'] == df['temperature'].max()] # doing SQL in pandas
df['temperature'].std()
df['event'].max() # But mean() won't work since data type is string
df.describe()
```
## <font color='blue'>set_index</font>
```
df.set_index('day')
df.set_index('day', inplace=True)
df
df.index
df.loc['1/6/2017']
df.reset_index(inplace=True)
df.head()
df.set_index('event',inplace=True) # this is kind of building a hash map using event as a key
df
df.loc['Snow']
df.reset_index(inplace=True)
df.head()
```
# <font color="TEAL"><h3 align="center">3.Read Write Excle CSV File</h3></font>
### <font color="blue">Write to CSV</color>
```
df.to_csv("new.csv", index=False)
```
### <font color="blue">Read CSV</color>
```
df = pd.read_csv("new.csv")
df
df = pd.read_csv("new.csv", header=None, names = ["ticker","eps","revenue","people"])
df
df = pd.read_csv("new.csv", nrows=5)
df
df.head(2)
```
### <font color="blue">Write to Excel</color>
```
df.to_excel("new.xlsx", sheet_name="weather", index=False, startrow=2)
df = pd.read_excel("new.xlsx",'weather')
df
df_stocks = pd.DataFrame({
'tickers': ['GOOGL', 'WMT', 'MSFT'],
'price': [845, 65, 64 ],
'pe': [30.37, 14.26, 30.97],
'eps': [27.82, 4.61, 2.12]
})
df_weather = pd.DataFrame({
'day': ['1/1/2017','1/2/2017','1/3/2017'],
'temperature': [32,35,28],
'event': ['Rain', 'Sunny', 'Snow']
})
with pd.ExcelWriter('stocks_weather.xlsx') as writer:
df_stocks.to_excel(writer, sheet_name="stocks")
df_weather.to_excel(writer, sheet_name="weather")
```
### <font color="blue">Read Excel</color>
```
df = pd.read_excel("new.xlsx","weather")
df
```
Excel data replace using **function**
```
def convert_people_cell(cell):
if cell=="n.a.":
return 'Sam Walton'
return cell
def convert_price_cell(cell):
if cell=="n.a.":
return 50
return cell
df = pd.read_excel("new.xlsx","weather", converters= {
'people': convert_people_cell,
'price': convert_price_cell
})
df
```
### <font color="blue">Write to JSON</color>
```
df.to_json('new.json')
```
### <font color="blue">Read JSON</color>
```
weather_df = pd.read_json('new.json')
weather_df.head()
```
# <font color="purple"><h3 align="center">4.Different Ways Of Creating Dataframe</h3></font>
## <font color="green">Using csv</h3></font>
```
df = pd.read_csv("weather_data.csv")
df
```
## <font color="green">Using excel</h3></font>
```
df=pd.read_excel("new.xlsx","weather")
df
```
## <font color="green">Using dictionary</h3></font>
```
import pandas as pd
weather_data = {
'day': ['1/1/2017','1/2/2017','1/3/2017'],
'temperature': [32,35,28],
'windspeed': [6,7,2],
'event': ['Rain', 'Sunny', 'Snow']
}
df = pd.DataFrame(weather_data)
df
```
## <font color="green">Using tuples list</h3></font>
```
weather_data = [
('1/1/2017',32,6,'Rain'),
('1/2/2017',35,7,'Sunny'),
('1/3/2017',28,2,'Snow')
]
df = pd.DataFrame(data=weather_data, columns=['day','temperature','windspeed','event'])
df
```
## <font color="green">Using list of dictionaries</h3></font>
```
weather_data = [
{'day': '1/1/2017', 'temperature': 32, 'windspeed': 6, 'event': 'Rain'},
{'day': '1/2/2017', 'temperature': 35, 'windspeed': 7, 'event': 'Sunny'},
{'day': '1/3/2017', 'temperature': 28, 'windspeed': 2, 'event': 'Snow'},
]
df = pd.DataFrame(data=weather_data, columns=['day','temperature','windspeed','event'])
df
```
## <font color="green">Using JSON</h3></font>
```
df.to_json('weather_data.json')
weather_df = pd.read_json('weather_data.json')
weather_df.head()
```
## <font color="maroon"><h4 align="center">5.Handling Missing Data - fillna, interpolate, dropna</font>
```
import pandas as pd
df = pd.read_csv("weather_data.csv",parse_dates=['day'])
type(df.day[0])
df
df.isnull().sum()
df.set_index('day',inplace=True)
df
```
## <font color="blue">fillna</font>
<font color="purple">**Fill all NaN with one specific value**</font>
```
new_df = df.fillna(0)
new_df
```
<font color="purple">**Fill na using column names and dict**</font>
```
new_df = df.fillna({
'temperature': 0,
'windspeed': 0,
'event': 'No Event'
})
new_df
```
<font color="purple">**Use method to determine how to fill na values**</font>
```
new_df = df.fillna(method="ffill")
new_df
new_df = df.fillna(method="bfill")
new_df
```
<font color="purple">**Use of axis**</font>
```
new_df = df.fillna(method="bfill", axis="columns") # axis is either "index" or "columns"
new_df
```
<font color="purple">**limit parameter**</font>
```
new_df = df.fillna(method="ffill",limit=1)
new_df
```
### <font color="blue">interpolate</font>
```
new_df = df.interpolate()
new_df
```
### <font color="blue">dropna</font>
```
new_df = df.dropna()
new_df
new_df = df.dropna(how='all')
new_df
```
### <font color="blue">Inserting Missing Dates</font>
```
dt = pd.date_range("01-01-2017","01-11-2017")
idx = pd.DatetimeIndex(dt)
df = df.reindex(idx)
df
```
## <font color="NAVY"><h4 align="center">6.Handling Missing Data - replace method</font>
**Replacing single value**
```
import numpy as np
new_df = df.replace(-99999, value = np.NaN)
new_df
```
**Replacing per column**
```
new_df = df.replace({
'temperature': -99999,
'windspeed': -99999,
'event': '0'
}, np.nan)
new_df
```
**Replacing by using mapping**
```
new_df = df.replace({
-99999: np.nan,
'no event': 'Sunny',
})
new_df
```
**Replacing list with another list**
```
df = pd.DataFrame({
'score': ['exceptional','average', 'good', 'poor', 'average', 'exceptional'],
'student': ['rob', 'maya', 'parthiv', 'tom', 'julian', 'erica']
})
df
df.replace(['poor', 'average', 'good', 'exceptional'], [1,2,3,4])
```
# <font color="purple"><h3 align="center">7.Pandas Concatenate</h3></font>
## <font color='blue'>Basic Concatenation</font>
```
import pandas as pd
india_weather = pd.DataFrame({
"city": ["mumbai","delhi","banglore"],
"temperature": [32,45,30],
"humidity": [80, 60, 78]
})
india_weather
us_weather = pd.DataFrame({
"city": ["new york","chicago","orlando"],
"temperature": [21,14,35],
"humidity": [68, 65, 75]
})
us_weather
df = pd.concat([india_weather, us_weather])
df
```
## <font color='blue'>Ignore Index</font>
```
df = pd.concat([india_weather, us_weather], ignore_index=True)
df
```
## <font color='blue'>Concatenation And Keys</font>
```
df = pd.concat([india_weather, us_weather], keys=["india", "us"])
df
df.loc["us"]
df.loc["india"]
```
## <font color='blue'>Concatenation Using Index</font>
```
temperature_df = pd.DataFrame({
"city": ["mumbai","delhi","banglore"],
"temperature": [32,45,30],
}, index=[0,1,2])
temperature_df
windspeed_df = pd.DataFrame({
"city": ["delhi","mumbai"],
"windspeed": [7,12],
}, index=[1,0])
windspeed_df
df = pd.concat([temperature_df,windspeed_df],axis=1)
df
```
## <font color='blue'>Concatenate dataframe with series</font>
```
s = pd.Series(["Humid","Dry","Rain"], name="event")
s
df = pd.concat([temperature_df,s],axis=1)
df
```
# <font color="OLIVE"><h3 align="center">8.Pandas Pivot table</h3></font>
<h1 style="color:blue">Pivot basics</h1>
```
import pandas as pd
import numpy as np
df = pd.read_csv("weather.csv")
df
df.pivot(index='city',columns='date')
df.pivot(index='city',columns='date',values="humidity")
df.pivot(index='date',columns='city',values='humidity')
df.pivot(index='humidity',columns='city')
```
<h1 style="color:blue">Pivot Table</h1>
```
df.pivot_table(index="city",columns="date")
```
<h2 style="color:brown">Grouper</h2>
```
df['date'] = pd.to_datetime(df['date'])
df.pivot_table(index=pd.Grouper(freq='M',key='date'),columns='city')
```
# <font color="PURPLE"><h3 align="center">9.Pandas Crosstab </h3></font>
```
import pandas as pd
df = pd.read_excel("survey.xls")
df
pd.crosstab(df.Nationality,df.Handedness)
pd.crosstab(df.Sex,df.Handedness)
```
<h2 style="color:purple">Margins</h2>
```
pd.crosstab(df.Sex,df.Handedness, margins=True)
```
<h2 style="color:purple">Multi Index Column and Rows</h2>
```
pd.crosstab(df.Sex, [df.Handedness,df.Nationality], margins=True)
```
### <font color="OLIVE"><h3 align="center">Read Write Database(Sql) using DataFrame</h3></font>
```
import pandas as pd
Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
'Price': [22000,25000,27000,35000]
}
df = pd.DataFrame(Cars, columns= ['Brand', 'Price'])
print (df)
import sqlite3
conn = sqlite3.connect('TestDB1.db')
c = conn.cursor()
c.execute('CREATE TABLE CARS (Brand text, Price number)')
conn.commit()
df.to_sql('CARS', conn, if_exists='replace', index = False)
database = 'TestDB1.db'
conn = sqlite3.connect(database)
tables = pd.read_sql("""SELECT *
FROM sqlite_master
WHERE type='table';""", conn)
print("Conection SuccessFull",conn)
df = pd.read_sql_query("SELECT * FROM CARS", conn)
df
```
| github_jupyter |
# Map Making
In this lesson we cover the mapmaking problem and current and available TOAST mapmaking facilities
* `OpMadam` -- interface to `libMadam`, a parallel Fortran library for destriping and mapping signal
* `OpMapmaker` -- nascent implementation of a native TOAST mapmaker with planned support for a host of systematics templates
```
# Are you using a special reservation for a workshop?
# If so, set it here:
nersc_reservation = "toast3"
# Load common tools for all lessons
import sys
sys.path.insert(0, "..")
from lesson_tools import (
check_nersc,
fake_focalplane
)
nersc_host, nersc_repo, nersc_resv = check_nersc(reservation=nersc_reservation)
# Capture C++ output in the jupyter cells
%reload_ext wurlitzer
```
## Mapmaking basics
(Apologies to the experts. You can freely skip the basics if this is trivial to you)
### Binning a map
CMB experiments measure the Stokes I (intensity), Q and U linear polarization components in discrete sky pixels. A detector pointed at sky pixels $p$ registers a linear combination of the three Stokes components:
$$
d_p = I_p + \eta \cdot (Q_p \cos 2\psi + U_p \sin 2\psi) + n,
$$
where $\eta$ is the polarization efficiency of the detector, $\psi$ is the polarization sensitive direction and $n$ is the noise. $\psi$ depends on the intrinsic polarization angle of the detector, $\psi_0$, and the relative orientation of the focalplane and the sky, $\psi'$. Furthermore, if the detector is observing the sky through a half-wave plate (HWP), then the HWP angle, $\omega$ must also be accounted for:
$$
\psi = \psi_0 + \alpha + 2\omega
$$
Regardless of how $\psi$ is modulated ($\psi_0$, $\alpha$ or $\omega$), one needs a bare minimum of 3 observations at different angles, $\psi$, to solve for $m=[I, Q, U]^T$. We encode the pointing weights ($1$, $\eta\cdot\cos 2\psi$, $\eta\cdot\sin 2\psi$) in a pointing matrix:
$$
P = \begin{bmatrix}
1 & \eta\cos 2\psi_1 & \eta\sin 2\psi_1 \\
1 & \eta\cos 2\psi_2 & \eta\sin 2\psi_2 \\
& ... & \\
1 & \eta\cos 2\psi_N & \eta\sin 2\psi_N \\
\end{bmatrix}
$$
A vector of samples drawn from $m$ is then
$$
d = P m
$$
and we can find a (generalized) least squares solution of $m$ as
$$
m = (P^T N^{-1} P)^{-1} P^T N^{-1} d,
$$
where we have accounted for non-trivial noise correlations in
$$
N = \langle n n^T \rangle.
$$
If each detector sample is subject to same, uncorrelated noise fluctuations, $N$ can be dropped. This recovers the regular least squares solution.
An important special case of $P$ results when the angles $\psi$ differ by 45 degrees and come in sets of 4:
```
import numpy as np
psi = np.radians(np.arange(4) * 45)
print("psi =", np.round(psi, 2))
P = np.vstack([np.ones_like(psi), np.cos(2*psi), np.sin(2*psi)]).T
print("P = \n", np.round(P, 3))
invcov = np.dot(P.T, P)
print("P^T P = \n", np.round(invcov, 3))
cov = np.linalg.inv(invcov)
print("(P^T P)^{-1} = \n", np.round(cov, 3))
```
The quantity $P^T P$ is proportional to the noise covariance between $IQU$. It being diagonal means that the statistical error between them is uncorrelated. The reciprocal condition number of the above matrix is 0.5 which is the theoretical maximum. Low condition number would indicate that the $IQU$ solution is degenerate.
The mapmaking formalism in this section can be generalised for multiple sky pixels. Each sky pixel corresponds to its own $I$, $Q$ and $U$ columns in $P$. If the noise matrix, $N$, is diagonal, the pixel covariance matrix, $P^T N^{-1} P$ is $3\times 3$ block diagonal with each pixel being solved independently.
### Destriping
[arXiv:0907.0367](https://arxiv.org/abs/0907.0367)
In its simplest form, the time-ordered data (TOD) can be described as sky signal and a noise term:
$$
d = Pm + n.
$$
An optimal solution of $m$ requires the sample-sample covariance of $n$. For that to exist, the noise term needs to be stationary, which is often not the case in presence of systematics. We may decompose $n$ into a set of systematics templates and the actual, stationary noise term:
$$
d = Pm + Fa + n.
$$
Maximum likelihood solution of the template amplitudes, $a$, follows from the *destriping equation*:
$$
(F^T N^{-1} Z F + C_a^{-1})a = F^T N^{-1} Z d,
$$
where
$$
Z = \mathbf 1 - P(P^T N^{-1} P)^{-1} P^T N^{-1}
$$
is a projection matrix that removes the sky-synchronous part of the signal and
$$
C_a = \langle a a^T \rangle
$$
TOAST provides an interface to a destriping library, [libMadam](https://github.com/hpc4cmb/libmadam), which solves a version of the destriping equation where the templates in $F$ are disjoint steps of a step function. `libMadam` approximates that the covariance between the steps is stationary and can be calculated from the detector noise power spectral densities (PSDs). The remaining noise term, $n$ is approximated as white noise with a diagonal noise covariance, $N$. Users can just have `libMadam` write out the destriped maps or continue processing the destriped TOD:
$$
d' = d - Fa
$$
The TOAST native mapmaker under development is designed to be more general. Columns of the template matrix, $F$ can be populated with arbitrary forms, with or without an associated noise prior term, $C_a$. The templates are MPI-aware so a template may span data across process boundaries (think orbital dipole or far sidelobes).
## Example
In this section we create a TOAST data object with simulated signal and noise and process the data into hit maps, pixels noise matrices and signal maps.
```
import toast
import toast.todmap
from toast.mpi import MPI
import numpy as np
import matplotlib.pyplot as plt
mpiworld, procs, rank = toast.mpi.get_world()
comm = toast.mpi.Comm(mpiworld)
# A pipeline would create the args object with argparse
class args:
sample_rate = 10 # Hz
hwp_rpm = None
hwp_step_deg = None
hwp_step_time_s = None
spin_period_min = 1 # 10
spin_angle_deg = 20 # 30
prec_period_min = 100 # 50
prec_angle_deg = 30 # 65
coord = "E"
nside = 64
nnz = 3
outdir = "maps"
# Create a fake focalplane, we could also load one from file.
# The Focalplane class interprets the focalplane dictionary
# created by fake_focalplane() but it can also load the information
# from file.
focalplane = fake_focalplane(samplerate=args.sample_rate, fknee=0.1, alpha=2)
detectors = sorted(focalplane.keys())
detquats = {}
for d in detectors:
detquats[d] = focalplane[d]["quat"]
nsample = 100000
start_sample = 0
start_time = 0
iobs = 0
tod = toast.todmap.TODSatellite(
comm.comm_group,
detquats,
nsample,
coord=args.coord,
firstsamp=start_sample,
firsttime=start_time,
rate=args.sample_rate,
spinperiod=args.spin_period_min,
spinangle=args.spin_angle_deg,
precperiod=args.prec_period_min,
precangle=args.prec_angle_deg,
detranks=comm.group_size,
hwprpm=args.hwp_rpm,
hwpstep=args.hwp_step_deg,
hwpsteptime=args.hwp_step_time_s,
)
# Constantly slewing precession axis
precquat = np.empty(4 * tod.local_samples[1], dtype=np.float64).reshape((-1, 4))
toast.todmap.slew_precession_axis(
precquat,
firstsamp=start_sample + tod.local_samples[0],
samplerate=args.sample_rate,
degday=360.0 / 365.25,
)
tod.set_prec_axis(qprec=precquat)
noise = toast.pipeline_tools.get_analytic_noise(args, comm, focalplane)
obs = {}
obs["name"] = "science_{:05d}".format(iobs)
obs["tod"] = tod
obs["intervals"] = None
obs["baselines"] = None
obs["noise"] = noise
obs["id"] = iobs
data = toast.Data(comm)
data.obs.append(obs)
```
Create a synthetic Gaussian map to scan as input signal
```
import healpy as hp
lmax = args.nside * 2
cls = np.zeros([4, lmax + 1])
cls[0] = 1e0
sim_map = hp.synfast(cls, args.nside, lmax=lmax, fwhm=np.radians(15), new=True)
hp.mollview(sim_map[0], cmap="coolwarm", title="Input signal")
hp.write_map("sim_map.fits", hp.reorder(sim_map, r2n=True), nest=True, overwrite=True)
```
Now simulate sky signal and noise
```
name = "signal"
toast.tod.OpCacheClear(name).exec(data)
toast.todmap.OpPointingHpix(nside=args.nside, nest=True, mode="IQU").exec(data)
npix = 12 * args.nside ** 2
hitmap = np.zeros(npix)
tod = data.obs[0]["tod"]
for det in tod.local_dets:
pixels = tod.cache.reference("pixels_{}".format(det))
hitmap[pixels] = 1
hitmap[hitmap == 0] = hp.UNSEEN
hp.mollview(hitmap, nest=True, title="all hit pixels", cbar=False)
hp.graticule(22.5, verbose=False)
# Scan the signal from a map
localpix, localsm, subnpix = toast.todmap.get_submaps_nested(data, args.nside, subnside=1)
distmap = toast.map.DistPixels(
comm=mpiworld,
size=12 * args.nside **2,
nnz=3,
dtype=np.float32,
submap=subnpix,
local=localsm,
)
distmap.read_healpix_fits("sim_map.fits")
toast.todmap.OpSimScan(distmap=distmap, out=name).exec(data)
# Copy the sky signal
toast.tod.OpCacheCopy(input=name, output="sky_signal", force=True).exec(data)
# Simulate noise
toast.tod.OpSimNoise(out=name, realization=0).exec(data)
toast.tod.OpCacheCopy(input=name, output="full_signal", force=True).exec(data)
```
Destripe the signal and make a map. We use the nascent TOAST mapmaker because it can be run in serial mode without MPI. The TOAST mapmaker is still significantly slower so production runs should used `libMadam`.
```
mapmaker = toast.todmap.OpMapMaker(
nside=args.nside,
nnz=3,
name=name,
outdir=args.outdir,
outprefix="toast_test_",
baseline_length=10,
# maskfile=self.maskfile_binary,
# weightmapfile=self.maskfile_smooth,
# subharmonic_order=None,
iter_max=100,
use_noise_prior=False,
# precond_width=30,
)
mapmaker.exec(data)
```
Plot a segment of the timelines
```
tod = data.obs[0]["tod"]
times = tod.local_times()
fig = plt.figure(figsize=[12, 8])
for idet, det in enumerate(tod.local_dets):
sky = tod.local_signal(det, "sky_signal")
full = tod.local_signal(det, "full_signal")
cleaned = tod.local_signal(det, name)
ind = slice(0, 1000)
ax = fig.add_subplot(4, 4, 1 + idet)
ax.set_title(det)
ax.plot(times[ind], sky[ind], '.', label="sky", zorder=100)
ax.plot(times[ind], full[ind] - sky[ind], '.', label="noise")
ax.plot(times[ind], full[ind] - cleaned[ind], '.', label="baselines")
ax.legend(bbox_to_anchor=(1.1, 1.00))
fig.subplots_adjust(hspace=0.6)
fig = plt.figure(figsize=[12, 8])
for idet, det in enumerate(tod.local_dets):
sky = tod.local_signal(det, "sky_signal")
full = tod.local_signal(det, "full_signal")
cleaned = tod.local_signal(det, name)
ax = fig.add_subplot(4, 4, 1 + idet)
ax.set_title(det)
#plt.plot(times[ind], sky[ind], '-', label="signal", zorder=100)
plt.plot(times, full - sky, '.', label="noise")
plt.plot(times, full - cleaned, '-', label="baselines")
ax.legend(bbox_to_anchor=(1.1, 1.00))
fig.subplots_adjust(hspace=.6)
plt.figure(figsize=[12, 8])
hitmap = hp.read_map("maps/toast_test_hits.fits")
hitmap[hitmap == 0] = hp.UNSEEN
hp.mollview(hitmap, sub=[2, 2, 1], title="hits")
binmap = hp.read_map("maps/toast_test_binned.fits")
binmap[binmap == 0] = hp.UNSEEN
hp.mollview(binmap, sub=[2, 2, 2], title="binned map", cmap="coolwarm")
destriped = hp.read_map("maps/toast_test_destriped.fits")
destriped[destriped == 0] = hp.UNSEEN
hp.mollview(destriped, sub=[2, 2, 3], title="destriped map", cmap="coolwarm")
inmap = hp.read_map("sim_map.fits")
inmap[hitmap == hp.UNSEEN] = hp.UNSEEN
hp.mollview(inmap, sub=[2, 2, 4], title="input map", cmap="coolwarm")
print(np.sum(hitmap[hitmap != hp.UNSEEN]) / 1400000.0)
# Plot the white noise covariance
plt.figure(figsize=[12, 8])
wcov = hp.read_map("maps/toast_test_npp.fits", None)
wcov[:, wcov[0] == 0] = hp.UNSEEN
hp.mollview(wcov[0], sub=[3, 3, 1], title="II", cmap="coolwarm")
hp.mollview(wcov[1], sub=[3, 3, 2], title="IQ", cmap="coolwarm")
hp.mollview(wcov[2], sub=[3, 3, 3], title="IU", cmap="coolwarm")
hp.mollview(wcov[3], sub=[3, 3, 5], title="QQ", cmap="coolwarm")
hp.mollview(wcov[4], sub=[3, 3, 6], title="QU", cmap="coolwarm")
hp.mollview(wcov[5], sub=[3, 3, 9], title="UU", cmap="coolwarm")
```
## Filter & bin
A filter-and-bin mapmaker is easily created by combining TOAST filter operators and running the mapmaker without destriping:
```
name_in = "full_signal"
name_out = "full_signal_copy"
toast.tod.OpCacheCopy(input=name_in, output=name_out, force=True).exec(data)
toast.tod.OpPolyFilter(order=30, name=name_out).exec(data)
mapmaker = toast.todmap.OpMapMaker(
nside=args.nside,
nnz=3,
name=name_out,
outdir=args.outdir,
outprefix="toast_test_filtered_",
baseline_length=None,
# maskfile=self.maskfile_binary,
# weightmapfile=self.maskfile_smooth,
# subharmonic_order=None,
iter_max=100,
use_noise_prior=False,
# precond_width=30,
)
mapmaker.exec(data)
plt.figure(figsize=[15, 8])
binmap = hp.read_map("maps/toast_test_binned.fits")
filtered_map = hp.read_map("maps/toast_test_filtered_binned.fits")
binmap[binmap == 0] = hp.UNSEEN
hp.mollview(binmap, sub=[1, 3, 1], title="binned map", cmap="coolwarm")
filtered_map[filtered_map == 0] = hp.UNSEEN
hp.mollview(filtered_map, sub=[1, 3, 2], title="filtered map", cmap="coolwarm")
inmap = hp.read_map("sim_map.fits")
inmap[binmap == hp.UNSEEN] = hp.UNSEEN
hp.mollview(inmap, sub=[1, 3, 3], title="input map", cmap="coolwarm")
```
| github_jupyter |
# In this notebook we show the basic experiment with our end-to-end Sinkhorn Autoencoder with Noise Generation, using standard MNIST dataset
```
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
from torchvision.utils import save_image
from torchvision.datasets import MNIST
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
import matplotlib.pyplot as plt
import time
import torchvision
import numpy as np
from geomloss import SamplesLoss
import pickle
import pandas as pd
torch.cuda.set_device(1)
device = torch.device("cuda")
# device = torch.device("cpu")
batch_size = 1000
n_epochs = 20
input_size = 64
# MNIST Dataset
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.5], std=[0.5])])
train_dataset = datasets.MNIST(root='./mnist_data/', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./mnist_data/', train=False, transform=transform, download=True)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, drop_last=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True, drop_last=True)
n_classes = len(train_dataset.classes)
```
### We define the archtitecture of our model as follows:
```
class Autoencoder(nn.Module):
def __init__(self, g_input_dim, cond_dim):
super(Autoencoder, self).__init__()
self.d = 64
self.conv1 = nn.Conv2d(in_channels=1, out_channels=self.d, kernel_size=4, stride=2, padding=1, bias=False)
self.bn_1 = nn.BatchNorm2d(self.d)
self.conv2 = nn.Conv2d(self.d, self.d, kernel_size=4, stride=2, padding=1, bias=False)
self.bn_2 = nn.BatchNorm2d(self.d)
self.conv3 = nn.Conv2d(self.d, self.d, kernel_size=4, stride=2, padding=1, bias=False)
self.bn_3 = nn.BatchNorm2d(self.d)
self.fc3 = nn.Linear(self.d*9, self.d//4)
self.fc1 = nn.Linear(self.d//4, self.d*4)
self.dc1 = nn.ConvTranspose2d( self.d, self.d * 4, 4, 2, 0, bias=False)
self.dc1_bn = nn.BatchNorm2d(self.d*4)
self.dc2 = nn.ConvTranspose2d( self.d * 4, self.d * 2, 4, 2, 1, bias=False)
self.dc2_bn = nn.BatchNorm2d(self.d*2)
self.dc3 = nn.ConvTranspose2d( self.d * 2, self.d , 4, 1, 1, bias=False)
self.dc3_bn = nn.BatchNorm2d(self.d)
self.dc4 = nn.ConvTranspose2d( self.d , 1, 4, 2, 0, bias=False)
############ noise_gen
self.ng_fc1 = nn.Linear(g_input_dim, self.d*2)
self.ng_input_2 = nn.Linear(cond_dim,self.d)
self.ng_fc2 = nn.Linear(self.d*3, self.d*4)
self.ng_fc3 = nn.Linear(self.d*4, self.d*3)
self.ng_fc4 = nn.Linear(self.d*3, self.d//4)
###############
for m in self.modules():
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif (classname.find('BatchNorm') != -1):#|(classname.find('Linear') != -1):
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
# forward method
def forward(self, x):
x = self.conv1(x)
x = F.leaky_relu(self.bn_1(x))
x = self.conv2(x)
x = F.leaky_relu(self.bn_2(x))
x = self.conv3(x)
x = F.leaky_relu(self.bn_3(x))
x = x.view([-1,self.d*9])
y = self.fc3(x)
x = F.leaky_relu(self.fc1(y))
x = x.view(-1,self.d,2,2)
x = self.dc1(x)
x = F.leaky_relu(self.dc1_bn(x))
x = self.dc2(x)
x = F.leaky_relu(self.dc2_bn(x))
x = self.dc3(x)
x = F.leaky_relu(self.dc3_bn(x))
return torch.tanh(self.dc4(x)), y
def generate(self,x):
x = F.leaky_relu(self.fc1(x))
x = x.view(-1,self.d,2,2)
x = self.dc1(x)
x = F.leaky_relu(self.dc1_bn(x))
x = self.dc2(x)
x =F.leaky_relu(self.dc2_bn(x))
x = self.dc3(x)
x = F.leaky_relu(self.dc3_bn(x))
return torch.tanh(self.dc4(x))
def generate_noise(self, x, cond_x):
x = F.leaky_relu(self.ng_fc1(x), 0.2)
x2 = F.leaky_relu(self.ng_input_2(cond_x), 0.2)
x_concat = torch.cat((x,x2),1)
x = F.leaky_relu(self.ng_fc2(x_concat), 0.2)
x = F.leaky_relu(self.ng_fc3(x), 0.2)
x = self.ng_fc4(x)
return x
autoencoder = Autoencoder(input_size,n_classes).to(device)
autoencoder
```
### We use a standard MSE as a reconstruction loss
```
criterion_mse = nn.MSELoss()
```
### For the sinkhorn loss we use its implementation from the SamplesLoss package
```
loss_func = SamplesLoss("sinkhorn", blur=0.05,scaling = 0.95,diameter=0.01,debias=True)
```
### We use Adam as an opitmizer
```
lr = 0.0001
a_optimizer = optim.Adam(autoencoder.parameters(), lr = lr)
scheduler = optim.lr_scheduler.ExponentialLR(a_optimizer, gamma = 0.95)
```
### In this simple example we trian the model for 50 epochs
### Because of the big differences in losses we scale them by the factors specified below
```
n_epoch = 50
a_weigth = 1000
ng_weigth = 1
autoencoder.train()
for epoch in range(1, n_epoch+1):
ng_losses = []
a_losses = []
mse_losses = []
l2_loss = []
for batch_idx, (x, cond_x) in enumerate(train_loader):
x = x.to(device)
y_onehot = torch.FloatTensor(batch_size, 10)
y_onehot.zero_()
cond_x = y_onehot.scatter_(1, cond_x.reshape([-1,1]), 1).to(device)
autoencoder.zero_grad()
autoencoder_output, y = autoencoder(x)
### STANDARD AUTOENCODER MSE loss
a_loss_mse = criterion_mse(autoencoder_output, x)
rand_x = torch.rand(batch_size, input_size).to(device) ### Generate input noise for the noise generator
rand_y = autoencoder.generate_noise(rand_x,cond_x) ### Generate noise from random vector and conditional params
ng_loss = loss_func(torch.cat([y,cond_x],1), torch.cat([rand_y,cond_x],1)) ### noise generator losss,
#conditional params added to compute also loss for generating noise close to this from other conditionals
s_loss = ng_weigth*ng_loss+ a_weigth*a_loss_mse
s_loss.backward()
a_optimizer.step()
a_losses.append(a_loss_mse)
ng_losses.append(ng_loss)
print('[%d/%d]: loss_ng: %.4f, loss_a: %.4f' % (
(epoch), n_epoch, torch.mean(torch.FloatTensor(ng_losses)), torch.mean(torch.FloatTensor(a_losses))))#, torch.mean(torch.FloatTensor(mse_losses)), torch.mean(torch.FloatTensor(l2_loss))))
scheduler.step()
# print("lr:",scheduler.get_lr())
```
### We plot the original images from the test dataset accompanied by their reconstructions with our autoencoder and random generations from the same class
```
autoencoder.eval()
x, cond_x = next(iter(test_loader))
img_shape = [44,44]
plt.figure(figsize=(15,6))
for i in range(5):
plt.subplot(2,5,i+1)
example = x[i:i+1]
example = example.cpu().detach().numpy()
example = example.squeeze()
# example[example==0]=-0.1*example.max()
plt.imshow(example)
plt.title("Original\n")
# print()
plt.show()
plt.figure(figsize=(15,6))
for i in range(5):
plt.subplot(2,5,i+1)
example,_ = autoencoder.forward(x[i:i+1].to(device))
example = example.cpu().detach().numpy()
example = example.squeeze()
# example[example==0]=-0.1*example.max()
plt.imshow(example)
plt.title("Decoded\n")
plt.show()
plt.figure(figsize=(15,6))
for i in range(5):
plt.subplot(2,5,i+1)
y_onehot = torch.FloatTensor(batch_size, 10)
y_onehot.zero_()
cond_s = y_onehot.scatter_(1, cond_x.reshape([-1,1]), 1)
# generated_noise = ng.forward(torch.rand(1, input_size).to(device),cond_s[i:i+1].to(device))
generated_noise = autoencoder.generate_noise(torch.rand(1, input_size).to(device),cond_s[i:i+1].to(device))
example = autoencoder.generate(generated_noise)
example = example.cpu().detach().numpy()
example = example.squeeze()
# example[example==0]=-0.1*example.max()
plt.imshow(example)
plt.title("Generated\n")
plt.show()
```
| github_jupyter |
## Facies classification using KNN
##### Zhili Wei revised 2019 summer
```
import pandas as pd
import numpy as np
from math import radians, cos, sin, asin, sqrt
import itertools
from sklearn import neighbors
from sklearn import preprocessing
from sklearn import ensemble
from sklearn.model_selection import LeaveOneGroupOut, LeavePGroupsOut
import inversion
import pickle
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
```
#### Load training data
```
df=pickle.load(open('/Users/zhiliwei/onedrive/科研总览/new_dissertation/my dessertation/1.intro/train_set_df.pickled','rb'))
df.describe()
```
#### Build features
In the real world it would be unusual to have neutron-density cross-plot porosity (i.e. PHIND) without the corresponding raw input curves, namely bulk density and neutron porosity, as we have in this contest dataset. So as part of the feature engineering process, I back-calculate estimates of those raw curves from the provided DeltaPHI and PHIND curves. One issue with this approach though is that cross-plot porosity differs between vendors, toolstrings, and software packages, and it is not known exactly how the PHIND in this dataset was computed. So I make the assumption here that PHIND ≈ sum of squares porosity, which is usually an adequate approximation of neutron-density crossplot porosity. That equation looks like this:
$$PHIND = \sqrt{\frac{NPHI^2 + DPHI^2}{2}}$$
and it is assumed here that DeltaPHI is:
$$DeltaPHI = NPHI - DPHI$$
The functions below use the relationships from the above equations (...two equations, two unknowns...) to estimate NPHI and DPHI (and consequently RHOB).
Once we have RHOB, we can use it combined with PE to estimate apparent grain density (RHOMAA) and apparent photoelectric capture cross-section (UMAA), which are useful in lithology estimations from well logs.
```
def estimate_dphi(df):
return ((4*(df['PHIND']**2) - (df['DeltaPHI']**2))**0.5 - df['DeltaPHI']) / 2
def estimate_rhob(df):
return (2.71 - (df['DPHI_EST']/100) * 1.71)
def estimate_nphi(df):
return df['DPHI_EST'] + df['DeltaPHI']
def compute_rhomaa(df):
return (df['RHOB_EST'] - (df['PHIND'] / 100)) / (1 - df['PHIND'] / 100)
def compute_umaa(df):
return ((df['PE'] * df['RHOB_EST']) - (df['PHIND']/100 * 0.398)) / (1 - df['PHIND'] / 100)
```
Because solving the sum of squares equation involved the quadratic formula, in some cases imaginary numbers result due to porosities being negative, which is what the warning below is about.
```
df['DPHI_EST'] = df.apply(lambda x: estimate_dphi(x), axis=1).astype(float)
df['RHOB_EST'] = df.apply(lambda x: estimate_rhob(x), axis=1)
df['NPHI_EST'] = df.apply(lambda x: estimate_nphi(x), axis=1)
df['RHOMAA_EST'] = df.apply(lambda x: compute_rhomaa(x), axis=1)
```
#### Regress missing PE values
```
pe = df.dropna()
PE = pe['PE'].values
wells = pe['Well Name'].values
drop_list_pe = ['Formation', 'Well Name', 'Facies', 'Depth', 'PE', 'RELPOS']
fv_pe = pe.drop(drop_list_pe, axis=1).values
X_pe = preprocessing.StandardScaler().fit(fv_pe).transform(fv_pe)
y_pe = PE
reg = neighbors.KNeighborsRegressor(n_neighbors=40, weights='distance')
logo = LeaveOneGroupOut()
f1knn_pe = []
for train, test in logo.split(X_pe, y_pe, groups=wells):
well_name = wells[test[0]]
reg.fit(X_pe[train], y_pe[train])
score = reg.fit(X_pe[train], y_pe[train]).score(X_pe[test], y_pe[test])
print("{:>20s} {:.3f}".format(well_name, score))
f1knn_pe.append(score)
print("-Average leave-one-well-out F1 Score: %6f" % (np.mean(f1knn_pe)))
```
#### Apply regression model to missing PE values and merge back into dataframe:
```
reg.fit(X_pe, y_pe)
fv_apply = df.drop(drop_list_pe, axis=1).values
X_apply = preprocessing.StandardScaler().fit(fv_apply).transform(fv_apply)
df['PE_EST'] = reg.predict(X_apply)
df.PE = df.PE.combine_first(df.PE_EST)
```
#### Compute UMAA for lithology model
```
df['UMAA_EST'] = df.apply(lambda x: compute_umaa(x), axis=1)
```
#### Umaa Rhomaa plot
Just for fun, below is a basic Umaa-Rhomaa plot to view relative abundances of quartz, calcite, dolomite, and clay. The red triangle represents a ternary solution for QTZ, CAL, and DOL, while the green triangle represents a solution for QTZ, CAL, and CLAY (illite).
```
df[df.GR < 125].plot(kind='scatter', x='UMAA_EST', y='RHOMAA_EST', c='GR', figsize=(8,6))
plt.ylim(3.1, 2.2)
plt.xlim(0.0, 17.0)
plt.plot([4.8, 9.0, 13.8, 4.8], [2.65, 2.87, 2.71, 2.65], c='r')
plt.plot([4.8, 11.9, 13.8, 4.8], [2.65, 3.06, 2.71, 2.65], c='g')
plt.scatter([4.8], [2.65], s=50, c='r')
plt.scatter([9.0], [2.87], s=50, c='r')
plt.scatter([13.8], [2.71], s=50, c='r')
plt.scatter([11.9], [3.06], s=50, c='g')
plt.text(2.8, 2.65, 'Quartz', backgroundcolor='w')
plt.text(14.4, 2.71, 'Calcite', backgroundcolor='w')
plt.text(9.6, 2.87, 'Dolomite', backgroundcolor='w')
plt.text(12.5, 3.06, 'Illite', backgroundcolor='w')
plt.text(7.0, 2.55, "gas effect", ha="center", va="center", rotation=-55,
size=8, bbox=dict(boxstyle="larrow,pad=0.3", fc="pink", ec="red", lw=2))
plt.text(15.0, 2.78, "barite?", ha="center", va="center", rotation=0,
size=8, bbox=dict(boxstyle="rarrow,pad=0.3", fc="yellow", ec="orange", lw=2))
```
Here I use matrix inversion to "solve" the ternary plot for each lithologic component. Essentially each datapoint is a mix of the three components defined by the ternary diagram, with abundances of each defined by the relative distances from each endpoint. I use a GR cutoff of 40 API to determine when to use either the QTZ-CAL-DOL or QTZ-CAL-CLAY ternary solutions. In other words, it is assumed that below 40 API, there is 0% clay, and above 40 API there is 0% dolomite, and also that these four lithologic components are the only components in these rocks. Admittedly it's not a great assumption, especially since the ternary plot indicates other stuff is going on. For example the high Umaa datapoints near the Calcite endpoint may indicate some heavy minerals (e.g., pyrite) or even barite-weighted mud. The "pull" of datapoints to the northwest quadrant probably reflects some gas effect, so my lithologies in those gassy zones will be skewed.
```
# QTZ-CAL-CLAY
ur1 = inversion.UmaaRhomaa()
ur1.set_dol_uma(11.9)
ur1.set_dol_rhoma(3.06)
# QTZ-CAL-DOL
ur2 = inversion.UmaaRhomaa()
df['UR_QTZ'] = np.nan
df['UR_CLY'] = np.nan
df['UR_CAL'] = np.nan
df['UR_DOL'] = np.nan
df.loc[df.GR >= 40, 'UR_QTZ'] = df.loc[df.GR >= 40].apply(lambda x: ur1.get_qtz(x.UMAA_EST, x.RHOMAA_EST), axis=1)
df.loc[df.GR >= 40, 'UR_CLY'] = df.loc[df.GR >= 40].apply(lambda x: ur1.get_dol(x.UMAA_EST, x.RHOMAA_EST), axis=1)
df.loc[df.GR >= 40, 'UR_CAL'] = df.loc[df.GR >= 40].apply(lambda x: ur1.get_cal(x.UMAA_EST, x.RHOMAA_EST), axis=1)
df.loc[df.GR >= 40, 'UR_DOL'] = 0
df.loc[df.GR < 40, 'UR_QTZ'] = df.loc[df.GR < 40].apply(lambda x: ur2.get_qtz(x.UMAA_EST, x.RHOMAA_EST), axis=1)
df.loc[df.GR < 40, 'UR_DOL'] = df.loc[df.GR < 40].apply(lambda x: ur2.get_dol(x.UMAA_EST, x.RHOMAA_EST), axis=1)
df.loc[df.GR < 40, 'UR_CAL'] = df.loc[df.GR < 40].apply(lambda x: ur2.get_cal(x.UMAA_EST, x.RHOMAA_EST), axis=1)
df.loc[df.GR < 40, 'UR_CLY'] = 0
```
#### Plot facies by formation to see if the Formation feature will be useful
```
facies_colors = ['#F4D03F', '#F5B041','#DC7633','#6E2C00', '#1B4F72','#2E86C1', '#AED6F1', '#A569BD', '#196F3D']
fms = df.Formation.unique()
fig, ax = plt.subplots(int(len(fms) / 2), 2, sharey=True, sharex=True, figsize=(5,10))
for i, fm in enumerate(fms):
facies_counts = df[df.Formation == fm]['Facies'].value_counts().sort_index()
colors = [facies_colors[i-1] for i in facies_counts.index]
ax[int(i/2), i%2].bar(facies_counts.index, height=facies_counts, color=colors)
ax[int(i/2), i%2].set_title(fm, size=8)
```
#### Group formations by similar facies distributions
```
fm_groups = [['A1 SH', 'B1 SH', 'B2 SH', 'B3 SH', 'B4 SH'],
['B5 SH', 'C SH'],
['A1 LM', 'C LM'],
['B1 LM', 'B3 LM', 'B4 LM'],
['B2 LM', 'B5 LM']]
fm_group_dict = {fm:i for i, l in enumerate(fm_groups) for fm in l}
df['FM_GRP'] = df.Formation.map(fm_group_dict)
```
#### Make dummy variables from the categorical Formation feature
```
df = pd.get_dummies(df, prefix='FM_GRP', columns=['FM_GRP'])
```
#### Compute Archie water saturation
```
def archie(df):
return np.sqrt(0.08 / ((df.PHIND ** 2) * (10 ** df.ILD_log10)))
df['SW'] = df.apply(lambda x: archie(x), axis=1)
```
#### Get distances between wells
```
# modified from jesper
latlong = pd.DataFrame({"SHRIMPLIN": [37.978076, -100.987305], #
"ALEXANDER D": [37.6747257, -101.1675259], #
"SHANKLE": [38.0633799, -101.3920543], #
"LUKE G U": [37.4499614, -101.6121913], #
"KIMZEY A": [37.12289, -101.39697], #
"CROSS H CATTLE": [37.9105826, -101.6464517], #
"NOLAN": [37.7866294, -101.0451641], #?
"NEWBY": [37.3172442, -101.3546995], #
"CHURCHMAN BIBLE": [37.3497658, -101.1060761], #?
"STUART": [37.4857262, -101.1391063], #
"CRAWFORD": [37.1893654, -101.1494994], #?
"Recruit F9": [0,0]})
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))
km = 6367 * c
return km
def get_lat(df):
return latlong[df['Well Name']][0]
def get_long(df):
return latlong[df['Well Name']][1]
```
#### Add latitude and longitude as features, add distances to every other well as features
```
df['LAT'] = df.apply(lambda x: get_lat(x), axis=1)
df['LON'] = df.apply(lambda x: get_long(x), axis=1)
dist_dict = {}
for k in latlong:
dict_name = k + '_DISTANCES'
k_dict = {}
lat1 = latlong[k][0]
lon1 = latlong[k][1]
for l in latlong:
lat2 = latlong[l][0]
lon2 = latlong[l][1]
if l == 'Recruit F9':
dist = haversine(0, 0, 0, 0)
elif k == "Recruit F9":
dist = haversine(0, 0, 0, 0)
else:
dist = haversine(lon1, lat1, lon2, lat2)
k_dict[l] = dist
dist_dict[dict_name] = k_dict
for i in dist_dict:
df[i] = np.nan
for j in dist_dict[i]:
df.loc[df['Well Name'] == j, i] = dist_dict[i][j]
```
#### First guess at facies using KNN
#### Fit RandomForect model and apply LeavePGroupsOut test
There is some bad log data in this dataset which I'd guess is due to rugose hole. PHIND gets as high at 80%, which is certainly spurious, so I'll remove data with cross-plot porosity greater than 40% from the dataset. CROSS H CATTLE well also looks pretty different from the others so I'm going to remove it from the training set.
```
df1 = df.dropna()
df1 = df1[(df1['Well Name'] != 'CROSS H CATTLE') & (df.PHIND < 40.0)]
facies = df1['Facies'].values
wells = df1['Well Name'].values
drop_list = ['Formation', 'Well Name', 'Facies', 'Depth', 'DPHI_EST', 'NPHI_EST', 'DeltaPHI',
'UMAA_EST', 'UR_QTZ', 'PE_EST', 'Recruit F9_DISTANCES', 'KIMZEY A_DISTANCES',
'NEWBY_DISTANCES', 'ALEXANDER D_DISTANCES', 'NOLAN_DISTANCES', 'FM_GRP_3', 'FM_GRP_0',
'FM_GRP_1',
'FM_GRP_2',
'FM_GRP_4']
# zhili drop 'FM_GRP_0','FM_GRP_1', 'FM_GRP_2', 'FM_GRP_4'
fv = df1.drop(drop_list, axis=1).values
X = preprocessing.StandardScaler().fit(fv).transform(fv)
y = facies
ne_grid = [150]
mf_grid = [10]
md_grid = [20]
msl_grid = [5]
mss_grid = [20]
keys = ['n_estimators', 'max_features', 'max_depth', 'min_samples_leaf', 'min_samples_split']
param_sets = itertools.product(ne_grid, mf_grid, md_grid, msl_grid, mss_grid)
param_grid = [dict(zip(keys, i)) for i in param_sets]
clf_list = []
for i, d in enumerate(param_grid):
clf = ensemble.RandomForestClassifier(n_estimators=d['n_estimators'],
class_weight='balanced',
min_samples_leaf=d['min_samples_leaf'],
min_samples_split=d['min_samples_split'],
max_features=d['max_features'],
max_depth=d['max_depth'],
n_jobs=-1)
lpgo = LeavePGroupsOut(n_groups=2)
f1rfc = []
for train, test in lpgo.split(X, y, groups=wells):
clf.fit(X[train], y[train])
score = clf.fit(X[train], y[train]).score(X[test], y[test])
f1rfc.append(score)
print("Average leave-two-wells-out F1 Score: %6f" % (np.mean(f1rfc)))
clf_list.append((clf, np.mean(f1rfc)))
np.max([i[1] for i in clf_list])
# df1.drop(drop_list, axis=1).FM_GRP_0
list(zip(df1.drop(drop_list, axis=1).columns, clf.feature_importances_))
keep_list0=list(df1.drop(drop_list, axis=1).columns)
```
#### Apply model to validation dataset
```
# refit model to entire training set
clf.fit(X, y)
# load validation data
test_set_df=pickle.load(open('/Users/zhiliwei/onedrive/科研总览/new_dissertation/my dessertation/1.intro/test_set_df.pickled','rb'))
vd = test_set_df
# compute extra log data features
vd['DPHI_EST'] = vd.apply(lambda x: estimate_dphi(x), axis=1).astype(float)
vd['RHOB_EST'] = vd.apply(lambda x: estimate_rhob(x), axis=1)
vd['NPHI_EST'] = vd.apply(lambda x: estimate_nphi(x), axis=1)
vd['RHOMAA_EST'] = vd.apply(lambda x: compute_rhomaa(x), axis=1)
vd['UMAA_EST'] = vd.apply(lambda x: compute_umaa(x), axis=1)
# Estimate lithology using Umaa Rhomaa solution
vd['UR_QTZ'] = np.nan
vd['UR_CLY'] = np.nan
vd['UR_CAL'] = np.nan
vd['UR_DOL'] = np.nan
vd.loc[vd.GR >= 40, 'UR_QTZ'] = vd.loc[vd.GR >= 40].apply(lambda x: ur1.get_qtz(x.UMAA_EST, x.RHOMAA_EST), axis=1)
vd.loc[vd.GR >= 40, 'UR_CLY'] = vd.loc[vd.GR >= 40].apply(lambda x: ur1.get_dol(x.UMAA_EST, x.RHOMAA_EST), axis=1)
vd.loc[vd.GR >= 40, 'UR_CAL'] = vd.loc[vd.GR >= 40].apply(lambda x: ur1.get_cal(x.UMAA_EST, x.RHOMAA_EST), axis=1)
vd.loc[vd.GR >= 40, 'UR_DOL'] = 0
vd.loc[vd.GR < 40, 'UR_QTZ'] = vd.loc[vd.GR < 40].apply(lambda x: ur2.get_qtz(x.UMAA_EST, x.RHOMAA_EST), axis=1)
vd.loc[vd.GR < 40, 'UR_DOL'] = vd.loc[vd.GR < 40].apply(lambda x: ur2.get_dol(x.UMAA_EST, x.RHOMAA_EST), axis=1)
vd.loc[vd.GR < 40, 'UR_CAL'] = vd.loc[vd.GR < 40].apply(lambda x: ur2.get_cal(x.UMAA_EST, x.RHOMAA_EST), axis=1)
vd.loc[vd.GR < 40, 'UR_CLY'] = 0
# Formation grouping
vd['FM_GRP'] = vd.Formation.map(fm_group_dict)
vd = pd.get_dummies(vd, prefix='FM_GRP', columns=['FM_GRP'])
# Water saturation
vd['SW'] = vd.apply(lambda x: archie(x), axis=1)
# Lat-long features
vd['LAT'] = vd.apply(lambda x: get_lat(x), axis=1)
vd['LON'] = vd.apply(lambda x: get_long(x), axis=1)
for i in dist_dict:
vd[i] = np.nan
for j in dist_dict[i]:
vd.loc[vd['Well Name'] == j, i] = dist_dict[i][j]
# haha
# Compute first guess at facies with KNN
X2 = preprocessing.StandardScaler().fit(vd[keep_list0].values).transform(vd[keep_list0].values)
# X2 = preprocessing.StandardScaler().fit(vd.values).transform(vd.values)
# vd['KNN_FACIES'] = clf0.predict(X2)
# Apply final model
drop_list1 = ['Formation', 'Well Name', 'Depth', 'DPHI_EST', 'NPHI_EST', 'DeltaPHI',
'UMAA_EST', 'UR_QTZ', 'Recruit F9_DISTANCES', 'KIMZEY A_DISTANCES',
'NEWBY_DISTANCES', 'ALEXANDER D_DISTANCES', 'NOLAN_DISTANCES', 'FM_GRP_3','Facies', 'FM_GRP_0',
'FM_GRP_1',
'FM_GRP_2',
'FM_GRP_4']
fv_vd1 = vd.drop(drop_list1, axis=1).values
X_vd1 = preprocessing.StandardScaler().fit(fv_vd1).transform(fv_vd1)
vd_predicted_facies = clf.predict(X_vd1)
vd.columns
X_vd1.shape
vd.describe()
a=list(vd.drop(drop_list1, axis=1).columns)
print(len(a))
b=list(df1.drop(drop_list, axis=1).columns)
print(len(b))
c=[item for item in b if item not in a]
for item in b:
if item in a:
continue
else:
print(item)
# vd['Facies'] = vd_predicted_facies
# vd.to_csv('RFC_submission_4_predictions.csv')
vd_predicted_facies
test_set_df.Facies.values
a=vd_predicted_facies.tolist()
b=test_set_df.Facies.values.tolist()
n=0
for i in range(len(a)):
if a[i]==b[i]:
n=n+1
print(n/len(a))
from sklearn.metrics import confusion_matrix
from classification_utilities import display_cm, display_adj_cm
facies_labels = ['SS', 'CSiS', 'FSiS', 'SiSh', 'MS',
'WS', 'D','PS', 'BS']
conf = confusion_matrix(b, a)
display_cm(conf, facies_labels, display_metrics=True, hide_zeros=True)
temp=['1','2','3','4','5','6','7','8','9']
import seaborn as sns
sns.heatmap(conf,annot=True, center=True,fmt='d',xticklabels=temp,yticklabels=temp)
plt.ylabel('True label')
plt.xlabel('Predicted label');
plt.show()
adjacent_facies = np.array([[1], [0,2], [1], [4], [3,5], [4,6,7], [5,7], [5,6,8], [6,7]])
def accuracy_adjacent(conf, adjacent_facies):
nb_classes = conf.shape[0]
total_correct = 0.
for i in np.arange(0,nb_classes):
total_correct += conf[i][i]
for j in adjacent_facies[i]:
total_correct += conf[i][j]
return total_correct / sum(sum(conf))
display_adj_cm(conf, facies_labels, adjacent_facies,
display_metrics=True, hide_zeros=True)
```
# test 9 feature apply clf0
```
test_set_df=pickle.load(open(r'C:\Users\H235652\Videos\zhili_2019_summer_intern\OneDrive-2019-06-15\my dessertation\1.intro\test_set_df.pickled','rb'))
df0=test_set_df
df0.head()
# vd_clf0_predicted_facies = clf0.predict(X_vd1)
x0.shape
conf = confusion_matrix(b, vd_clf0_predicted_facies)
display_cm(conf, facies_labels, display_metrics=True, hide_zeros=True)
```
| github_jupyter |
**[Course Home Page](https://www.kaggle.com/learn/machine-learning-for-insights)**
---
## Set Up
Today you will create partial dependence plots and practice building insights with data from the [Taxi Fare Prediction](https://www.kaggle.com/c/new-york-city-taxi-fare-prediction) competition.
We have again provided code to do the basic loading, review and model-building. Run the cell below to set everything up:
```
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# Environment Set-Up for feedback system.
from learntools.core import binder
binder.bind(globals())
from learntools.ml_explainability.ex3 import *
print("Setup Complete")
# Data manipulation code below here
data = pd.read_csv('../input/new-york-city-taxi-fare-prediction/train.csv', nrows=50000)
# Remove data with extreme outlier coordinates or negative fares
data = data.query('pickup_latitude > 40.7 and pickup_latitude < 40.8 and ' +
'dropoff_latitude > 40.7 and dropoff_latitude < 40.8 and ' +
'pickup_longitude > -74 and pickup_longitude < -73.9 and ' +
'dropoff_longitude > -74 and dropoff_longitude < -73.9 and ' +
'fare_amount > 0'
)
y = data.fare_amount
base_features = ['pickup_longitude',
'pickup_latitude',
'dropoff_longitude',
'dropoff_latitude']
X = data[base_features]
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)
first_model = RandomForestRegressor(n_estimators=30, random_state=1).fit(train_X, train_y)
print("Data sample:")
data.head()
data.describe()
```
## Question 1
Here is the code to plot the partial dependence plot for pickup_longitude. Run the following cell.
```
from matplotlib import pyplot as plt
from pdpbox import pdp, get_dataset, info_plots
feat_name = 'pickup_longitude'
pdp_dist = pdp.pdp_isolate(model=first_model, dataset=val_X, model_features=base_features, feature=feat_name)
pdp.pdp_plot(pdp_dist, feat_name)
plt.show()
```
Why does the partial dependence plot have this U-shape?
Does your explanation suggest what shape to expect in the partial dependence plots for the other features?
Create all other partial plots in a for-loop below (copying the appropriate lines from the code above).
```
for feat_name in base_features:
pdp_dist = _
_
plt.show()
```
Do the shapes match your expectations for what shapes they would have? Can you explain the shape now that you've seen them?
Uncomment the following line to check your intuition.
```
# q_1.solution()
```
## Q2
Now you will run a 2D partial dependence plot. As a reminder, here is the code from the tutorial.
```
inter1 = pdp.pdp_interact(model=my_model, dataset=val_X, model_features=feature_names, features=['Goal Scored', 'Distance Covered (Kms)'])
pdp.pdp_interact_plot(pdp_interact_out=inter1, feature_names=['Goal Scored', 'Distance Covered (Kms)'], plot_type='contour')
plt.show()
```
Create a 2D plot for the features `pickup_longitude` and `dropoff_longitude`. Plot it appropriately?
What do you expect it to look like?
```
# Add your code here
```
Uncomment the line below to see the solution and explanation for how one might reason about the plot shape.
```
# q_2.solution()
```
## Question 3
Consider a ride starting at longitude -73.92 and ending at longitude -74. Using the graph from the last question, estimate how much money the rider would have saved if they'd started the ride at longitude -73.98 instead?
```
savings_from_shorter_trip = _
q_3.check()
```
For a solution or hint, uncomment the appropriate line below.
```
# q_3.hint()
# q_3.solution()
```
## Question 4
In the PDP's you've seen so far, location features have primarily served as a proxy to capture distance traveled. In the permutation importance lessons, you added the features `abs_lon_change` and `abs_lat_change` as a more direct measure of distance.
Create these features again here. You only need to fill in the top two lines. Then run the following cell.
**After you run it, identify the most important difference between this partial dependence plot and the one you got without absolute value features. The code to generate the PDP without absolute value features is at the top of this code cell.**
---
```
# This is the PDP for pickup_longitude without the absolute difference features. Included here to help compare it to the new PDP you create
feat_name = 'pickup_longitude'
pdp_dist_original = pdp.pdp_isolate(model=first_model, dataset=val_X, model_features=base_features, feature=feat_name)
pdp.pdp_plot(pdp_dist_original, feat_name)
plt.show()
# create new features
data['abs_lon_change'] = _
data['abs_lat_change'] = _
features_2 = ['pickup_longitude',
'pickup_latitude',
'dropoff_longitude',
'dropoff_latitude',
'abs_lat_change',
'abs_lon_change']
X = data[features_2]
new_train_X, new_val_X, new_train_y, new_val_y = train_test_split(X, y, random_state=1)
second_model = RandomForestRegressor(n_estimators=30, random_state=1).fit(new_train_X, new_train_y)
feat_name = 'pickup_longitude'
pdp_dist = pdp.pdp_isolate(model=second_model, dataset=new_val_X, model_features=features_2, feature=feat_name)
pdp.pdp_plot(pdp_dist, feat_name)
plt.show()
q_4.check()
```
Uncomment the lines below to see a hint or the solution (including an explanation of the important differences between the plots).
```
# q_4.hint()
# q_4.solution()
```
## Question 5
Consider a scenario where you have only 2 predictive features, which we will call `feat_A` and `feat_B`. Both features have minimum values of -1 and maximum values of 1. The partial dependence plot for `feat_A` increases steeply over its whole range, whereas the partial dependence plot for feature B increases at a slower rate (less steeply) over its whole range.
Does this guarantee that `feat_A` will have a higher permutation importance than `feat_B`. Why or why not?
After you've thought about it, uncomment the line below for the solution.
```
# q_5.solution()
```
## Q6
The code cell below does the following:
1. Creates two features, `X1` and `X2`, having random values in the range [-2, 2].
2. Creates a target variable `y`, which is always 1.
3. Trains a `RandomForestRegressor` model to predict `y` given `X1` and `X2`.
4. Creates a PDP plot for `X1` and a scatter plot of `X1` vs. `y`.
Do you have a prediction about what the PDP plot will look like? Run the cell to find out.
Modify the initialization of `y` so that our PDP plot has a positive slope in the range [-1,1], and a negative slope everywhere else. (Note: *you should only modify the creation of `y`, leaving `X1`, `X2`, and `my_model` unchanged.*)
```
import numpy as np
from numpy.random import rand
n_samples = 20000
# Create array holding predictive feature
X1 = 4 * rand(n_samples) - 2
X2 = 4 * rand(n_samples) - 2
# Create y. you should have X1 and X2 in the expression for y
y = np.ones(n_samples)
# create dataframe because pdp_isolate expects a dataFrame as an argument
my_df = pd.DataFrame({'X1': X1, 'X2': X2, 'y': y})
predictors_df = my_df.drop(['y'], axis=1)
my_model = RandomForestRegressor(n_estimators=30, random_state=1).fit(predictors_df, my_df.y)
pdp_dist = pdp.pdp_isolate(model=my_model, dataset=my_df, model_features=['X1', 'X2'], feature='X1')
# visualize your results
pdp.pdp_plot(pdp_dist, 'X1')
plt.show()
q_6.check()
```
Uncomment the lines below for a hint or solution
```
# q_6.hint()
# q_6.solution()
```
## Question 7
Create a dataset with 2 features and a target, such that the pdp of the first feature is flat, but its permutation importance is high. We will use a RandomForest for the model.
*Note: You only need to supply the lines that create the variables X1, X2 and y. The code to build the model and calculate insights is provided*.
```
import eli5
from eli5.sklearn import PermutationImportance
n_samples = 20000
# Create array holding predictive feature
X1 = _
X2 = _
# Create y. you should have X1 and X2 in the expression for y
y = _
# create dataframe because pdp_isolate expects a dataFrame as an argument
my_df = pd.DataFrame({'X1': X1, 'X2': X2, 'y': y})
predictors_df = my_df.drop(['y'], axis=1)
my_model = RandomForestRegressor(n_estimators=30, random_state=1).fit(predictors_df, my_df.y)
pdp_dist = pdp.pdp_isolate(model=my_model, dataset=my_df, model_features=['X1', 'X2'], feature='X1')
pdp.pdp_plot(pdp_dist, 'X1')
plt.show()
perm = PermutationImportance(my_model).fit(predictors_df, my_df.y)
q_7.check()
# show the weights for the permutation importance you just calculated
eli5.show_weights(perm, feature_names = ['X1', 'X2'])
# Uncomment the following lines for the hint or solution
# q_7.hint()
# q_7.solution()
```
## Keep Going
Partial dependence plots can be really interesting. We have a [discussion thread](https://www.kaggle.com/learn-forum/65782) to talk about what real-world topics or questions you'd be curious to see addressed with partial dependence plots.
Next, learn how **[SHAP values](https://www.kaggle.com/dansbecker/shap-values)** help you understand the logic for each individual prediction.
---
**[Course Home Page](https://www.kaggle.com/learn/machine-learning-for-insights)**
| github_jupyter |
# Complex Fourier Transform
## Complex numbers
Although complex numbers are fundamentally disconnected from our reality, they can be used to solve science and engineering problems in two ways:
1. As parameters from a real world problem than can be substituted into a complex form.
2. As complex numbers that can be mathematically equivalent to the physical problem.
This second approach leads to the complex Fourier Transform, a more sophisticated version of the real Fourier Transform.
## Review of Real DFT
We defined the real version of the Discrete Fourier Transform according to the equations:
$$\mathbf{Re}X[k] = \sum^{N-1}_{n=0}x[n]\cos{(2\pi kn/N)}$$
$$\mathbf{Im}X[k] = -\sum^{N-1}_{n=0}x[n]\sin{(2\pi kn/N)}$$
where $0\leq k \leq N/2$
By introducing the normalization factor $2/N$, which comes from $Re\bar{X}[k]$ and $Im\bar{X}[k]$, we can write:
$$\mathbf{Re}X[k] = \frac{2}{N}\sum^{N-1}_{n=0}x[n]\cos{(2\pi kn/N)}$$
$$\mathbf{Im}X[k] = -\frac{2}{N}\sum^{N-1}_{n=0}x[n]\sin{(2\pi kn/N)}$$
The amplitudes of the cosine waves are contained in $Re X[k]$, while the amplitudes of the sine waves are contained in $ImX[k]$. These equations operate by correlating the respective cosine or sine wave with the time domain signal. In spite of using the names: real part and imaginary part, there are no complex numbers in these equations.
Even though the real DFT uses only real numbers, substitution allows the frequency domain to be represented using complex numbers. As suggested by the names of the arrays. In other words, we place a $j$ with each value in the imaginary part, and add the result to the real part. However, do not make the mistake of thinking that this is the **"complex DFT"**. This is nothing more than the real DFT with complex substitution.
While the real DFT is adequate for many applications in science and engineering, it is mathematically awkward in three respects:
1. Only takes advantage of complex numbers through the use of substitution, therefore complex numbers doesn't have a meaning here.
2. Poor handling of the negative frequency portion of the spectrum.
3. $Re X[0]$ and $Re X[N/2]$ need special handling.
## Euler's Refresher
We can use Euler's formula to express the relationship between the trigonometric functions and the complex exponential function as:
$$e^{jx}=\cos{(x)}+j\sin{(x)}$$
Using this formula, we can express sine and cosines as follows:
$$e^{-jx}=\cos{(-x)}+j\sin{(-x)}$$
Since cosine is an even and sine an odd function we can get:
$$e^{-jx}=\cos{(x)}-j\sin{(x)}$$
If we add $e^{jx}$ and $e^{-jx}$ we can get an expression for cosine as:
$$\cos(x) = \frac{e^{jx}+e^{-jx}}{2}$$
If we subtract $e^{jx}$ and $e^{-jx}$ we can get an expression for sine as:
$$\sin(x) = \frac{e^{jx}-e^{-jx}}{2j}$$
Rewriting for $x=\omega t$
$$\cos(\omega t) =\frac{1}{2} e^{j\omega t}+\frac{1}{2} e^{-j\omega t}$$
$$\sin(\omega t) =\frac{1}{2j}e^{j\omega t}-\frac{1}{2j}e^{-j\omega t}$$
With Euler's formula we see that the sum of exponential contains a positive frequency $\omega$ and a negative frequency $-\omega$.
# Complex DFT
The Complex Discrete Fourier Transform is defined as:
$$X[k] = \frac{1}{N}\sum\limits^{N-1}_{n=0}{x[n]e^{-j\frac{2\pi k n}{N}}} $$
Where $X[k]$ has $N-1$ points.
By using Euler's formula we can get a rectangular form for the Complex DFT:
$$X[k] = \frac{1}{N}\sum\limits^{N-1}_{n=0}{x[n]\left[\cos{\left(\frac{2\pi k n}{N}\right)} -j\sin{\left(\frac{2\pi k n}{N}\right)} \right]} $$
### Differences between Real DFT and Complex DFT
1. Real DFT converts a real time domain signal, $x[n]$ into two real frequency domain signals $Re X[k]$ and $Im X[k]$. In Complex DFT, $x[n]$ and $X[k]$ are arrays of complex numbers.
2. Real DFT uses only positive frequencies (k goes from 0 to N/2). Complex DFT uses positive and negative frequencies (k goes from 0 to N-1, positive frequencies go from 0 to N/2 and negative from N/2 to N-1).
3. Real DFT adds $j$ to the sine wave allowing the frequency spectrum to be represented by complex numbers. To convert back to sine and cosine waves we drop the $j$ and sum terms. This is mathematically incorrect!
4. Scaling factors of two is not needed in Complex DFT, since this is dealt by the positive and negative frequency nature of the transformation.
5. Complex DFT doesn't require special handling of $Re X[0]$ and $Re X[N/2]$.
```
import sys
sys.path.insert(0, '../../')
import numpy as np
import matplotlib.pyplot as plt
from Common import common_plots
from Common import statistics
cplots = common_plots.Plot()
file = {'x':'Signals/InputSignal_f32_1kHz_15kHz.dat'}
x = np.loadtxt(file['x'])
N,M = x.shape
x = x.reshape(N*M, 1)
cplots.plot_single(x.T, style='line')
plt.xlabel('samples')
plt.ylabel('amplitude');
```
### Create a FourierComplex Class
In this part you will create a class called `FourierComplex` which has the methods described in the implementation. The method `complex_dft` uses the equation described before to implement the Complex Fourier Transform. You have to take special care of your numpy arrays because they will hold complex values.
```
class FourierComplex():
def __init__(self, signal, domain='fraction', **kwargs):
"""
Function that calculates the Complex DFT of an input signal.
Parameters:
signal (numpy array): Array of numbers representing the signal to transform.
domain (string): String value that selects between frequency domain's
independent variable.
'samples' returns number of samples between 0 to N/2
'fraction' returns a fraction of the sampling rate between 0 to 0.5
'natural' returns the natural frequency between 0 and pi.
'analog' returns analog frequency between 0 and fsamp/2
kwargs: - fsamp (float): value representing the sampling frequency.
(Only used for 'analog' style).
Attributes:
signal (numpy array): orignal signal.
dft (complex numpy array): complex Fourier Transform of input signal.
rex (numpy array): real DFT part of input signal.
imx (numpy array): imaginary DFT part of input signal.
domain (numpy array): Frequency domain's independent variable.
"""
self.signal = None
self.dft = None
self.rex = None
self.imx = None
self.domain = None
return
def complex_dft(self):
"""
Function that calculates the Complex DFT of an input signal.
Returns:
complex numpy array: complex DFT of input signal of type imaginary.
"""
return None
def real_dft(self):
"""
Function that calculates the real part of the Complex DFT of
an input signal.
Returns:
numpy array: real part of the Complex DFT of input signal.
"""
return None
def imag_dft(self):
"""
Function that calculates the imaginary part of the Complex DFT of
an input signal.
Returns:
numpy array: imaginary part of the Complex DFT of input signal.
"""
return None
def frequency_domain(self, style='fraction', **kwargs):
"""
Function that calculates the frequency domain independent variable.
Parameters:
obtain the frequency domain.
style (string): String value that selects between frequency domain's
independent variable.
'samples' returns number of samples between 0 to N/2
'fraction' returns a fraction of the sampling rate between 0 to 0.5
'natural' returns the natural frequency between 0 and pi.
'analog' returns analog frequency between 0 and fsamp/2
fsamp (float): Float value representing the sampling frequency.
(Only used for 'analog' style).
Returns:
numpy array: Returns frequency domain's independent variable.
"""
N = self.dft.shape[0]
t = np.arange(N)
if(style=='fraction'):
return t/(N-1)
elif(style=='natural'):
return np.pi*(t/(N-1))
elif(style=='analog'):
return kwargs['fsamp']*t/(N-1)
elif(style=='samples'):
return t
else:
return t
```
### Test your FourierComplex Class
You can test your implementation and compare it with SciPy, if there is any mismatch try to correct your code.
```
from scipy.fftpack import fft
#SciPy Calculations
y =fft(x.flatten())
N = y.shape[0]
rey = (np.real(y)).reshape(-1,1)/N
imy = (np.imag(y)).reshape(-1,1)/N
#Our Calculation
X = FourierComplex(x, domain='fraction')
plt.suptitle("Comparison between Scipy and Our Implementation", fontsize=14)
plt.subplot(1,2,1)
plt.plot(X.domain, X.rex, label='Our Implementation')
plt.plot(X.domain, rey, label='SciPy Implementation')
plt.xlabel('Fraction Domain')
plt.ylabel('Amplitude')
plt.legend()
plt.grid('on');
plt.subplot(1,2,2)
plt.plot(X.domain, X.imx, label='Our Implementation')
plt.plot(X.domain, imy, label='SciPy Implementation')
plt.xlabel('Fraction Domain')
plt.ylabel('Amplitude')
plt.legend()
plt.grid('on');
```
## Complex IDFT
The Complex Inverse Discrete Fourier Transform is defined as:
$$x[n] = \sum\limits^{N-1}_{k=0}{X[k]e^{j\frac{2\pi k n}{N}}} $$
Where $x[n]$ has $N-1$ points.
By using Euler's formula we can get a rectangular form for the Complex IDFT:
$$x[n] = \sum\limits^{N-1}_{k=0}{\left(Re X[k]+j ImX[k] \right)e^{j\frac{2\pi k n}{N}}} $$
$$ = \sum\limits^{N-1}_{k=0}{Re X[k] e^{j\frac{2\pi k n}{N}}} + \sum\limits^{N-1}_{k=0}{j Im X[k] e^{j\frac{2\pi k n}{N}}} $$
with:
$$e^{j\frac{2\pi k n}{N}} = \left[\cos{\left(\frac{2\pi k n}{N}\right)} +j\sin{\left(\frac{2\pi k n}{N}\right)} \right]$$
therefore:
$$x[n] = \sum\limits^{N-1}_{k=0}{Re X[k] \left[\cos{\left(\frac{2\pi k n}{N}\right)} +j\sin{\left(\frac{2\pi k n}{N}\right)} \right]} + \sum\limits^{N-1}_{k=0}{Im X[k] \left[-\sin{\left(\frac{2\pi k n}{N}\right)} +j\cos{\left(\frac{2\pi k n}{N}\right)} \right]} $$
In words, each value in the real part of the frequency domain contributes a real cosine wave and an imaginary sine wave to the time domain. Likewise, each value in the imaginary part of the frequency domain contributes a real sine wave and an imaginary cosine wave. The time domain is found by adding all these real and imaginary sinusoids. The important concept is that each value in the frequency domain produces both a real sinusoid and an imaginary sinusoid in the time domain.
### Create a ComplexFourierTransform Class
Now you will implement a class called `ComplexFourierTransform` which extends your previous class `FourierComplex` and inherits all of its attributes. You can search about the `super` function for this.
```
class ComplexFourierTransform():
def __init__(self, signal, domain='fraction', **kwargs):
"""
Function that calculates the Complex DFT and IDFT of an input signal.
Parameters:
Same parameters as FourierComplex class.
Attributes:
Ihnerits same attributes as FourierComplex class.
idft (complex numpy array): complex IDFT of the signal
"""
self.idft = None
return
def complex_idft(self):
"""
Function that calculates the Complex IDFT of an input signal.
Returns:
complex numpy array: complex IDFT of input signal of type imaginary.
"""
return None
```
### Test your ComplexFourierTransform Class
You can test your implementation and compare it with the original signal, if there is any mismatch try to correct your code. Try to understand both the real and imaginary signals that the Complex IDFT generates.
```
#Our Calculation
X = ComplexFourierTransform(x, domain='fraction')
plt.suptitle("Complex IDFT", fontsize=14)
plt.subplot(2,1,1)
plt.plot(x, label='Original Signal')
plt.plot(np.real(X.idft), label='Complex IDT -Real Part')
plt.xlabel('Sample')
plt.ylabel('Amplitude')
plt.legend()
plt.grid('on');
plt.subplot(2,1,2)
plt.plot(np.imag(X.idft), label='Complex IDT -Imaginary Part')
plt.xlabel('Sample')
plt.ylabel('Amplitude')
plt.legend()
plt.grid('on');
```
Find the mean and variance of the real and imaginary IDFT signal using the `Statistics` class developed before.
```
stat = None
print('Mean of the real IDFT signal = {:.3f}'.format(stat.mean(np.real(X.idft))))
print('Mean of the imaginary IDFT signal = {:.3f}'.format(stat.mean(np.imag(X.idft))))
print('\nVariance of the real IDFT signal = {:.3f}'.format(stat.variance(np.real(X.idft))))
print('Variance of the imaginary IDFT signal = {:.3f}'.format(stat.variance(np.imag(X.idft))))
```
You can see that our signal can be though as "pure" real signal.
As a final exercise, save your `ComplexFourierTransform` class in the `Common` folder as `complex_fourier_transform.py`
| github_jupyter |
<a href="https://colab.research.google.com/github/faizuddin/IBB31103/blob/main/lab_exercise_2_(probability).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Probability Exercise
We’re going to calculate the probability a student gets an A (80%+) in math, given they miss 10 or more classes.
## Dataset used in this exercise
* https://www.kaggle.com/uciml/student-alcohol-consumption (*in this exercise, I have included the one from IBB31103 code repository*)
## Data structure used this exercise
* Numpy (https://numpy.org)
* Pandas (https://pandas.pydata.org)
```
import numpy as np
import pandas as pd
# download file from IBB31103 code repository
!wget https://raw.githubusercontent.com/faizuddin/IBB31103/main/student-mat.csv
# load the file into pandas dataframe
df = pd.read_csv("student-mat.csv")
```
## Inspect the data using Pandas built-in functions
* View the first 5 records in the dataset: ``head()``
* Check the total number of records: ``len()``
* Basic statistics of the dataset (only for columns with numerical data): ``describe()``
```
df.head()
print("Total number of records: \n")
len(df)
df.describe()
```
## Goal
Compute the probability a student gets an A (80%+) in math, given they miss 10 or more classes.
### Extract related columns
From the dataset, we are only concerned with the following columns:
1. ``absences`` (number of absences)
2. ``G3`` (final grade from 0 to 20)
Original values in ``G3`` are on a 0-20 scale, therefore we multiply ``G3`` by 5 to get the values on 0-100 scale.
```
# Extract columns of interest and put them in absence_grade dataframe
absence_grade = df[["absences", "G3"]]
# View the first 5 records
absence_grade.head()
```
### Helper/utility columns
To make things easier we create a couple of booleans columns from ``absence_grade``:
1. ``grade_A`` - 1 if a student achieved 80% or higher as final score or 0 otherwise.
2. ``high_absences`` - 1 if a student missed 10 or more classes or 0 otherwise.
3. ``count`` - to build pivot table
We use function ``where`` from ``numpy`` library to get elements from ``absence_grade`` based on the given conditions (e.g. ``G3`` >= 80, ``absences`` >= 10)
**References**
* https://numpy.org/doc/stable/reference/generated/numpy.where.html
```
# Multiply G3 by 5 and check whether G3 is equal or more than 80, if it does give value 1 to grade_A or 0 otherwise.
absence_grade["grade_A"] = np.where(absence_grade["G3"]*5 >= 80, 1, 0)
# Check whether absences is equal or more than 10, if it does give value 1 to grade_A or 0 otherwise.
absence_grade["high_absences"] = np.where(absence_grade["absences"] >= 10, 1, 0)
# Count
absence_grade["count"] = 1
# Drop absences and G3 columns - we don't need them to compute probability.
absence_grade = absence_grade[["grade_A", "high_absences", "count"]]
# View the first 5 records of absence_grade dataframe
absence_grade.head()
```
## Pivot Table
We use Pandas ``pivot_table`` function to create a spreadsheet-style pivot table as a DataFrame. This allows us to build distribution tables just like how we did in the lecture.
**References**
* https://en.wikipedia.org/wiki/Pivot_table
* https://pandas.pydata.org/docs/reference/api/pandas.pivot_table.html
```
pt = pd.pivot_table(
absence_grade,
values="count",
index=["grade_A"],
columns=["high_absences"],
aggfunc=np.size,
fill_value=0
)
# View the table
pt
```
## Calculating Probabilities
In our case:
* ``P(A)`` is the probability of a grade of 80% or more.
* ``P(B)`` is the probability of missing 10 or more classes.
* ``P(A|B)`` is the probability of a 80% grade or more, given missing 10 or more classes.
### Calculation
* ``P(A)``: those who got 80% or more (35 + 5) / total students (395)
* ``P(B)``: those who is absent 10 or more times (78 + 5) / total students (395)
* ``P(A,B)``: those who got 80% or more **AND** is absent 10 or more times (5) / total students (395)
* ``P(A|B)``: as per conditional probability formula: P(A,B)/P(B)
```
# P(A)
A = (pt.iloc[1,0] + pt.iloc[1,1])/(pt.iloc[1,0] + pt.iloc[1,1]+pt.iloc[0,0] + pt.iloc[0,1])
# P(B)
B = (pt.iloc[0,1] + pt.iloc[1,1])/(pt.iloc[1,0] + pt.iloc[1,1]+pt.iloc[0,0] + pt.iloc[0,1])
# P(A,B)
AB = pt.iloc[1,1]/(pt.iloc[1,0] + pt.iloc[1,1]+pt.iloc[0,0] + pt.iloc[0,1])
# P(A|B)
ABcond = AB/B
print("P(A) = " + str(A))
print("P(B) = " + str(B))
print("P(A,B) = " + str(AB))
print("P(A|B) = " + str(ABcond))
```
## Using Bayes' rule
``P(A|B) = P(B|A).P(A) / P(B)``
### Calculation
Additional calculation for ``P(B|A)``, that is proability of missing 10 classes or more, given getting 80% grades or more.
* ``P(B|A) = P(B,A)/P(A)`` : *probability* of those who got 80% or more **AND** is absent 10 or more times / *probability* of those who got 80% or more.
```
# P(B|A). Note that P(A,B) == P(B,A): commutative law
BAcond = AB/A
BayesAB = (BAcond * A) / B
print("Bayes' Rule")
print("P(A|B) = " + str(BayesAB))
```
## Conclusion
Go to class if you want good grades!
| github_jupyter |
# Working with Projections
This section of the tutorial discusses [map projections](https://en.wikipedia.org/wiki/Map_projection). If you don't know what a projection is, or are looking to learn more about how they work in `geoplot`, this page is for you!
I recommend following along with this tutorial interactively using [Binder](https://mybinder.org/v2/gh/ResidentMario/geoplot/master?filepath=notebooks/tutorials/Working_with_Projections.ipynb).
## Projection and unprojection
```
import geopandas as gpd
import geoplot as gplt
%matplotlib inline
# load the example data
contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa'))
gplt.polyplot(contiguous_usa)
```
This map is an example of an unprojected plot: it reproduces our coordinates as if they were on a flat Cartesian plane. But remember, the Earth is not a flat surface; it's a sphere. This isn't a map of the United States that you'd seen in print anywhere because it badly distorts both of the [two criteria](http://www.geo.hunter.cuny.edu/~jochen/gtech201/lectures/lec6concepts/Map%20coordinate%20systems/How%20to%20choose%20a%20projection.htm) most projections are evaluated on: *shape* and *area*.
For sufficiently small areas, the amount of distortion is very small. This map of New York City, for example, is reasonably accurate:
```
boroughs = gpd.read_file(gplt.datasets.get_path('nyc_boroughs'))
gplt.polyplot(boroughs)
```
But there is a better way: use a **projection**.
A projection is a way of mapping points on the surface of the Earth into two dimensions (like a piece of paper or a computer screen). Because moving from three dimensions to two is intrinsically lossy, no projection is perfect, but some will definitely work better in certain case than others.
The most common projection used for the contiguous United States is the [Albers Equal Area projection](https://en.wikipedia.org/wiki/Albers_projection). This projection works by wrapping the Earth around a cone, one that's particularly well optimized for locations near the middle of the Northern Hemisphere (and particularly poorly for locations at the poles).
To add a projection to a map in `geoplot`, pass a `geoplot.crs` object to the `projection` parameter on the plot. For instance, here's what we get when we try `Albers` out on the contiguous United States:
```
import geoplot.crs as gcrs
gplt.polyplot(contiguous_usa, projection=gcrs.AlbersEqualArea())
```
For a list of projections implemented in `geoplot`, refer to [the projections reference](https://scitools.org.uk/cartopy/docs/latest/crs/projections.html) in the `cartopy` documentation (`cartopy` is the library `geoplot` relies on for its projections).
## Stacking projected plots
A key feature of `geoplot` is the ability to stack plots on top of one another.
```
cities = gpd.read_file(gplt.datasets.get_path('usa_cities'))
ax = gplt.polyplot(
contiguous_usa,
projection=gcrs.AlbersEqualArea()
)
gplt.pointplot(cities, ax=ax)
```
By default, `geoplot` will set the [extent](Customizing_Plots.ipynb#extent) (the area covered by the plot) to the [total_bounds](https://geopandas.org/reference.html#geopandas.GeoSeries.total_bounds) of the last plot stacked onto the map.
However, suppose that even though we have data for One entire United States (plus Puerto Rico) we actually want to display just data for the contiguous United States. An easy way to get this is setting the `extent` parameter using `total_bounds`.
```
ax = gplt.polyplot(
contiguous_usa,
projection=gcrs.AlbersEqualArea()
)
gplt.pointplot(cities, ax=ax, extent=contiguous_usa.total_bounds)
```
The section of the tutorial on [Customizing Plots](Customizing_Plots.ipynb#Extent) explains the `extent` parameter in more detail.
## Projections on subplots
It is possible to compose multiple axes together into a single panel figure in `matplotlib` using the `subplots` feature. This feature is highly useful for creating side-by-side comparisons of your plots, or for stacking your plots together into a single more informative display.
```
import matplotlib.pyplot as plt
import geoplot as gplt
f, axarr = plt.subplots(1, 2, figsize=(12, 4))
gplt.polyplot(contiguous_usa, ax=axarr[0])
gplt.polyplot(contiguous_usa, ax=axarr[1])
```
`matplotlib` supports subplotting projected maps using the `projection` argument to `subplot_kw`.
```
proj = gcrs.AlbersEqualArea(central_longitude=-98, central_latitude=39.5)
f, axarr = plt.subplots(1, 2, figsize=(12, 4), subplot_kw={
'projection': proj
})
gplt.polyplot(contiguous_usa, projection=proj, ax=axarr[0])
gplt.polyplot(contiguous_usa, projection=proj, ax=axarr[1])
```
The [Gallery](../gallery/index.rst) includes several demos, like the [Pointplot Scale Functions](../gallery/plot_usa_city_elevations.rst) demo, that use this feature to good effect.
Notice that in this code sample we specified some additional parameters for our projection. The `central_longitude=-98` and `central_latitude=39.5` parameters set the "center point" around which the points and shapes on the map are reprojected (in this case we use the [geographic center of the contiguous United States](https://en.wikipedia.org/wiki/Geographic_center_of_the_contiguous_United_States)).
When you pass a projection to a `geoplot` function, `geoplot` will infer these values for you. But when passing the projection directly to `matplotlib` you must set them yourself.
| github_jupyter |
```
# this is an example of federated leraning for voice data
# I borrowed almost all codes from this repositry. Thank a lot!
# https://github.com/tugstugi/pytorch-speech-commands.git
# you can learn
# 1. how to handle audio datasets
# 2. how to do federated learning with audio datasets
import warnings
warnings.filterwarnings('ignore')
# First let's run some code for jupyter notebooks
%reload_ext autoreload
%autoreload 2
%matplotlib inline
# import dependencies.
import torch
from torchvision.transforms import Compose
from torch.utils.data.sampler import WeightedRandomSampler
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
import torch.nn as nn
import math
import time
from tqdm import *
import os
import librosa
import numpy as np
import random
# from torch.autograd import Variable
# CLASSES = 'unknown, silence, yes, no, up, down, left, right, on, off, stop, go'.split(', ')
CLASSES = 'unknown, silence, yes, no, left, right'.split(', ')
# prepare datasets
# prepare datasets
# create directory it not exist
# we put data on datasets directory
if os.path.isdir('./datasets') is False:
try:
os.mkdir('./datasets')
except OSError:
print ("Creation of the directory datasets failed")
# download data
# ! wget -O datasets/speech_commands_v0.01.tar.gz http://download.tensorflow.org/data/speech_commands_v0.01.tar.gz
# prepare directories
if os.path.isdir('./datasets/speech_commands') is False:
try:
os.mkdir('./datasets/speech_commands')
except OSError:
print ("Creation of the directory datasets/speech_commands failed")
if os.path.isdir('./datasets/speech_commands/audio') is False:
try:
os.mkdir('./datasets/speech_commands/audio')
except OSError:
print ("Creation of the directory datasets/speech_commands/audio failed")
# untar files.
# ! tar -xzf datasets/speech_commands_v0.01.tar.gz -C datasets/speech_command/audio
# once you downloaded datasets,
# you can split datasets into train and valid.
# since which one is for validation is defined by txt file, just split data accordingly.
# mode files
def move_files(src_folder, to_folder, list_file):
with open(list_file) as f:
for line in f.readlines():
line = line.rstrip()
dirname = os.path.dirname(line)
dest = os.path.join(to_folder, dirname)
if not os.path.exists(dest):
os.mkdir(dest)
shutil.move(os.path.join(src_folder, line), dest)
# move files
def prepare_dataset():
audio_folder = "datasets/speech_commands/audio"
validation_path = "datasets/speech_commands/audio/validation_list.txt"
test_path = "datasets/speech_commands/audio/testing_list.txt"
valid_folder = "datasets/speech_commands/valid"
test_folder = "datasets/speech_commands/test"
train_folder = "datasets/speech_commands/train"
if os.path.isdir(valid_folder) is False:
os.mkdir(valid_folder)
if os.path.isdir(test_folder) is False:
os.mkdir(test_folder)
move_files(audio_folder, test_folder, test_path)
move_files(audio_folder, valid_folder, validation_path)
os.rename(audio_folder, train_folder)
# import shutil for moving files.
# impo rt shutil
# run prepare datasets
# prepare_dataset()
# here we define convenient functions for audio.
# most of them is for data augmentation
# this is just returning true or false ramdomly
def should_apply_transform(prob=0.5):
"""Transforms are only randomly applied with the given probability."""
return random.random() < prob
# change ampletude for data augmentation
class ChangeAmplitude(object):
"""Changes amplitude of an audio randomly."""
def __init__(self, amplitude_range=(0.7, 1.1)):
self.amplitude_range = amplitude_range
def __call__(self, data):
if not should_apply_transform():
return data
data['samples'] = data['samples'] * random.uniform(*self.amplitude_range)
return data
# change speedch and pitch for data augmentation
class ChangeSpeedAndPitchAudio(object):
"""Change the speed of an audio. This transform also changes the pitch of the audio."""
def __init__(self, max_scale=0.2):
self.max_scale = max_scale
def __call__(self, data):
if not should_apply_transform():
return data
samples = data['samples']
sample_rate = data['sample_rate']
scale = random.uniform(-self.max_scale, self.max_scale)
speed_fac = 1.0 / (1 + scale)
data['samples'] = np.interp(np.arange(0, len(samples), speed_fac), np.arange(0,len(samples)), samples).astype(np.float32)
return data
# function to fix audio length
# Because our architecture is not RNN-based but CNN-based, we need shapes of all input data exact same.
class FixAudioLength(object):
"""Either pads or truncates an audio into a fixed length."""
def __init__(self, time=1):
self.time = time
def __call__(self, data):
samples = data['samples']
sample_rate = data['sample_rate']
length = int(self.time * sample_rate)
if length < len(samples):
data['samples'] = samples[:length]
elif length > len(samples):
data['samples'] = np.pad(samples, (0, length - len(samples)), "constant")
return data
class ToSTFT(object):
"""Applies on an audio the short time fourier transform."""
def __init__(self, n_fft=2048, hop_length=512):
self.n_fft = n_fft
self.hop_length = hop_length
def __call__(self, data):
samples = data['samples']
sample_rate = data['sample_rate']
data['n_fft'] = self.n_fft
data['hop_length'] = self.hop_length
data['stft'] = librosa.stft(samples, n_fft=self.n_fft, hop_length=self.hop_length)
data['stft_shape'] = data['stft'].shape
return data
class StretchAudioOnSTFT(object):
"""Stretches an audio on the frequency domain."""
def __init__(self, max_scale=0.2):
self.max_scale = max_scale
def __call__(self, data):
if not should_apply_transform():
return data
stft = data['stft']
sample_rate = data['sample_rate']
hop_length = data['hop_length']
scale = random.uniform(-self.max_scale, self.max_scale)
stft_stretch = librosa.core.phase_vocoder(stft, 1+scale, hop_length=hop_length)
data['stft'] = stft_stretch
return data
class TimeshiftAudioOnSTFT(object):
"""A simple timeshift on the frequency domain without multiplying with exp."""
def __init__(self, max_shift=8):
self.max_shift = max_shift
def __call__(self, data):
if not should_apply_transform():
return data
stft = data['stft']
shift = random.randint(-self.max_shift, self.max_shift)
a = -min(0, shift)
b = max(0, shift)
stft = np.pad(stft, ((0, 0), (a, b)), "constant")
if a == 0:
stft = stft[:,b:]
else:
stft = stft[:,0:-a]
data['stft'] = stft
return data
class FixSTFTDimension(object):
"""Either pads or truncates in the time axis on the frequency domain, applied after stretching, time shifting etc."""
def __call__(self, data):
stft = data['stft']
t_len = stft.shape[1]
orig_t_len = data['stft_shape'][1]
if t_len > orig_t_len:
stft = stft[:,0:orig_t_len]
elif t_len < orig_t_len:
stft = np.pad(stft, ((0, 0), (0, orig_t_len-t_len)), "constant")
data['stft'] = stft
return data
# data augmentation
data_aug_transform = Compose([
ChangeAmplitude(),
ChangeSpeedAndPitchAudio(),
FixAudioLength(),
ToSTFT(),
StretchAudioOnSTFT(),
TimeshiftAudioOnSTFT(),
FixSTFTDimension()])
class BackgroundNoiseDataset(Dataset):
"""Dataset for silence / background noise."""
def __init__(self, folder, transform=None, sample_rate=16000, sample_length=1):
audio_files = [d for d in os.listdir(folder) if os.path.isfile(os.path.join(folder, d)) and d.endswith('.wav')]
samples = []
for f in audio_files:
path = os.path.join(folder, f)
s, sr = librosa.load(path, sample_rate)
samples.append(s)
samples = np.hstack(samples)
c = int(sample_rate * sample_length)
r = len(samples) // c
self.samples = samples[:r*c].reshape(-1, c)
self.sample_rate = sample_rate
self.classes = CLASSES
self.transform = transform
self.path = folder
def __len__(self):
return len(self.samples)
def __getitem__(self, index):
data = {'samples': self.samples[index], 'sample_rate': self.sample_rate, 'target': 1, 'path': self.path}
if self.transform is not None:
data = self.transform(data)
return data
# define background nosie datasets
# background_noise_dir = "./datasets/speech_commands/train/_background_noise_"
background_noise_dir = "/disk2/ohashi/pytorch-speech-commands/datasets/speech_commands/train/_background_noise_"
bg_dataset = BackgroundNoiseDataset(background_noise_dir, data_aug_transform)
# function to add background noise on datasets
class AddBackgroundNoiseOnSTFT(Dataset):
"""Adds a random background noise on the frequency domain."""
def __init__(self, bg_dataset, max_percentage=0.45):
self.bg_dataset = bg_dataset
self.max_percentage = max_percentage
def __call__(self, data):
if not should_apply_transform():
return data
noise = random.choice(self.bg_dataset)['stft']
percentage = random.uniform(0, self.max_percentage)
data['stft'] = data['stft'] * (1 - percentage) + noise * percentage
return data
# create a function
add_bg_noise = AddBackgroundNoiseOnSTFT(bg_dataset)
# function to convert data from STFT into MelSpectrogram
class ToMelSpectrogramFromSTFT(object):
"""Creates the mel spectrogram from the short time fourier transform of a file. The result is a 32x32 matrix."""
def __init__(self, n_mels=32):
self.n_mels = n_mels
def __call__(self, data):
stft = data['stft']
sample_rate = data['sample_rate']
n_fft = data['n_fft']
mel_basis = librosa.filters.mel(sample_rate, n_fft, self.n_mels)
s = np.dot(mel_basis, np.abs(stft)**2.0)
data['mel_spectrogram'] = librosa.power_to_db(s, ref=np.max)
return data
class DeleteSTFT(object):
"""Pytorch doesn't like complex numbers, use this transform to remove STFT after computing the mel spectrogram."""
def __call__(self, data):
del data['stft']
return data
class ToTensor(object):
"""Converts into a tensor."""
def __init__(self, np_name, tensor_name, normalize=None):
self.np_name = np_name
self.tensor_name = tensor_name
self.normalize = normalize
def __call__(self, data):
tensor = torch.FloatTensor(data[self.np_name])
if self.normalize is not None:
mean, std = self.normalize
tensor -= mean
tensor /= std
data[self.tensor_name] = tensor
return data
# define data preprocessing more
n_mels = 32
train_feature_transform = Compose([
ToMelSpectrogramFromSTFT(n_mels=n_mels),
DeleteSTFT(),
ToTensor('mel_spectrogram', 'input')])
class LoadAudio(object):
"""Loads an audio into a numpy array."""
def __init__(self, sample_rate=16000):
self.sample_rate = sample_rate
def __call__(self, data):
path = data['path']
if path:
samples, sample_rate = librosa.load(path, self.sample_rate)
else:
# silence
sample_rate = self.sample_rate
samples = np.zeros(sample_rate, dtype=np.float32)
data['samples'] = samples
data['sample_rate'] = sample_rate
return data
class SpeechCommandsDataset(Dataset):
"""Google speech commands dataset. Only 'yes', 'no', 'up', 'down', 'left',
'right', 'on', 'off', 'stop' and 'go' are treated as known classes.
All other classes are used as 'unknown' samples.
See for more information: https://www.kaggle.com/c/tensorflow-speech-recognition-challenge
"""
def __init__(self, folder, transform=None, classes=CLASSES, silence_percentage=0.1, use_rate=1.0):
all_classes = [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d)) and not d.startswith('_')]
#for c in classes[2:]:
# assert c in all_classes
class_to_idx = {classes[i]: i for i in range(len(classes))}
for c in all_classes:
if c not in class_to_idx:
class_to_idx[c] = 0
data = []
for c in all_classes:
d = os.path.join(folder, c)
target = class_to_idx[c]
if c in classes:
for f in os.listdir(d):
path = os.path.join(d, f)
data.append((path, target))
# data = []
# for c in all_classes:
# d = os.path.join(folder, c)
# target = class_to_idx[c]
# for f in os.listdir(d):
# path = os.path.join(d, f)
# data.append((path, target))
# add silence
target = class_to_idx['silence']
data += [('', target)] * int(len(data) * silence_percentage)
self.classes = classes
self.data = data
self.transform = transform
def __len__(self):
return len(self.data)
def __getitem__(self, index):
path, target = self.data[index]
data = {'path': path, 'target': target}
if self.transform is not None:
data = self.transform(data)
# return data, target
return data['input'], target
def make_weights_for_balanced_classes(self):
"""adopted from https://discuss.pytorch.org/t/balanced-sampling-between-classes-with-torchvision-dataloader/2703/3"""
nclasses = len(self.classes)
count = np.zeros(nclasses)
for item in self.data:
count[item[1]] += 1
N = float(sum(count))
weight_per_class = N / count
weight = np.zeros(len(self))
for idx, item in enumerate(self.data):
weight[idx] = weight_per_class[item[1]]
return weight
# here lets see each augmetation steps
# First, let's see a data sample
import IPython.display
example_path = "/disk2/ohashi/pytorch-speech-commands/datasets/speech_commands/train/right/9f4098cb_nohash_0.wav"
# example_path = "datasets/speech_commands/train/five/4def68db_nohash_1.wav"
IPython.display.Audio(example_path)
# data is like data = {'path': path, 'target': target}
# 7 if for 'right'
sample_data = {
'path': example_path,
'target': 7
}
# CLASSES[7]
# load audio
# samples keeps actual data which mean 16000 numbers, which means exact 1 second of audio
_load_audio = LoadAudio()
_audio_sample = _load_audio(sample_data)
len(_audio_sample["samples"])
# let's see wave form too
import librosa
import librosa.display
import matplotlib.pyplot as plt
x, sr = librosa.load(sample_data['path'])
print(x, sr)
plt.figure(figsize=(14, 5))
librosa.display.waveplot(x, sr=sr)
# ToSTFT change shape from (16000) to (1025, 36)
_toSTFT = ToSTFT()
_stft_sample = _toSTFT(_audio_sample)
_stft_sample["stft_shape"]
# then change shape from (1025, 36) to (32, 32)
# this is the shape of input
_toMelSpectrogramFromSTFT = ToMelSpectrogramFromSTFT()
_mel_sample = _toMelSpectrogramFromSTFT(_stft_sample)
_mel_sample["mel_spectrogram"].shape
# finally we define dataset here
# # train_dataset_dir = "./datasets/speech_commands/train"
# train_dataset_dir = "/disk2/ohashi/pytorch-speech-commands/datasets/speech_commands/train"
# train_dataset = SpeechCommandsDataset(train_dataset_dir,
# Compose([LoadAudio(),
# data_aug_transform,
# add_bg_noise,
# train_feature_transform]))
# specify the percent of entire datasets
use_rate = 0.5
# use_rate = 1.0
train_dataset_dir = "./datasets/speech_commands/train"
train_dataset = SpeechCommandsDataset(train_dataset_dir,
Compose([LoadAudio(),
data_aug_transform,
add_bg_noise,
train_feature_transform]), use_rate=use_rate)
# this is a function to create melSpectrogram datasets from audio directly to skip data augumentation
class ToMelSpectrogram(object):
"""Creates the mel spectrogram from an audio. The result is a 32x32 matrix."""
def __init__(self, n_mels=32):
self.n_mels = n_mels
def __call__(self, data):
samples = data['samples']
sample_rate = data['sample_rate']
s = librosa.feature.melspectrogram(samples, sr=sample_rate, n_mels=self.n_mels)
data['mel_spectrogram'] = librosa.power_to_db(s, ref=np.max)
return data
valid_feature_transform = Compose([
ToMelSpectrogram(n_mels=n_mels),
ToTensor('mel_spectrogram', 'input')])
# define validation sets
# valid_dataset_dir = "./datasets/speech_commands/valid"
valid_dataset_dir = "/disk2/ohashi/pytorch-speech-commands/datasets/speech_commands/valid"
valid_dataset = SpeechCommandsDataset(valid_dataset_dir,
Compose([LoadAudio(),
FixAudioLength(),
valid_feature_transform]))
# get weights for each classes
weights = train_dataset.make_weights_for_balanced_classes()
len(weights)
weights[:4]
# define dataloaders
batch_size = 64
dataload_workers_nums = 4
sampler = WeightedRandomSampler(weights, len(weights))
train_dataloader = DataLoader(train_dataset, batch_size=batch_size, sampler=sampler,
num_workers=dataload_workers_nums)
valid_dataloader = DataLoader(valid_dataset, batch_size=batch_size, shuffle=False,
num_workers=dataload_workers_nums)
# aaa = next(iter(train_dataloader))
# now we can define our architecture
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, in_channels=3):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(1, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def resnet34(pretrained=False, **kwargs):
"""Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url('https://download.pytorch.org/models/resnet34-333f7ec4.pth'))
return model
# create model
model = resnet34(num_classes=len(CLASSES), in_channels=1)
device = torch.device("cuda")
# if use_gpu:
# device = torch.device("cuda")
# else:
# device = torch.device("cpu")
# move model to gpu if you use gpu
model = model.to(device)
# model.to(device)
# loss function is normal crossentrophy
criterion = torch.nn.CrossEntropyLoss()
# define optimizer
# adamw seems to be best
learning_rate = 1e-4
weight_decay = 1e-2
# SGD works
# optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=1e-2)
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, weight_decay=1e-2)
# # AdamW is best
# optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
start_timestamp = int(time.time()*1000)
start_epoch = 0
max_epochs = 70
# max_epochs = 18
best_accuracy = 0
best_loss = 1e100
global_step = 0
# probably we don't need schduler for this tutorial
lr_scheduler_patience = 5
lr_scheduler_gamma = 0.1
lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer,
patience=lr_scheduler_patience,
factor=lr_scheduler_gamma)
def get_lr():
return optimizer.param_groups[0]['lr']
full_name = "basic-sgd"
def train(epoch):
global global_step
# print("epoch %3d with lr=%.02e" % (epoch, get_lr()))
phase = 'train'
model.train() # Set model to training mode
running_loss = 0.0
it = 0
correct = 0
total = 0
pbar = tqdm(train_dataloader, unit="audios", unit_scale=train_dataloader.batch_size)
for batch in pbar:
optimizer.zero_grad()
# inputs_x = batch[0]
inputs = batch[0]
targets = batch[1]
# inputs = batch['input']
# inputs = inputs_x['input']
inputs = torch.unsqueeze(inputs, 1)
# targets = batch['target']
inputs = inputs.to(device)
targets = targets.to(device)
# forward/backward
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
# statistics
it += 1
global_step += 1
# running_loss += loss.data[0]
running_loss += loss.item()
pred = outputs.max(1, keepdim=True)[1]
# correct += pred.eq(targets.data.view_as(pred)).sum().item()
correct += pred.eq(targets.view_as(pred)).sum().item()
total += targets.size(0)
# update the progress bar
pbar.set_postfix({
'loss': "%.05f" % (running_loss / it),
'acc': "%.02f%%" % (100*correct/total)
})
accuracy = correct/total
epoch_loss = running_loss / it
print('%s/accuracy' % phase, 100*accuracy, epoch)
print('%s/epoch_loss' % phase, epoch_loss, epoch)
def valid(epoch):
global best_accuracy, best_loss, global_step
phase = 'valid'
model.eval() # Set model to evaluate mode
running_loss = 0.0
it = 0
correct = 0
total = 0
pbar = tqdm(valid_dataloader, unit="audios", unit_scale=valid_dataloader.batch_size)
for batch in pbar:
# inputs_x = batch[0]
inputs = batch[0]
targets = batch[1]
# inputs = batch['input']
# inputs = inputs_x['input']
inputs = torch.unsqueeze(inputs, 1)
# targets = batch['target']
inputs = inputs.to(device)
targets = targets.to(device)
# forward
outputs = model(inputs)
loss = criterion(outputs, targets)
# statistics
it += 1
global_step += 1
running_loss += loss.item()
pred = outputs.data.max(1, keepdim=True)[1]
_correct = pred.eq(targets.view_as(pred)).sum().item()
correct += _correct
total += targets.size(0)
# update the progress bar
pbar.set_postfix({
'loss': "%.05f" % (running_loss / it),
'acc': "%.02f%%" % (100*correct/total)
})
accuracy = correct/total
epoch_loss = running_loss / it
print('%s/accuracy' % phase, 100*accuracy, epoch)
print('%s/epoch_loss' % phase, epoch_loss, epoch)
checkpoint = {
'epoch': epoch,
'step': global_step,
'state_dict': model.state_dict(),
'loss': epoch_loss,
'accuracy': accuracy,
'optimizer' : optimizer.state_dict(),
}
if accuracy > best_accuracy:
best_accuracy = accuracy
torch.save(checkpoint, 'checkpoints/best-loss-speech-commands-checkpoint-%s.pth' % full_name)
torch.save(model, '%d-%s-best-loss.pth' % (start_timestamp, full_name))
if epoch_loss < best_loss:
best_loss = epoch_loss
torch.save(checkpoint, 'checkpoints/best-acc-speech-commands-checkpoint-%s.pth' % full_name)
torch.save(model, '%d-%s-best-acc.pth' % (start_timestamp, full_name))
torch.save(checkpoint, 'checkpoints/last-speech-commands-checkpoint.pth')
del checkpoint # reduce memory
return epoch_loss
start_epoch = 0
if os.path.isdir('./checkpoints') is False:
try:
os.mkdir('./checkpoints')
except OSError:
print ("Creation of the directory %s failed" % path)
since = time.time()
for epoch in range(start_epoch, max_epochs):
train(epoch)
epoch_loss = valid(epoch)
lr_scheduler.step(metrics=epoch_loss)
time_elapsed = time.time() - since
time_str = 'total time elapsed: {:.0f}h {:.0f}m {:.0f}s '.format(time_elapsed // 3600, time_elapsed % 3600 // 60, time_elapsed % 60)
# print("%s, best accuracy: %.02f%%, best loss %f" % (time_str, 100*best_accuracy, best_loss))
print("finished")
len(train_dataset)
raise Exception("stop")
# test
# First, let's see a data sample
import IPython.display
example_path = "./datasets/speech_commands/train/right/9f4098cb_nohash_0.wav"
IPython.display.Audio(example_path)
# load audio
_load_audio = LoadAudio()
_audio_sample = _load_audio(sample_data)
len(_audio_sample["samples"])
_fixAudioLength = FixAudioLength()
_fixed_sample = _fixAudioLength(_audio_sample)
_processed_input = valid_feature_transform(_fixed_sample)
# load saved weights
weight_path2 = "./checkpoints/best-acc-speech-commands-checkpoint-basic1.pth"
# weight_path2 = "./checkpoints/best-acc-speech-commands-checkpoint-speech_command_with_fl.pth"
# weight_path2 = "./checkpoints/last-speech-commands-checkpoint.pth"
state2 = torch.load(
weight_path2,
map_location=torch.device("cpu"))
_ = model2.load_state_dict(state2['state_dict'])
# get prediction
_ = model2.eval()
_eval_output = model2(_processed_input)
_eval_pred = _eval_output.max(1, keepdim=True)[1]
_eval_pred
CLASSES
```
| github_jupyter |
# Overview
This colab demonstrates the steps to use the DeepLab model to perform semantic segmentation on a sample input image. Expected outputs are semantic labels overlayed on the sample image.
### About DeepLab
The models used in this colab perform semantic segmentation. Semantic segmentation models focus on assigning semantic labels, such as sky, person, or car, to multiple objects and stuff in a single image.
# Instructions
<h3><a href="https://cloud.google.com/tpu/"><img valign="middle" src="https://raw.githubusercontent.com/GoogleCloudPlatform/tensorflow-without-a-phd/master/tensorflow-rl-pong/images/tpu-hexagon.png" width="50"></a> Use a free TPU device</h3>
1. On the main menu, click Runtime and select **Change runtime type**. Set "TPU" as the hardware accelerator.
1. Click Runtime again and select **Runtime > Run All**. You can also run the cells manually with Shift-ENTER.
## Import Libraries
```
import os
from io import BytesIO
import tarfile
import tempfile
from six.moves import urllib
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
import tensorflow as tf
```
## Import helper methods
These methods help us perform the following tasks:
* Load the latest version of the pretrained DeepLab model
* Load the colormap from the PASCAL VOC dataset
* Adds colors to various labels, such as "pink" for people, "green" for bicycle and more
* Visualize an image, and add an overlay of colors on various regions
```
class DeepLabModel(object):
"""Class to load deeplab model and run inference."""
INPUT_TENSOR_NAME = 'ImageTensor:0'
OUTPUT_TENSOR_NAME = 'SemanticPredictions:0'
INPUT_SIZE = 513
FROZEN_GRAPH_NAME = 'frozen_inference_graph'
def __init__(self, tarball_path):
"""Creates and loads pretrained deeplab model."""
self.graph = tf.Graph()
graph_def = None
# Extract frozen graph from tar archive.
tar_file = tarfile.open(tarball_path)
for tar_info in tar_file.getmembers():
if self.FROZEN_GRAPH_NAME in os.path.basename(tar_info.name):
file_handle = tar_file.extractfile(tar_info)
graph_def = tf.GraphDef.FromString(file_handle.read())
break
tar_file.close()
if graph_def is None:
raise RuntimeError('Cannot find inference graph in tar archive.')
with self.graph.as_default():
tf.import_graph_def(graph_def, name='')
self.sess = tf.Session(graph=self.graph)
def run(self, image):
"""Runs inference on a single image.
Args:
image: A PIL.Image object, raw input image.
Returns:
resized_image: RGB image resized from original input image.
seg_map: Segmentation map of `resized_image`.
"""
width, height = image.size
resize_ratio = 1.0 * self.INPUT_SIZE / max(width, height)
target_size = (int(resize_ratio * width), int(resize_ratio * height))
resized_image = image.convert('RGB').resize(target_size, Image.ANTIALIAS)
batch_seg_map = self.sess.run(
self.OUTPUT_TENSOR_NAME,
feed_dict={self.INPUT_TENSOR_NAME: [np.asarray(resized_image)]})
seg_map = batch_seg_map[0]
return resized_image, seg_map
def create_pascal_label_colormap():
"""Creates a label colormap used in PASCAL VOC segmentation benchmark.
Returns:
A Colormap for visualizing segmentation results.
"""
colormap = np.zeros((256, 3), dtype=int)
ind = np.arange(256, dtype=int)
for shift in reversed(range(8)):
for channel in range(3):
colormap[:, channel] |= ((ind >> channel) & 1) << shift
ind >>= 3
return colormap
def label_to_color_image(label):
"""Adds color defined by the dataset colormap to the label.
Args:
label: A 2D array with integer type, storing the segmentation label.
Returns:
result: A 2D array with floating type. The element of the array
is the color indexed by the corresponding element in the input label
to the PASCAL color map.
Raises:
ValueError: If label is not of rank 2 or its value is larger than color
map maximum entry.
"""
if label.ndim != 2:
raise ValueError('Expect 2-D input label')
colormap = create_pascal_label_colormap()
if np.max(label) >= len(colormap):
raise ValueError('label value too large.')
return colormap[label]
def vis_segmentation(image, seg_map):
"""Visualizes input image, segmentation map and overlay view."""
plt.figure(figsize=(15, 5))
grid_spec = gridspec.GridSpec(1, 4, width_ratios=[6, 6, 6, 1])
plt.subplot(grid_spec[0])
plt.imshow(image)
plt.axis('off')
plt.title('input image')
plt.subplot(grid_spec[1])
seg_image = label_to_color_image(seg_map).astype(np.uint8)
plt.imshow(seg_image)
plt.axis('off')
plt.title('segmentation map')
plt.subplot(grid_spec[2])
plt.imshow(image)
plt.imshow(seg_image, alpha=0.7)
plt.axis('off')
plt.title('segmentation overlay')
unique_labels = np.unique(seg_map)
ax = plt.subplot(grid_spec[3])
plt.imshow(
FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation='nearest')
ax.yaxis.tick_right()
plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])
plt.xticks([], [])
ax.tick_params(width=0.0)
plt.grid('off')
plt.show()
LABEL_NAMES = np.asarray([
'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',
'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike',
'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tv'
])
FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)
FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)
```
## Select a pretrained model
We have trained the DeepLab model using various backbone networks. Select one from the MODEL_NAME list.
```
MODEL_NAME = 'mobilenetv2_coco_voctrainaug' # @param ['mobilenetv2_coco_voctrainaug', 'mobilenetv2_coco_voctrainval', 'xception_coco_voctrainaug', 'xception_coco_voctrainval']
_DOWNLOAD_URL_PREFIX = 'http://download.tensorflow.org/models/'
_MODEL_URLS = {
'mobilenetv2_coco_voctrainaug':
'deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz',
'mobilenetv2_coco_voctrainval':
'deeplabv3_mnv2_pascal_trainval_2018_01_29.tar.gz',
'xception_coco_voctrainaug':
'deeplabv3_pascal_train_aug_2018_01_04.tar.gz',
'xception_coco_voctrainval':
'deeplabv3_pascal_trainval_2018_01_04.tar.gz',
}
_TARBALL_NAME = 'deeplab_model.tar.gz'
model_dir = tempfile.mkdtemp()
tf.gfile.MakeDirs(model_dir)
download_path = os.path.join(model_dir, _TARBALL_NAME)
print('downloading model, this might take a while...')
urllib.request.urlretrieve(_DOWNLOAD_URL_PREFIX + _MODEL_URLS[MODEL_NAME],
download_path)
print('download completed! loading DeepLab model...')
MODEL = DeepLabModel(download_path)
print('model loaded successfully!')
```
## Run on sample images
Select one of sample images (leave `IMAGE_URL` empty) or feed any internet image
url for inference.
Note that this colab uses single scale inference for fast computation,
so the results may slightly differ from the visualizations in the
[README](https://github.com/tensorflow/models/blob/master/research/deeplab/README.md) file,
which uses multi-scale and left-right flipped inputs.
```
SAMPLE_IMAGE = 'image1' # @param ['image1', 'image2', 'image3']
IMAGE_URL = '' #@param {type:"string"}
_SAMPLE_URL = ('https://github.com/tensorflow/models/blob/master/research/'
'deeplab/g3doc/img/%s.jpg?raw=true')
def run_visualization(url):
"""Inferences DeepLab model and visualizes result."""
try:
f = urllib.request.urlopen(url)
jpeg_str = f.read()
original_im = Image.open(BytesIO(jpeg_str))
except IOError:
print('Cannot retrieve image. Please check url: ' + url)
return
print('running deeplab on image %s...' % url)
resized_im, seg_map = MODEL.run(original_im)
vis_segmentation(resized_im, seg_map)
image_url = IMAGE_URL or _SAMPLE_URL % SAMPLE_IMAGE
run_visualization(image_url)
```
## What's next
* Learn about [Cloud TPUs](https://cloud.google.com/tpu/docs) that Google designed and optimized specifically to speed up and scale up ML workloads for training and inference and to enable ML engineers and researchers to iterate more quickly.
* Explore the range of [Cloud TPU tutorials and Colabs](https://cloud.google.com/tpu/docs/tutorials) to find other examples that can be used when implementing your ML project.
* For more information on running the DeepLab model on Cloud TPUs, see the [DeepLab tutorial](https://cloud.google.com/tpu/docs/tutorials/deeplab).
| github_jupyter |
```
export_folder = "sp2"
filename_prefix = "sp2"
from local_vars import root_folder
import os
export_fullpath = os.path.join(root_folder, export_folder)
if not os.path.exists(export_fullpath):
os.makedirs(export_fullpath)
print("Created folder: " + export_fullpath)
print "Export data to: " + export_fullpath
images_fullpath = os.path.join(export_fullpath, "images")
annotations_fullpath = os.path.join(export_fullpath, "annotations")
if not os.path.exists(images_fullpath):
os.makedirs(images_fullpath)
if not os.path.exists(annotations_fullpath):
os.makedirs(annotations_fullpath)
fiducials_name = "F"
fiducials_node = slicer.util.getFirstNodeByName(fiducials_name, className="vtkMRMLMarkupsFiducialNode")
print "Fiducials node: " + fiducials_node.GetName()
sequence_browser_node = slicer.util.getFirstNodeByName('', className='vtkMRMLSequenceBrowserNode')
print "Sequence browser node: " + str(sequence_browser_node.GetID())
n = sequence_browser_node.GetNumberOfItems()
sequence_browser_node.SelectFirstItem()
print "Number of images: " + str(n)
master_node = sequence_browser_node.GetMasterSequenceNode()
image_node = sequence_browser_node.GetProxyNode(master_node)
image_transform_id = image_node.GetTransformNodeID()
if image_transform_id is None:
print "Probably forgot to transform image node!"
raise ValueError
image_to_reference_node = slicer.util.getNode(image_transform_id)
image_data = image_node.GetImageData()
print "Ultrasound image node: " + image_node.GetName()
print "Transform node ID: " + image_transform_id
def transform_fiducial_array_by_matrix(fiducial_array, transform_matrix):
"""
:param fiducial_array: numpy.array((n,3))
:param transform_matrix: vtk.vtkMatrix4x4
:return: numpy.array((n,3))
"""
n = fiducial_array.shape[0]
transformed_array = np.zeros([n, 3])
for i in range(n):
point_src = np.append(fiducial_array[i], 1)
point_dst = np.array(transform_matrix.MultiplyFloatPoint(point_src))
transformed_array[i][:] = point_dst[:3]
return transformed_array
def find_closest_point(image_extent, fiducials_Image):
"""
:param image_extent: array(4) = [minX, maxX, minY, maxY]
:param fiducials_Image: numpy.array((n,3))
:param min_distance_px: float
:return: (min_index, min_distance_px)
"""
min_index = 0
min_distance_px = float_info.max
n = fiducials_Image.shape[0]
for i in range(n):
x = fiducials_Image[i][0]
y = fiducials_Image[i][1]
z = fiducials_Image[i][2]
# Only work with fiducials within the width and height of the image
if x < image_extent[0] or x > image_extent[1] or y < image_extent[2] or y > image_extent[3]:
continue
if abs(z) < min_distance_px:
min_distance_px = abs(z)
min_index = i
return (min_index, min_distance_px)
minimum_intensity = 40.0
min_distance_mm = 6.0
import numpy as np
import csv
from sys import float_info
png_writer = vtk.vtkPNGWriter()
image_to_reference_matrix = vtk.vtkMatrix4x4()
reference_to_image_matrix = vtk.vtkMatrix4x4()
image_dims = image_data.GetDimensions()
image_extent = image_data.GetExtent()
csv_file_name = filename_prefix + ".csv"
csv_fullname = os.path.join(annotations_fullpath, csv_file_name)
csv_file = open(csv_fullname, 'wb')
csv_writer = csv.writer(csv_file, delimiter=',')
csv_writer.writerow(['filename', 'width', 'height', 'class', 'x', 'y'])
n_fiducials = fiducials_node.GetNumberOfFiducials()
fiducial_labels = [''] * n_fiducials
fiducial_coordinates_Reference = np.zeros([n_fiducials, 3])
n_output = 0
for i in range(n_fiducials):
fiducials_node.GetNthFiducialPosition(i, fiducial_coordinates_Reference[i])
fiducial_labels[i] = fiducials_node.GetNthFiducialLabel(i)
for i in range(n):
image_data = image_node.GetImageData()
image_array = slicer.util.arrayFromVolume(image_node)
avg_intensity = np.average(image_array)
if avg_intensity < minimum_intensity:
print "Skipping image due to low intensity {:.2f}".format(avg_intensity)
continue
img_file_name = filename_prefix + "_%04d_ultrasound" % i + ".png"
img_fullname = os.path.join(images_fullpath, img_file_name)
png_writer.SetInputData(image_data)
png_writer.SetFileName(img_fullname)
png_writer.Update()
png_writer.Write()
image_to_reference_node.GetMatrixTransformToWorld(image_to_reference_matrix)
reference_to_image_matrix.DeepCopy(image_to_reference_matrix)
reference_to_image_matrix.Invert()
image_to_reference_transform = vtk.vtkTransform()
image_to_reference_transform.SetMatrix(image_to_reference_matrix)
pixel_to_mm = image_to_reference_transform.GetScale()[0]
fiducials_Image = transform_fiducial_array_by_matrix(fiducial_coordinates_Reference, reference_to_image_matrix)
(min_index, min_distance_px) = find_closest_point(image_extent, fiducials_Image)
p = fiducials_Image[min_index]
p[1] = image_extent[1] - p[1]
x = p[0] / image_dims[0]
y = p[1] / image_dims[1]
if (min_distance_px * pixel_to_mm) < min_distance_mm:
csv_writer.writerow([img_file_name, str(image_dims[0]), str(image_dims[1]), fiducial_labels[min_index], x, y])
else:
csv_writer.writerow([img_file_name, str(image_dims[0]), str(image_dims[1]), '0', 0, 0])
n_output += 1
try:
sequence_browser_node.SelectNextItem()
except:
print "End of sequence reached"
# slicer.app.processEvents()
csv_file.close()
print "{} image files and annotations written".format(n_output)
```
| github_jupyter |
```
import ete3
import re
import itertools
import multiprocessing
import random
import pandas as pd
import numpy as np
import igraph as ig
import pickle as pkl
from scipy.spatial.distance import squareform, pdist
from scipy.stats import mannwhitneyu
from collections import Counter
ncbi = ete3.NCBITaxa()
%cd /work/eggNOG/
sampled_genomes = pd.read_csv('../kelsey/genomes.tab',
sep='\t',
index_col=0)
lineages = pd.DataFrame()
for taxid in sampled_genomes.species_taxid.unique():
if pd.isna(taxid):
continue
lineages = lineages.append({tax_rank: tmp_taxid
for tmp_taxid, tax_rank in ncbi.get_rank(ncbi.get_lineage(taxid)).items()},
ignore_index=True)
lineages = lineages.reindex(columns=['class', 'family', 'genus', 'phylum',
'order', 'species', 'superkingdom']).copy()
lineages = lineages.query('superkingdom == 2').copy()
working_groups = pd.read_parquet('working_eggNOG_groups.parquet')
working_trees = pd.read_parquet('working_eggNOG_trees.parquet' )
eggNOG_taxonomy = pd.read_parquet('eggNOG_taxonomy.parquet' )
def get_pairwise_distances(group_id):
tree = ete3.Tree(working_trees.loc[group_id, 'tree'])
leaf_names = []
for count, node in enumerate(tree.traverse()):
if node.is_leaf():
leaf_names.append(node.name)
else:
node.name = 'node_%i' % count
leaf_names = np.array(leaf_names)
nodes = []
children = []
branch_length = []
for node in tree.traverse():
if not node.is_leaf():
for child in node.get_children():
nodes.append( node.name)
children.append( child.name)
branch_length.append(child.dist)
branch_length_df = pd.DataFrame()
branch_length_df['node'] = nodes
branch_length_df['child'] = children
branch_length_df['branch_length'] = branch_length
dag = ig.Graph.TupleList(edges=branch_length_df[['node',
'child',
'branch_length']].itertuples(index=False),
directed=False,
weights=True)
dist_matrix = pd.DataFrame(index =leaf_names,
columns=leaf_names,
data =np.array(dag.shortest_paths(source=leaf_names,
target=leaf_names,
weights='weight'))
)
return(dist_matrix)
def create_taxa_graph(dist_matrix, phyla):
triu_indices = np.triu_indices_from(dist_matrix, k=1)
edge_list = pd.DataFrame()
edge_list['phylum1'] = phyla[triu_indices[0]]
edge_list['phylum2'] = phyla[triu_indices[1]]
edge_list['sequence1'] = dist_matrix.index[triu_indices[0]]
edge_list['sequence2'] = dist_matrix.index[triu_indices[1]]
edge_list['distance'] = dist_matrix.values[triu_indices]
edge_list['inverse_dist'] = np.e**np.negative(edge_list.distance)
graph = ig.Graph.TupleList(edges=edge_list[['sequence1',
'sequence2',
'inverse_dist']].itertuples(index=False),
directed=False,
weights =True)
return(edge_list, graph)
def cles(lessers, greaters):
#
# https://github.com/ajschumacher/cles/blob/master/cles.py
#
"""Common-Language Effect Size
Probability that a random draw from `greater` is in fact greater
than a random draw from `lesser`.
Args:
lesser, greater: Iterables of comparables.
"""
if len(lessers) == 0 and len(greaters) == 0:
raise ValueError('At least one argument must be non-empty')
# These values are a bit arbitrary, but make some sense.
# (It might be appropriate to warn for these cases.)
if len(lessers) == 0:
return 1
if len(greaters) == 0:
return 0
numerator = 0
lessers, greaters = sorted(lessers), sorted(greaters)
lesser_index = 0
for greater in greaters:
while lesser_index < len(lessers) and lessers[lesser_index] < greater:
lesser_index += 1
numerator += lesser_index # the count less than the greater
denominator = len(lessers) * len(greaters)
return float(numerator) / denominator
def assess_cluster(reference_phylum, minimal_freq_phyla, cluster_edges, cluster_nodes):
#
# store distances between reference phylum and others
cluster_dists = pd.DataFrame(columns=['phylum', 'median', 'distances'])
#
# traverse all phylum pairs containing the reference phylum
for phylum in minimal_freq_phyla:
if phylum == reference_phylum:
continue
inter_phyla = cluster_edges.loc[((cluster_edges.phylum1==reference_phylum) & (cluster_edges.phylum2==phylum)) |\
((cluster_edges.phylum2==reference_phylum) & (cluster_edges.phylum1==phylum))]
#
# create a quadratic matrix of pairwise distances between phyla
# rows and columns must be unique pairs of sequence names
indices = np.unique(inter_phyla[['sequence1', 'sequence2']])
adjacencies = pd.DataFrame(index =indices,
columns=indices,
data =0.0)
#
# add distances between sequences from the edge list to the quadratic matrix
# as the matrix is quadratic, add values to both directions
indexer = adjacencies.index.get_indexer
adjacencies.values[indexer(inter_phyla.sequence1), indexer(inter_phyla.sequence2)] = inter_phyla.distance.values
adjacencies.values[indexer(inter_phyla.sequence2), indexer(inter_phyla.sequence1)] = inter_phyla.distance.values
#
# sum the obtained distances into a single cell
tmp_closest_to_phylum = adjacencies.loc[cluster_nodes.loc[cluster_nodes.phylum==reference_phylum, 'name'],
cluster_nodes.loc[cluster_nodes.phylum==phylum, 'name']].sum()
tmp_closest_to_phylum.sort_values(inplace=True)
#
# and grab the five sequences from <phylum> closest to all from <reference phylum>
tmp_closest_to_phylum = tmp_closest_to_phylum.index[:5]
try:
#
# get all inter-phyla distances between
distances_to_reference_phylum = adjacencies.loc[
#
# all sequences from <reference phylum>
cluster_nodes.loc[cluster_nodes.phylum==reference_phylum, 'name'],
#
# the 5 sequences from <phylum> closest to <reference phylum>
tmp_closest_to_phylum
].values.flatten()
except IndexError:
continue
cluster_dists = cluster_dists.append(pd.Series(data =[phylum,
np.median(distances_to_reference_phylum),
distances_to_reference_phylum],
index=['phylum', 'median', 'distances']),
ignore_index=True)
return(cluster_dists)
def get_phyla_evol_distances(group_id):
dist_matrix = get_pairwise_distances(group_id)
taxids = [int(leaf.split('.')[0]) for leaf in dist_matrix.index]
phyla = eggNOG_taxonomy.loc[taxids, 'phylum'].values.astype(int)
edge_list, graph = create_taxa_graph(dist_matrix, phyla)
random.seed(12345)
clusters = graph.community_multilevel(weights='weight')
node_data = pd.DataFrame(columns=['name', 'phylum', 'cluster'],
data =zip(dist_matrix.index,
phyla,
clusters.membership)
)
cluster_evol_relations = {}
target_phyla = {1090, # chlorobi
1117, # cyanobacteria
1224, # proteobacteria
200795, # chloroflexi
976, # bacteroidetes
1134404, # ignavibacteriae
1798710} # melainabacteria
for cluster_num in set(clusters.membership):
cluster_nodes = node_data[node_data.cluster==cluster_num]
minimal_freq_phyla = [phylum
for phylum, frequency in Counter(cluster_nodes.phylum).items()
if frequency>=5 # at least five sequences from a phylum
and phylum > 0] # given pandas manipulation, unknown phyla are represented
# as NAN, which when forced to be int are negative numbers
# that is why we ignore phylum taxids smaller than zero...
#
# if there are fewer than two phyla of interested within the tree cluster there is no reason to
# assess it...
if len( target_phyla.intersection( minimal_freq_phyla ) ) < 2:
continue
cluster_evol_relations[cluster_num] = {}
#
# filter patristic distances from the whole tree to only those between sequences within the cluster
cluster_edges = edge_list.loc[(edge_list.sequence1.isin(cluster_nodes.name)) &
(edge_list.sequence2.isin(cluster_nodes.name)),
['phylum1', 'phylum2', 'sequence1', 'sequence2', 'distance']]
#
# filter again, leaving only between sequences whose phylum fulfills the minimal frequency
cluster_edges = cluster_edges[(cluster_edges.phylum1.isin(minimal_freq_phyla)) &\
(cluster_edges.phylum2.isin(minimal_freq_phyla))]
#
# we will divide all pairwise distances by the cluster's mean
normalizer = np.median(cluster_edges.distance)
#
# remove all intra-phylum distances
cluster_edges = cluster_edges[cluster_edges.phylum1 != cluster_edges.phylum2]
#
# assess all inter-phyla distances, using each phylum as a reference to itself
#
for ref_phylum in target_phyla.intersection(minimal_freq_phyla):
cluster_dists = assess_cluster(ref_phylum,
minimal_freq_phyla,
cluster_edges,
cluster_nodes)
#
# sort phyla by its avg. distance to <reference phylum>
cluster_dists.sort_values('median', inplace=True)
cluster_evol_relations[cluster_num][ref_phylum] = {
'df' :cluster_dists[['phylum', 'median']].copy(),
'significant':False
}
if not cluster_dists.shape[0]:
continue
cluster_evol_relations[cluster_num][ref_phylum]['df']['median'] /= normalizer
#
# if there is only one <phylum> together with <reference phylum>, the proximity between
# both is automaticaly significant
if cluster_dists.shape[0] == 1:
cluster_evol_relations[cluster_num][ref_phylum]['significant'] = True
continue
try:
#
# test if distances from the closest phylum to <reference phylum> is significantly
# smaller than distances from the second closest phylum
hypothesis = mannwhitneyu(cluster_dists.iloc[0, 2],
cluster_dists.iloc[1, 2],
alternative='less')
except ValueError:
continue
else:
#
# both cles lines below should work identically... I am leaving the above because it is the one I
# used in the paper, no real reason...
effect_size = hypothesis.statistic / (len(cluster_dists.iloc[0, 2])*len(cluster_dists.iloc[1, 2]))
# effect_size = 1-cles(cluster_dists.iloc[0, 2], cluster_dists.iloc[1, 2])
if hypothesis.pvalue < 0.01 and effect_size < 0.2:
cluster_evol_relations[cluster_num][ref_phylum]['significant'] = True
return(group_id, cluster_evol_relations)
# %%time
# get_phyla_evol_distances('COG0499')
%%time
pool = multiprocessing.Pool(processes=10, maxtasksperchild=5)
results = pool.map_async(get_phyla_evol_distances, working_groups.group_id.values)
pool.close()
pool.join()
with open('all_results.pkl', 'wb') as out:
pkl.dump(results.get(), out)
del(results)
```
| github_jupyter |
```
%matplotlib inline
import plot_helpers as ph
from matplotlib import pyplot as plt
fairgp_files_race = [
('../results/ICML/propublica/gpyt500_eqopp_tuning_race.csv', ''),
]
def label_change(label):
parts = label.split('_')
#mode = parts[-1]
in_True = parts[4] == "True"
tnr = parts[6]
if not in_True and tnr != "0.74":
return
if in_True and tnr != "0.71":
return
optional_star = "*" if in_True else ""
with_s = ", use $s$" if in_True else ""
#return f"FairGPparity{optional_star}", in_True
#return "average" if mode == "True" else mode, True
num = label.split('_')[-1]
return f"$TPR_t={num}${with_s}", not in_True
fairgp_race = ph.parse_all(fairgp_files_race, label_change)
fairgp_files_sex = [
('../results/ICML/propublica/gpyt500_eqopp_tuning_sex.csv', ''),
]
def label_change(label):
parts = label.split('_')
#mode = parts[-1]
in_True = parts[4] == "True"
tnr = parts[6]
if not in_True and tnr != "0.77":
return
if in_True and tnr != "0.72":
return
optional_star = "*" if in_True else ""
with_s = ", use $s$" if in_True else ""
#return f"FairGPparity{optional_star}", in_True
#return "average" if mode == "True" else mode, True
num = label.split('_')[-1]
return f"$TPR_t={num}${with_s}", not in_True
fairgp_sex = ph.parse_all(fairgp_files_sex, label_change)
fairgp = fairgp_race + fairgp_sex
fairgp = ph.choose_entries(fairgp, [0, 5, 1, 6, 2, 7, 3, 8, 4, 9])
#baselines = ph.choose_entries(baselines, [1, 0])
def tpr0_vs_tpr1(plot, legend, sens, swap_axes, *data):
ms = 4
xaxis = (f'0-TPR-{sens}', '$TPR_{s=0}$')
yaxis = (f'1-TPR-{sens}', '$TPR_{s=1}$')
if swap_axes:
temp = xaxis
xaxis = yaxis
yaxis = temp
legends = []
startindex = 0
plot.plot([0.0, 1.0], [0.0, 1.0], 'k--', label="perfect fairness" if legend is not None else None)
for data_structure in data:
legends += [ph.scatter(plot, data_structure, xaxis, yaxis, legend=legend, startindex=startindex, markersize=ms)]
startindex += len(data_structure.entries) // 2
if legend is not None:
return legends
def tpr_vs_tnr(plot, do_legend, *data):
ms = 4
xaxis = ('TPR', 'TPR')
yaxis = ('TNR', 'TNR')
legends = []
startindex = 0
legend = "outside" if do_legend else None
for data_structure in data:
legends += [ph.scatter(plot, data_structure, xaxis, yaxis, legend=legend, startindex=startindex, markersize=ms)]
startindex += len(data_structure.entries) // 2
if do_legend:
return legends
fig, plots = plt.subplots(ncols=4, figsize=(12, 2.2))
tpr_vs_tnr(plots[0], False, fairgp[0])
plots[0].set_title('(a) sensitive: race', loc='left')
tpr_vs_tnr(plots[1], False, fairgp[1])
plots[1].set_title('(b) sensitive: gender', loc='left')
tpr0_vs_tpr1(plots[2], None, 'race', True, fairgp[0])
plots[2].set_title('(c) sensitive: race', loc='left')
plots[2].set_ylim(0.5, 0.95)
plots[2].set_xlim(0.35, 0.9)
legends = tpr0_vs_tpr1(plots[3], ("outside", 1.1), 'sex', False, fairgp[1])
plots[3].set_title('(d) sensitive: gender', loc='left')
plots[3].set_ylim(0.5, 0.9)
plots[3].set_xlim(0.35, 0.85)
fig.tight_layout()
fig.subplots_adjust(bottom=0, wspace=0.3)
fig.savefig("/Users/tk324/dev/latex/Tunable_Fairness_ICML/figures/propublica_opp_scatter.pdf",
bbox_extra_artists=legends, bbox_inches='tight', pad_inches=0)
fig
```
| github_jupyter |
## Enviroment:
Open AI gym [CartPole v0](https://github.com/openai/gym/wiki/CartPole-v0)
### Observation
Type: Box(4)
| Num | Observation | Min | Max |
| ---- | -------------------- | -------- | ------- |
| 0 | Cart Position | -2.4 | 2.4 |
| 1 | Cart Velocity | -Inf | Inf |
| 2 | Pole Angle | ~ -41.8° | ~ 41.8° |
| 3 | Pole Velocity At Tip | -Inf | Inf |
### Actions
Type: Discrete(2)
| Num | Action |
| ---- | ---------------------- |
| 0 | Push cart to the left |
| 1 | Push cart to the right |
Note: The amount the velocity is reduced or increased is not fixed as it depends on the angle the pole is pointing. This is because the center of gravity of the pole increases the amount of energy needed to move the cart underneath it
### Reward
Reward is 1 for every step taken, including the termination step
### Starting State
All observations are assigned a uniform random value between ±0.05
### Episode Termination
1. Pole Angle is more than ±12°
2. Cart Position is more than ±2.4 (center of the cart reaches the edge of the display)
3. Episode length is greater than 200
### Solved Requirements
Considered solved when the average reward is greater than or equal to 195.0 over 100 consecutive trials
## 1. gym enviroment setup
```
import gym
import numpy as np
import matplotlib.pyplot as plt
env = gym.make("CartPole-v0")
env.reset()
```
## 2. Q Table setup
```
LEARNING_RATE = 0.5
DISCOUNT = 0.95
EPISODES = 50000
SHOW_EVERY = 1000
Q_TABLE_LEN = 150
def sigmoid(x):
return 1 / (1 + np.exp(-x))
DISCRETE_OS_SIZE = [Q_TABLE_LEN] * (len(env.observation_space.high))
observation_high = np.array([env.observation_space.high[0],
Q_TABLE_LEN*sigmoid(env.observation_space.high[1]),
env.observation_space.high[2],
Q_TABLE_LEN*sigmoid(env.observation_space.high[3])])
observation_low = np.array([env.observation_space.low[0],
Q_TABLE_LEN*sigmoid(env.observation_space.low[1]),
env.observation_space.low[2],
Q_TABLE_LEN*sigmoid(env.observation_space.low[3])])
discrete_os_win_size = (observation_high - observation_low) / DISCRETE_OS_SIZE
# q_table = np.random.uniform(low=0, high=1,
# size=(DISCRETE_OS_SIZE + [env.action_space.n]))
q_table = np.zeros((DISCRETE_OS_SIZE + [env.action_space.n]))
q_table.shape
```
### Decay epsilon
```
epsilon = 1 # not a constant, qoing to be decayed
START_EPSILON_DECAYING = 1
END_EPSILON_DECAYING = EPISODES//2
epsilon_decay_value = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING)
```
## 3. Help functions
```
def get_discrete_state (state):
discrete_state = (state - observation_low) // discrete_os_win_size
return tuple(discrete_state.astype(int))
def take_epilon_greedy_action(state, epsilon):
discrete_state = get_discrete_state(state)
if np.random.random() < epsilon:
action = np.random.randint(0,env.action_space.n)
else:
action = np.argmax(q_table[discrete_state])
return action
```
## 4. Rewards Recorder setup
```
ep_rewards = []
aggr_ep_rewards = {'ep':[],'avg':[],'min':[],'max':[]}
```
## 5. Train the Agent
```
for episode in range(EPISODES):
# initiate reward every episode
ep_reward = 0
if episode % SHOW_EVERY == 0:
print("episode: {}".format(episode))
render = True
else:
render = False
state = env.reset()
done = False
while not done:
action = take_epilon_greedy_action(state, epsilon)
next_state, reward, done, _ = env.step(action)
ep_reward += reward
# if render:
# env.render()
if not done:
td_target = reward + DISCOUNT * np.max(q_table[get_discrete_state(next_state)])
q_table[get_discrete_state(state)][action] += LEARNING_RATE * (td_target - q_table[get_discrete_state(state)][action])
state = next_state
# Decaying is being done every episode if episode number is within decaying range
if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING:
epsilon -= epsilon_decay_value
# recoard aggrated rewards on each epsoide
ep_rewards.append(ep_reward)
# every SHOW_EVERY calculate average rewords
if episode % SHOW_EVERY == 0:
avg_reward = sum(ep_rewards[-SHOW_EVERY:]) / len(ep_rewards[-SHOW_EVERY:])
aggr_ep_rewards['ep'].append(episode)
aggr_ep_rewards['avg'].append(avg_reward)
aggr_ep_rewards['min'].append(min(ep_rewards[-SHOW_EVERY:]))
aggr_ep_rewards['max'].append(max(ep_rewards[-SHOW_EVERY:]))
plt.plot(aggr_ep_rewards['ep'], aggr_ep_rewards['avg'], label = 'avg')
plt.plot(aggr_ep_rewards['ep'], aggr_ep_rewards['min'], label = 'min')
plt.plot(aggr_ep_rewards['ep'], aggr_ep_rewards['max'], label = 'max')
plt.legend(loc='upper left')
plt.xlabel('Episodes')
plt.ylabel('Rewards')
```
### 6. Rendering Test
```
done = False
state = env.reset()
while not done:
action = np.argmax(q_table[get_discrete_state(state)])
next_state, _, done, _ = env.step(action)
state = next_state
env.render()
env.close()
```
| github_jupyter |
# Evaluation of a QA System
[](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial5_Evaluation.ipynb)
To be able to make a statement about the performance of a question-answering system, it is important to evalute it. Furthermore, evaluation allows to determine which parts of the system can be improved.
### Prepare environment
#### Colab: Enable the GPU runtime
Make sure you enable the GPU runtime to experience decent speed in this tutorial.
**Runtime -> Change Runtime type -> Hardware accelerator -> GPU**
<img src="https://raw.githubusercontent.com/deepset-ai/haystack/master/docs/_src/img/colab_gpu_runtime.jpg">
```
# Make sure you have a GPU running
!nvidia-smi
```
## Start an Elasticsearch server
You can start Elasticsearch on your local machine instance using Docker. If Docker is not readily available in your environment (eg., in Colab notebooks), then you can manually download and execute Elasticsearch from source.
```
# Install the latest release of Haystack in your own environment
#! pip install farm-haystack
# Install the latest master of Haystack
!pip install git+https://github.com/deepset-ai/haystack.git
!pip install urllib3==1.25.4
!pip install torch==1.6.0+cu101 torchvision==0.6.1+cu101 -f https://download.pytorch.org/whl/torch_stable.html
# In Colab / No Docker environments: Start Elasticsearch from source
! wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.2-linux-x86_64.tar.gz -q
! tar -xzf elasticsearch-7.9.2-linux-x86_64.tar.gz
! chown -R daemon:daemon elasticsearch-7.9.2
import os
from subprocess import Popen, PIPE, STDOUT
es_server = Popen(['elasticsearch-7.9.2/bin/elasticsearch'],
stdout=PIPE, stderr=STDOUT,
preexec_fn=lambda: os.setuid(1) # as daemon
)
# wait until ES has started
! sleep 30
from farm.utils import initialize_device_settings
device, n_gpu = initialize_device_settings(use_cuda=True)
from haystack.preprocessor.utils import fetch_archive_from_http
# Download evaluation data, which is a subset of Natural Questions development set containing 50 documents
doc_dir = "../data/nq"
s3_url = "https://s3.eu-central-1.amazonaws.com/deepset.ai-farm-qa/datasets/nq_dev_subset_v2.json.zip"
fetch_archive_from_http(url=s3_url, output_dir=doc_dir)
# make sure these indices do not collide with existing ones, the indices will be wiped clean before data is inserted
doc_index = "tutorial5_docs"
label_index = "tutorial5_labels"
# Connect to Elasticsearch
from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
# Connect to Elasticsearch
document_store = ElasticsearchDocumentStore(host="localhost", username="", password="", index="document",
create_index=False, embedding_field="emb",
embedding_dim=768, excluded_meta_data=["emb"])
# Add evaluation data to Elasticsearch Document Store
# We first delete the custom tutorial indices to not have duplicate elements
document_store.delete_all_documents(index=doc_index)
document_store.delete_all_documents(index=label_index)
document_store.add_eval_data(filename="../data/nq/nq_dev_subset_v2.json", doc_index=doc_index, label_index=label_index)
```
## Initialize components of QA-System
```
# Initialize Retriever
from haystack.retriever.sparse import ElasticsearchRetriever
retriever = ElasticsearchRetriever(document_store=document_store)
# Alternative: Evaluate DensePassageRetriever
# Note, that DPR works best when you index short passages < 512 tokens as only those tokens will be used for the embedding.
# Here, for nq_dev_subset_v2.json we have avg. num of tokens = 5220(!).
# DPR still outperforms Elastic's BM25 by a small margin here.
# from haystack.retriever.dense import DensePassageRetriever
# retriever = DensePassageRetriever(document_store=document_store,
# query_embedding_model="facebook/dpr-question_encoder-single-nq-base",
# passage_embedding_model="facebook/dpr-ctx_encoder-single-nq-base",
# use_gpu=True,
# embed_title=True,
# max_seq_len=256,
# batch_size=16,
# remove_sep_tok_from_untitled_passages=True)
#document_store.update_embeddings(retriever, index=doc_index)
# Initialize Reader
from haystack.reader.farm import FARMReader
reader = FARMReader("deepset/roberta-base-squad2", top_k_per_candidate=4)
# Initialize Finder which sticks together Reader and Retriever
from haystack.finder import Finder
finder = Finder(reader, retriever)
```
## Evaluation of Retriever
```
## Evaluate Retriever on its own
retriever_eval_results = retriever.eval(top_k=20, label_index=label_index, doc_index=doc_index)
## Retriever Recall is the proportion of questions for which the correct document containing the answer is
## among the correct documents
print("Retriever Recall:", retriever_eval_results["recall"])
## Retriever Mean Avg Precision rewards retrievers that give relevant documents a higher rank
print("Retriever Mean Avg Precision:", retriever_eval_results["map"])
```
## Evaluation of Reader
```
# Evaluate Reader on its own
reader_eval_results = reader.eval(document_store=document_store, device=device, label_index=label_index, doc_index=doc_index)
# Evaluation of Reader can also be done directly on a SQuAD-formatted file without passing the data to Elasticsearch
#reader_eval_results = reader.eval_on_file("../data/nq", "nq_dev_subset_v2.json", device=device)
## Reader Top-N-Accuracy is the proportion of predicted answers that match with their corresponding correct answer
print("Reader Top-N-Accuracy:", reader_eval_results["top_n_accuracy"])
## Reader Exact Match is the proportion of questions where the predicted answer is exactly the same as the correct answer
print("Reader Exact Match:", reader_eval_results["EM"])
## Reader F1-Score is the average overlap between the predicted answers and the correct answers
print("Reader F1-Score:", reader_eval_results["f1"])
```
## Evaluation of Finder
```
# Evaluate combination of Reader and Retriever through Finder
# Evaluate combination of Reader and Retriever through Finder
finder_eval_results = finder.eval(top_k_retriever=1, top_k_reader=10, label_index=label_index, doc_index=doc_index)
finder.print_eval_results(finder_eval_results)
```
| github_jupyter |
# <center>Regression Models - The why and the how </center>
**Notebook Outline:**
**Regression Models**
- [Introduction](#Introduction)
- [Hedonic House Price Models](#Hedonic-House-Price-Models)
- [Spatial Dependency and Heterogeneity](#Spatial-Dependency-and-Heterogeneity) <br><br>
[Back to the main page](https://mehak-sachdeva.github.io/MGWR_workshop_book/)
# Introduction
***
Models often used to estimate relationships between processes and how they affect the spatial data we observe in the world are broadly classified under the umbrella of **regression**.
Let's jump right into the problem we are going to work on in this workshop and understand the concepts of regression while working through it.
# Hedonic House Price Models
***
Since the value of the attributes of a housing unit cannot be directly measured, a method called the hedonic modeling is applied to a housing unit price such that it could be decomposed into estimated prices for various characteristics - structural, neighborhood and locational. A typical house price model can be written as:
<img src = "../images/traditional_hedonic_model.PNG">
The *Xs* are the **independent variables** that affect the dependent variable *y* or **observed patterns** with the magnitude and direction modeled by the *Betas* which are the measure of **processes** affecting the dependent variable. These are the coefficient estimates that define how much and in what direction these processes affect the pattern.
For example, in the equation above if the beta assumes a value of + 5, this would be interpreted as the change in house price expected with an increase of living area by one unit. Consquently, if we have house price data for a city, we can easily understand how increase in living area and other such attributes of a housing unit would affect house prices in the region.
**However, can you see the obvious limitation in using this equation for the data of an entire city?**
# Spatial Dependency and Heterogeneity
***
In the equation above, the betas or the measure of processes affecting the patterns are averages across the entire study area!
This would suggest that an increase in living area of a housing unit would affect the house price of the unit by the exact same amount no matter where the unit is located in the city. Is that a fair assumption?
**For instance, would you expect the size of a housing unit to have the same marginal cost in Manhattan as compared to that in Staten Island?**
<img src = "../images/global_regression_estimate.PNG">
***
#### **Perhaps, not.**
Spatial phenomenon exhibit spatial heterogeneity that is, we expect values to be higher in some places and lower in others. In the context of house prices in a city for example, housing units with the same structural characteristics are valued differently in different areas of a city. This would then imply that the same stimulus across a city such as an increase in living area of a housing unit, would affect the housing cost differently in different areas. For example, a more accurate map of the marginal cost of living area in New York City would be as below - where adding a unit square feet of space in downtown Manhattan would increase the housing price by a lot more than that in Staten Island.
<img src = "../images/local_regression_results.PNG">
***
*Please note, the mapped estimates below are only representational.*
| github_jupyter |
## Setup Data Fetching
```
import ta
import pandas as pd
import tensortrade.env.default as default
from tensortrade.data.cdd import CryptoDataDownload
from tensortrade.feed.core import Stream, DataFeed, NameSpace
from tensortrade.oms.instruments import USD, BTC, ETH, LTC
from tensortrade.oms.wallets import Wallet, Portfolio
from tensortrade.oms.exchanges import Exchange
from tensortrade.oms.services.execution.simulated import execute_order
```
## Fetch Historical Data
```
cdd = CryptoDataDownload()
bitfinex_data = pd.concat([
cdd.fetch("Bitfinex", "USD", "BTC", "1h").add_prefix("BTC:"),
cdd.fetch("Bitfinex", "USD", "ETH", "1h").add_prefix("ETH:")
], axis=1)
bitstamp_data = pd.concat([
cdd.fetch("Bitstamp", "USD", "BTC", "1h").add_prefix("BTC:"),
cdd.fetch("Bitstamp", "USD", "LTC", "1h").add_prefix("LTC:")
], axis=1)
bitfinex_data.head()
bitstamp_data.head()
```
## Define Exchanges
An exchange needs a name, an execution service, and streams of price data in order to function properly.
The setups supported right now are the simulated execution service using simulated or stochastic data. More execution services will be made available in the future, as well as price streams so that live data and execution can be supported.
```
bitfinex = Exchange("bitfinex", service=execute_order)(
Stream.source(list(bitfinex_data['BTC:close']), dtype="float").rename("USD-BTC"),
Stream.source(list(bitfinex_data['ETH:close']), dtype="float").rename("USD-ETH")
)
bitstamp = Exchange("bitstamp", service=execute_order)(
Stream.source(list(bitstamp_data['BTC:close']), dtype="float").rename("USD-BTC"),
Stream.source(list(bitstamp_data['LTC:close']), dtype="float").rename("USD-LTC")
)
```
Now that the exchanges have been defined we can define our features that we would like to include, excluding the prices we have provided for the exchanges.
## Define External Data Feed
Here we will define the feed to use whatever data you would like. From financial indicators to alternative datasets, they will all have to be defined and incorporated into the `DataFeed` provided to the environment.
```
# Add all features for bitstamp BTC & ETH
bitfinex_btc = bitfinex_data.loc[:, [name.startswith("BTC") for name in bitfinex_data.columns]]
bitfinex_eth = bitfinex_data.loc[:, [name.startswith("ETH") for name in bitfinex_data.columns]]
ta.add_all_ta_features(
bitfinex_btc,
colprefix="BTC:",
**{k: "BTC:" + k for k in ['open', 'high', 'low', 'close', 'volume']}
)
with NameSpace("bitfinex"):
bitfinex_streams = [
Stream.source(list(bitfinex_btc[c]), dtype="float").rename(c) for c in bitfinex_btc.columns
]
bitfinex_streams += [
Stream.source(list(bitfinex_eth[c]), dtype="float").rename(c) for c in bitfinex_eth.columns
]
# Add all features for bitstamp BTC & LTC
bitstamp_btc = bitstamp_data.loc[:, [name.startswith("BTC") for name in bitstamp_data.columns]]
bitstamp_ltc = bitstamp_data.loc[:, [name.startswith("LTC") for name in bitstamp_data.columns]]
ta.add_all_ta_features(
bitstamp_ltc,
colprefix="LTC:",
**{k: "LTC:" + k for k in ['open', 'high', 'low', 'close', 'volume']}
)
with NameSpace("bitstamp"):
bitstamp_streams = [
Stream.source(list(bitstamp_btc[c]), dtype="float").rename(c) for c in bitstamp_btc.columns
]
bitstamp_streams += [
Stream.source(list(bitstamp_ltc[c]), dtype="float").rename(c) for c in bitstamp_ltc.columns
]
feed = DataFeed(bitfinex_streams + bitstamp_streams)
feed.next()
```
## Portfolio
Make the portfolio using the any combinations of exchanges and intruments that the exchange supports
```
portfolio = Portfolio(USD, [
Wallet(bitfinex, 10000 * USD),
Wallet(bitfinex, 10 * BTC),
Wallet(bitfinex, 5 * ETH),
Wallet(bitstamp, 1000 * USD),
Wallet(bitstamp, 5 * BTC),
Wallet(bitstamp, 3 * LTC),
])
```
## Environment
```
env = default.create(
portfolio=portfolio,
action_scheme="managed-risk",
reward_scheme="simple",
feed=feed,
window_size=15,
enable_logger=False
)
env.observer.feed.next()
```
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License");
```
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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.
```
# TensorFlow Distributions: A Gentle Introduction
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/TensorFlow_Distributions_Tutorial.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/TensorFlow_Distributions_Tutorial.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
In this notebook, we'll explore TensorFlow Distributions (TFD for short). The goal of this notebook is to get you gently up the learning curve, including understanding TFD's handling of tensor shapes. This notebook tries to present examples before rather than abstract concepts. We'll present canonical easy ways to do things first, and save the most general abstract view until the end. If you're the type who prefers a more abstract and reference-style tutorial, check out [Understanding TensorFlow Distributions Shapes](https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Understanding_TensorFlow_Distributions_Shapes.ipynb). If you have any questions about the material here, don't hesitate to contact (or join) [the TensorFlow Probability mailing list](https://groups.google.com/a/tensorflow.org/forum/#!forum/tfprobability). We're happy to help.
Before we start, we need to import the appropriate libraries. Our overall library is `tensorflow_probability`. By convention, we generally refer to the distributions library as `tfd`.
[Tensorflow Eager](https://www.tensorflow.org/guide/eager) is an imperative execution environment for TensorFlow. In TensorFlow eager, every TF operation is immediately evaluated and produces a result. This is in contrast to TensorFlow's standard "graph" mode, in which TF operations add nodes to a graph which is later executed. This entire notebook is written using TF Eager, although none of the concepts presented here rely on that, and TFP can be used in graph mode.
```
!pip install -q tensorflow-probability
import collections
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfe = tf.contrib.eager
try:
tfe.enable_eager_execution()
except ValueError:
pass
import matplotlib.pyplot as plt
from __future__ import print_function
```
## Basic Univariate Distributions
Let's dive right in and create a normal distribution:
```
n = tfd.Normal(loc=0., scale=1.)
n
```
We can draw a sample from it:
```
n.sample()
```
We can draw multiple samples:
```
n.sample(3)
```
We can evaluate a log prob:
```
n.log_prob(0.)
```
We can evaluate multiple log probabilities:
```
n.log_prob([0., 2., 4.])
```
We have a wide range of distributions. Let's try a Bernoulli:
```
b = tfd.Bernoulli(probs=0.7)
b
b.sample()
b.sample(8)
b.log_prob(1)
b.log_prob([1, 0, 1, 0])
```
## Multivariate Distributions
We'll create a multivariate normal with a diagonal covariance:
```
nd = tfd.MultivariateNormalDiag(loc=[0., 10.], scale_diag=[1., 4.])
nd
```
Comparing this to the univariate normal we created earlier, what's different?
```
tfd.Normal(loc=0., scale=1.)
```
We see that the univariate normal has an `event_shape` of `()`, indicating it's a scalar distribution. The multivariate normal has an `event_shape` of `2`, indicating the basic [event space](https://en.wikipedia.org/wiki/Event_(probability_theory)) of this distribution is two-dimensional.
Sampling works just as before:
```
nd.sample()
nd.sample(5)
nd.log_prob([0., 10])
```
Multivariate normals do not in general have diagonal covariance. TFD offers multiple ways to create multivariate normals, including a full-covariance specification, which we use here.
```
nd = tfd.MultivariateNormalFullCovariance(
loc = [0., 5], covariance_matrix = [[1., .7], [.7, 1.]])
data = nd.sample(200)
plt.scatter(data[:, 0], data[:, 1], color='blue', alpha=0.4)
plt.axis([-5, 5, 0, 10])
plt.title("Data set")
plt.show()
```
## Multiple Distributions
Our first Bernoulli distribution represented a flip of a single fair coin. We can also create a batch of independent Bernoulli distributions, each with their own parameters, in a single `Distribution` object:
```
b3 = tfd.Bernoulli(probs=[.3, .5, .7])
b3
```
It's important to be clear on what this means. The above call defines three independent Bernoulli distributions, which happen to be contained in the same Python `Distribution` object. The three distributions cannot be manipulated individually. Note how the `batch_shape` is `(3,)`, indicating a batch of three distributions, and the `event_shape` is `()`, indicating the individual distributions have a univariate event space.
If we call `sample`, we get a sample from all three:
```
b3.sample()
b3.sample(6)
```
If we call `prob`, (this has the same shape semantics as `log_prob`; we use `prob` with these small Bernoulli examples for clarity, although `log_prob` is usually preferred in applications) we can pass it a vector and evaluate the probability of each coin yielding that value:
```
b3.prob([1, 1, 0])
```
Why does the API include batch shape? Semantically, one could perform the same computations by creating a list of distributions and iterating over them with a `for` loop (at least in Eager mode, in TF graph mode you'd need a `tf.while` loop). However, having a (potentially large) set of identically parameterized distributions is extremely common, and the use of vectorized computations whenever possible is a key ingredient in being able to perform fast computations using hardware accelerators.
## Using Independent To Aggregate Batches to Events
In the previous section, we created `b3`, a single `Distribution` object that represented three coin flips. If we called `b3.prob` on a vector $v$, the $i$'th entry was the probability that the $i$th coin takes value $v[i]$.
Suppose we'd instead like to specify a "joint" distribution over independent random variables from the same underlying family. This is a different object mathematically, in that for this new distribution, `prob` on a vector $v$ will return a single value representing the probability that the entire set of coins matches the vector $v$.
How do we accomplish this? We use a "higher-order" distribution called `Independent`, which takes a distribution and yields a new distribution with the batch shape moved to the event shape:
```
b3_joint = tfd.Independent(b3, reinterpreted_batch_ndims=1)
b3_joint
```
Compare the shape to that of the original `b3`:
```
b3
```
As promised, we see that that `Independent` has moved the batch shape into the event shape: `b3_joint` is a single distribution (`batch_shape = ()`) over a three-dimensional event space (`event_shape = (3,)`).
Let's check the semantics:
```
b3_joint.prob([1, 1, 0])
```
An alternate way to get the same result would be to compute probabilities using `b3` and do the reduction manually by multiplying (or, in the more usual case where log probabilities are used, summing):
```
tf.reduce_prod(b3.prob([1, 1, 0]))
```
`Indpendent` allows the user to more explicitly represent the desired concept. We view this as extremely useful, although it's not strictly necessary.
Fun facts:
* `b3.sample` and `b3_joint.sample` have different conceptual implementations, but indistinguishable outputs: the difference between a batch of independent distributions and a single distribution created from the batch using `Independent` shows up when computing probabilites, not when sampling.
* `MultivariateNormalDiag` could be trivially implemented using the scalar `Normal` and `Independent` distributions (it isn't actually implemented this way, but it could be).
## Batches of Multivariate Distirbutions
Let's create a batch of three full-covariance two-dimensional multivariate normals:
```
nd_batch = tfd.MultivariateNormalFullCovariance(
loc = [[0., 0.], [1., 1.], [2., 2.]],
covariance_matrix = [[[1., .1], [.1, 1.]],
[[1., .3], [.3, 1.]],
[[1., .5], [.5, 1.]]])
nd_batch
```
We see `batch_shape = (3,)`, so there are three independent multivariate normals, and `event_shape = (2,)`, so each multivariate normal is two-dimensional. In this example, the individual distributions do not have independent elements.
Sampling works:
```
nd_batch.sample(4)
```
Since `batch_shape = (3,)` and `event_shape = (2,)`, we pass a tensor of shape `(3, 2)` to `log_prob`:
```
nd_batch.log_prob([[0., 0.], [1., 1.], [2., 2.]])
```
## Broadcasting, aka Why Is This So Confusing?
Abstracting out what we've done so far, every distribution has an batch shape `B` and an event shape `E`. Let `BE` be the concatenation of the event shapes:
* For the univariate scalar distributions `n` and `b`, `BE = ().`.
* For the two-dimensional multivariate normals `nd`. `BE = (2).`
* For both `b3` and `b3_joint`, `BE = (3).`
* For the batch of multivariate normals `ndb`, `BE = (3, 2).`
The "evaluation rules" we've been using so far are:
* Sample with no argument returns a tensor with shape `BE`; sampling with a scalar n returns an "n by `BE`" tensor.
* `prob` and `log_prob` take a tensor of shape `BE` and return a result of shape `B`.
The actual "evaluation rule" for `prob` and `log_prob` is more complicated, in a way that offers potential power and speed but also complexity and challenges. The actual rule is (essentially) that **the argument to `log_prob` *must* be [broadcastable](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) against `BE`; any "extra" dimensions are preserved in the output.**
Let's explore the implications. For the univariate normal `n`, `BE = ()`, so `log_prob` expects a scalar. If we pass `log_prob` a tensor with non-empty shape, those show up as batch dimensions in the output:
```
n = tfd.Normal(loc=0., scale=1.)
n
n.log_prob(0.)
n.log_prob([0.])
n.log_prob([[0., 1.], [-1., 2.]])
```
Let's turn to the two-dimensional multivariate normal `nd` (parameters changed for illustrative purposes):
```
nd = tfd.MultivariateNormalDiag(loc=[0., 1.], scale_diag=[1., 1.])
nd
```
`log_prob` "expects" an argument with shape `(2,)`, but it will accept any argument that broadcasts against this shape:
```
nd.log_prob([0., 0.])
```
But we can pass in "more" examples, and evaluate all their `log_prob`'s at once:
```
nd.log_prob([[0., 0.],
[1., 1.],
[2., 2.]])
```
Perhaps less appealingly, we can broadcast over the event dimensions:
```
nd.log_prob([0.])
nd.log_prob([[0.], [1.], [2.]])
```
Broadcasting this way is a consequence of our "enable broadcasting whenever possible" design; this usage is somewhat controversial and could potentially be removed in a future version of TFP.
Now let's look at the three coins example again:
```
b3 = tfd.Bernoulli(probs=[.3, .5, .7])
```
Here, using broadcasting to represent the probability that *each* coin comes up heads is quite intuitive:
```
b3.prob([1])
```
(Compare this to `b3.prob([1., 1., 1.])`, which we would have used back where `b3` was introduced.)
Now suppose we want to know, for each coin, the probability the coin comes up heads *and* the probability it comes up tails. We could imagine trying:
`b3.log_prob([0, 1])`
Unfortunately, this produces an error with a long and not-very-readable stack trace. `b3` has `BE = (3)`, so we must pass `b3.prob` something broadcastable against `(3,)`. `[0, 1]` has shape `(2)`, so it doesn't broadcast and creates an error. Instead, we have to say:
```
b3.prob([[0], [1]])
```
Why? `[[0], [1]]` has shape `(2, 1)`, so it broadcasts against shape `(3)` to make a broadcast shape of `(2, 3)`.
Broadcasting is quite powerful: there are cases where it allows order-of-magnitude reduction in the amount of memory used, and it often makes user code shorter. However, it can be challenging to program with. If you call `log_prob` and get an error, a failure to broadcast is nearly always the problem.
## Going Farther
In this tutorial, we've (hopefully) provided a simple introduction. A few pointers for going further:
* `event_shape`, `batch_shape` and `sample_shape` can be arbitrary rank (in this tutorial they are always either scalar or rank 1). This increases the power but again can lead to programming challenges, especially when broadcasting is involved. For an additional deep dive into shape manipulation, see the [Understanding TensorFlow Distributions Shapes](https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Understanding_TensorFlow_Distributions_Shapes.ipynb).
* TFP includes a powerful abstraction known as `Bijectors`, which in conjunction with `TransformedDistribution`, yields a flexible, compositional way to easily create new distributions that are invertible transformations of existing distributions. We'll try to write a tutorial on this soon, but in the meantime, check out [the documentation](https://www.tensorflow.org/probability/api_docs/python/tfp/distributions/TransformedDistribution)
| github_jupyter |
# Aufgabe 11 - Trading Environment Setup
22.01.2022, Thomas Iten
**Content**
0. Setup
1. Load S&P 500 Dataset
2. Define Trading Environment
3. Create Trading Environment and visualize some state values
4. Test some random actions and visualize the rewards
## 0. Setup
```
import random
import numpy as np
import gym
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
from dataset import SP500DataSet
from env import TradingEnv
```
## 1. Load S&P 500 Dataset
```
ds = SP500DataSet()
df_train, df_test = ds.get_train_test()
```
### Head of train data
```
df_train.head()
```
### Head of test data
```
df_test.head()
```
## 2. Define Trading Environment
```
class TradingEnv(gym.Env):
"""The S&P 500 Trading Environment."""
INITIAL_IDX = 0
INITIAL_CASH = 10_000
INITIAL_PORTFOLIO_VALUE = 0
ACTIONS = ["sell", "hold", "buy"]
def __init__(self, df_train, df_test, play=False):
# df and starting index
self.df = df_test if play else df_train
self.current_idx = TradingEnv.INITIAL_IDX
# cash and portfolio
self.cash = TradingEnv.INITIAL_CASH
self.portfolio_value = TradingEnv.INITIAL_PORTFOLIO_VALUE
# target stocks and stock values
self.stocks = ['AAPL', 'MSFT', 'AMZN', 'NFLX', 'XOM', 'JPM', 'T'] # target stocks
self.stock_values = np.zeros(len(self.stocks))
# number, states and rewards
self.n = len(self.df)
self.states = self.df.loc[:, ~self.df.columns.isin(self.stocks)].to_numpy()
self.rewards = self.df[self.stocks].to_numpy()
# last step data
self.last_step = None
def reset(self):
self.current_idx = TradingEnv.INITIAL_IDX
self.cash = TradingEnv.INITIAL_CASH
self.portfolio_value = TradingEnv.INITIAL_PORTFOLIO_VALUE
self.stock_values = np.zeros(len(self.stocks))
state = self.states[self.current_idx]
state = np.array(state).reshape(1, -1)
self.last_step = None
return state
def step(self, action):
"""
Run the give action, take a step forward and return the next state with the reward and done flag.
The actions calculates the difference between the mean value of the next states and the current states.
The reward is then calculated according the following table:
Action Difference Rise Reward
sell positive True -10
sell negative False +10
buy positive True +20
buy negative False -10
hold n/a n/a 0
:param action: ["sell", "hold", "buy"]
:return: next_state, reward, done
"""
# check valid state
if self.current_idx >= self.n:
raise Exception("Episode already done")
# check valid actions
if action not in TradingEnv.ACTIONS:
raise Exception("Invalid action: " + action)
# apply action and calculate mean values before and after
mean = np.mean(self.states[self.current_idx])
self.current_idx += 1 # apply action
next_mean = np.mean(self.states[self.current_idx])
# calculate done
done = (self.current_idx == self.n - 1)
if done:
next_state = None
reward = 0
else:
# calculate reward
reward = 0
rise = (next_mean - mean) > 0
if action == "sell":
reward = -10 if rise else +10
elif action == "buy":
reward = +20 if rise else -10
# calculate next step
next_state = self.states[self.current_idx]
next_state = np.array(next_state).reshape(1, -1)
# save last step data
self.last_step = {"action": action, "rise": rise, "reward": reward, "done": done}
# return results
return next_state, reward, done
def render(self):
# Currently we just render the data of the last step
print(self.last_step["action"] + ":",
"vaules rised=" + str(self.last_step["rise"]),
"reward=" + str(self.last_step["reward"]),
"done=" + str(self.last_step["done"]))
def render_state_mean_values(self, start=0, n=None):
means = []
steps = []
stop = len(self.states) if n is None else n
for i in range(start, stop):
mean = np.mean(self.states[i])
means.append(mean)
steps.append(i)
self.plot(steps, means, title="State values", xlabel="Step", ylabel="Mean")
def plot(self, x, y, title="", xlabel="", ylabel=""):
"""Simple plot function.
Further details see: https://jakevdp.github.io/PythonDataScienceHandbook/04.01-simple-line-plots.html
"""
fig = plt.figure()
ax = plt.axes()
ax.plot(x, y);
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.show()
```
## 3. Create Trading Environment and visualize some state values
### Create and reset
```
env = TradingEnv(df_train, df_test)
env.reset()
```
### Visualize the first 100 state mean values
```
env.render_state_mean_values(n=100)
```
## 4. Test some random actions and visualize the rewards
### Test some random actions
```
# test some actions
n=24
rewards = []
print("Actions:")
for _ in range(n):
action = TradingEnv.ACTIONS[random.randint(0,2)]
next_state, reward, done = env.step(action)
rewards.append(reward)
env.render()
```
### Visualize the rewards
```
env.plot(range(0,n), rewards, title="Rewards", xlabel="Step", ylabel="Reward")
```
---
__The end.__
| github_jupyter |
```
%gui qt5
import datetime
from collections import defaultdict
import ibapi
from tws_async import TWSClientQt, iswrapper, util, Stock
util.logToConsole()
# sample application
class TWS(TWSClientQt):
def __init__(self):
TWSClientQt.__init__(self)
self._reqIdSeq = 0
self._histData = defaultdict(list)
def popHistData(self, reqId):
"""
Remove and return the historical data that was downloaded for the given reqId.
"""
return self._histData.pop(reqId)
@iswrapper
def tickPrice(self, reqId: int,
tickType: ibapi.ticktype.TickType,
price: float,
attrib: ibapi.common.TickAttrib):
print('{} price {}'.format(reqId, price))
@iswrapper
def tickSize(self, reqId: int,
tickType: ibapi.ticktype.TickType,
size: int):
print('{} size {}'.format(reqId, size))
@iswrapper
def historicalData(self, reqId: int, date: str, open: float, high: float,
low: float, close: float, volume: int, barCount: int,
WAP: float, hasGaps: int):
self._histData[reqId].append((date, open, high, low, close, volume))
@iswrapper
def historicalDataEnd(self, reqId: int, start: str, end: str):
print('Historical request {} is finished'.format(reqId))
if 'tws' in locals():
tws.disconnect()
tws = TWS()
tws.connect('127.0.0.1', 7497, clientId=1)
# request historical bar data
contract = Stock('TSLA')
reqId = tws.getReqId()
tws.reqHistoricalData(reqId, contract,
endDateTime=datetime.datetime.utcnow().strftime('%Y%m%d %H:%M:%S UTC'),
durationStr='60 D',
barSizeSetting='1 hour',
whatToShow='TRADES',
useRTH=False,
formatDate=1,
chartOptions=None)
# fetch data when it's finished
data = tws.popHistData(reqId)
# process data
import pandas as pd
df = pd.DataFrame.from_records(data)
df.columns = ['datetime', 'open', 'high', 'low', 'close', 'volume']
df['datetime'] = pd.to_datetime(df['datetime'])
# df.set_index('datetime', inplace=True)
display(df.head())
display(df.tail())
# plot data
%matplotlib inline
import seaborn as sns
df.plot(y='close', figsize=(12,8))
# subscribe to realtime tick data
reqId = tws.getReqId()
tws.reqMktData(reqId, contract, genericTickList='', snapshot=False,
regulatorySnapshot=False, mktDataOptions=[])
# cancel realtime ticks
tws.cancelMktData(reqId)
# asyncio integration
import asyncio
import quamash
async def coro(seconds):
print('starting coroutine...')
await asyncio.sleep(seconds)
print('coroutine finished')
loop = quamash.QEventLoop()
asyncio.set_event_loop(loop)
task = asyncio.ensure_future(coro(seconds=1))
# note that the Qt event loop doesn't need to be started as it's already running
```
| github_jupyter |
```
... # these dots mean the code segement is not executable
# prepare dataset
data = ...
# define transform
lda = LinearDiscriminantAnalysis()
# prepare transform on dataset
lda.fit(data)
# apply transform to dataset
transformed = lda.transform(data)
...
# define the pipeline
steps = [('lda', LinearDiscriminantAnalysis()), ('m', GaussianNB())]
model = Pipeline(steps=steps)
...
# define the pipeline
steps = [('s', StandardScaler()), ('lda', LinearDiscriminantAnalysis()), ('m',
GaussianNB())]
model = Pipeline(steps=steps)
# test classification dataset
from sklearn.datasets import make_classification
# define dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5,
random_state=7, n_classes=10)
# summarize the dataset
print(X.shape, y.shape)
# evaluate lda with naive bayes algorithm for classification
from numpy import mean
from numpy import std
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
# define dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5,
random_state=7, n_classes=10)
# define the pipeline
steps = [('lda', LinearDiscriminantAnalysis(n_components=5)), ('m', GaussianNB())]
model = Pipeline(steps=steps)
# evaluate model
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1)
# report performance
print('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))
# compare lda number of components with naive bayes algorithm for classification
from numpy import mean
from numpy import std
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from matplotlib import pyplot
# get the dataset
def get_dataset():
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=7, n_classes=10)
return X, y
# get a list of models to evaluate
def get_models():
models = dict()
for i in range(1,10):
steps = [('lda', LinearDiscriminantAnalysis(n_components=i)), ('m', GaussianNB())]
models[str(i)] = Pipeline(steps=steps)
return models
# evaluate a give model using cross-validation
def evaluate_model(model, X, y):
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')
return scores
# define dataset
X, y = get_dataset()
# get the models to evaluate
models = get_models()
# evaluate the models and store results
results, names = list(), list()
for name, model in models.items():
scores = evaluate_model(model, X, y)
results.append(scores)
names.append(name)
print('>%s %.3f (%.3f)' % (name, mean(scores), std(scores)))
# plot model performance for comparison
pyplot.boxplot(results, labels=names, showmeans=True)
pyplot.show()
# make predictions using lda with naive bayes
from sklearn.datasets import make_classification
from sklearn.pipeline import Pipeline
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
# define dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=7, n_classes=10)
# define the model
steps = [('lda', LinearDiscriminantAnalysis(n_components=9)), ('m', GaussianNB())]
model = Pipeline(steps=steps)
# fit the model on the whole dataset
model.fit(X, y)
# make a single prediction
row = [[2.3548775,-1.69674567,1.6193882,-1.19668862,-2.85422348,-2.00998376,16.56128782,2.57257575,9.93779782,0.43415008,6.08274911,2.12689336,1.70100279,3.32160983,13.02048541,-3.05034488,2.06346747,-3.33390362,2.45147541,-1.23455205]]
yhat = model.predict(row)
print('Predicted Class: %d' % yhat[0])
..
data = ...
# define transform
pca = PCA()
# prepare transform on dataset
pca.fit(data)
# apply transform to dataset
transformed = pca.transform(data)
...
# define the pipeline
steps = [('pca', PCA()), ('m', LogisticRegression())]
model = Pipeline(steps=steps)
...
# define the pipeline
steps = [('norm', MinMaxScaler()), ('pca', PCA()), ('m', LogisticRegression())]
model = Pipeline(steps=steps)
# test classification dataset
from sklearn.datasets import make_classification
# define dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=7)
# summarize the dataset
print(X.shape, y.shape)
# evaluate pca with logistic regression algorithm for classification
from numpy import mean
from numpy import std
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
# define dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=7)
# define the pipeline
steps = [('pca', PCA(n_components=10)), ('m', LogisticRegression())]
model = Pipeline(steps=steps)
# evaluate model
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')
# report performance
print('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))
# compare pca number of components with logistic regression algorithm for classification
from numpy import mean
from numpy import std
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from matplotlib import pyplot
# get the dataset
def get_dataset():
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=7)
return X, y
# get a list of models to evaluate
def get_models():
models = dict()
for i in range(1,21):
steps = [('pca', PCA(n_components=i)), ('m', LogisticRegression())]
models[str(i)] = Pipeline(steps=steps)
return models
# evaluate a given model using cross-validation
def evaluate_model(model, X, y):
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')
return scores
# define dataset
X, y = get_dataset()
# get the models to evaluate
models = get_models()
# evaluate the models and store results
results, names = list(), list()
for name, model in models.items():
scores = evaluate_model(model, X, y)
results.append(scores)
names.append(name)
print('>%s %.3f (%.3f)' % (name, mean(scores), std(scores)))
# plot model performance for comparison
pyplot.boxplot(results, labels=names, showmeans=True)
pyplot.xticks(rotation=45)
pyplot.show()
```
| github_jupyter |
#**THE SPARKS FOUNDATION**
*Graduate Rotational Internship Program* <br>
**Task 2: Prediction using Unsupervised ML**
**Author: Rushabh Thakkar**
```
#importing required libraries
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
%matplotlib inline
from google.colab import drive
drive.mount('/content/drive')
#Loading Dataset
df=pd.read_csv('/content/Iris.csv')
df.drop(['Id'],axis=1,inplace=True)
#Reading Data
df.head()
df.describe()
df.info()
df.drop_duplicates(inplace=True)
df.shape
```
**Label Encoding**
```
from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
df['Species']=le.fit_transform(df['Species'])
df['Species'].value_counts()
```
**PetalLengthCm vs PetalWidthCm**
```
plt.scatter(df['PetalLengthCm'],df['PetalWidthCm'],c=df.Species.values)
plt.title('PetalLengthCm vs PetalWidthCm', fontsize=15)
plt.xlabel('PetalLengthCm')
plt.ylabel('PetalWidthCm')
df.corr()
df=df.iloc[:,[0,1,2,3]].values
```
**Elbow Method using within-cluster-sum-of-squares(wcss)**
```
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)
kmeans.fit(df)
# inertia method returns wcss for that model
wcss.append(kmeans.inertia_)
wcss
```
**Using Elbow graph to find optimum no. of Clusters**
```
import seaborn as sns
plt.figure(figsize=(10,5))
sns.set(style='whitegrid')
sns.lineplot(range(1, 11), wcss,marker='o',color='red')
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
```
>The optimum value for K would be 3. As we can see that with an increase in the number of clusters the WCSS value decreases. We select the value for K on the basis of the rate of decrease in WCSS and we can see that after 3 the drop in wcss is minimal.
**Initialization using K-means++**
```
kmeans = KMeans(n_clusters = 3, init = 'k-means++', random_state = 5)
y_kmeans = kmeans.fit_predict(df)
y_kmeans
```
**Visualizing the Clusters**
```
fig = plt.figure(figsize=(10, 7))
plt.title('Clusters with Centroids',fontweight ='bold', fontsize=20)
plt.scatter(df[y_kmeans == 0, 2], df[y_kmeans == 0, 3], s = 100, c = 'blue', label = 'Iris-versicolour')
plt.scatter(df[y_kmeans == 1, 2], df[y_kmeans == 1, 3], s = 100, c = 'red', label = 'Iris-setosa')
plt.scatter(df[y_kmeans == 2, 2], df[y_kmeans == 2, 3],s = 100, c = 'yellow', label = 'Iris-virginica')
plt.scatter(kmeans.cluster_centers_[:, 2], kmeans.cluster_centers_[:,3], s = 150, c = 'black',
label = 'Centroids')
plt.title('Iris Flower Clusters')
plt.ylabel('Petal Width in cm')
plt.xlabel('Petal Length in cm')
plt.legend()
```
We can see that our predicted graph is quite similar to the actual one.
| github_jupyter |
```
# preliminaries
import sys,os,time,cv2
import numpy as np
import matplotlib.pyplot as plt
from utils import imread_to_rgb, img_rgb2bw
DB_PATH = '/home/jhchoi/datasets4/RAF/'
raf_dict = dict()
#FER: 0=angry, 1=disgust, 2=fear, 3=happy, 4=sad, 5=surprise, 6=neutral
#RAF-basic and RAF-multi:
# 1:Surprise, 2:Fear, 3:Disgust, 4:Happiness, 5:Sadness, 6:Anger, 7:Neutral
#RAF-compound:
# 1: Happily Surprised, 2: Happily Disgusted, 3: Sadly Fearful, 4: Sadly Angry, 5: Sadly Surprised, 6: Sadly Disgusted
# 7: Fearfully Angry, 8: Fearfully Surprised, 9: Angrily Surprised, 10: Angrily Disgusted, 11: Disgustedly Surprised
# translate from RAF-Basic to FER label vectors
def emo_rafb2fer(rf):
fer_arr = [-1, 5, 2, 1, 3, 4, 0, 6]
fer = fer_arr[rf]
emo_label = np.zeros(7)
emo_label[fer] = 1.
return emo_label
# translate from RAF-Compound to FER label vectors
def emo_rafc2fer(rf):
dic = [-1, #0,1,2,3,4,5,6
np.array([0,0,0,1,0,1,0]), #1 Happily Surprised
np.array([0,1,0,1,0,0,0]), #2 Happily Disgusted
np.array([0,0,1,0,1,0,0]), #3 Sadly Fearful
np.array([1,0,0,0,1,0,0]), #4 Sadly Angry
np.array([0,0,0,0,1,1,0]), #5 Sadly Surprised
np.array([0,1,0,0,1,0,0]), #6 Sadly Disgusted
np.array([1,0,1,0,0,0,0]), #7 Fearfully Angry
np.array([0,0,1,0,0,1,0]), #8 Fearfully Surprised
np.array([1,0,0,0,0,1,0]), #9 Angrily Surprised
np.array([1,1,0,0,0,0,0]), #10 Angrily Disgusted
np.array([0,1,0,0,0,1,0]) #11 Disgustedly Surprised
]
fer = dic[rf].astype(float)*0.5
return fer
# translate from RAF-Multi to FER label vectors
def emo_rafm2fer(rf):
neu = np.max([1. - np.sum(rf), 0.])
fer = np.array([rf[5],rf[2],rf[1],rf[3],rf[4],rf[0],neu])
return fer
raf_b_dict = dict()
raf_c_dict = dict()
raf_m_dict = dict()
# add basic db
basic_path = os.path.join(DB_PATH, 'basic')
labels = np.genfromtxt(os.path.join(basic_path,'EmoLabel','list_patition_label.txt'), delimiter=' ', dtype=str)
for i,data in enumerate(labels):
data_name = data[0]
data_label = emo_rafb2fer(int(data[1]))
data_bb_path = os.path.join(basic_path, 'Annotation/boundingbox', data_name.split('.')[0]+'_boundingbox.txt')
data_bb = np.genfromtxt(data_bb_path, delimiter=' ') # (xmin,ymin,xmax,ymax)
data_path = os.path.join('basic/Image/original', data_name)
raf_b_dict[i] = {'img': data_path, 'em': data_label, 'bb': data_bb }
# add compound db
comp_path = os.path.join(DB_PATH, 'compound')
labels = np.genfromtxt(os.path.join(comp_path,'EmoLabel','list_patition_label.txt'), delimiter=' ', dtype=str)
for i,data in enumerate(labels):
data_name = data[0]
data_label = emo_rafc2fer(int(data[1]))
data_bb_path = os.path.join(comp_path, 'Annotation/boundingbox', data_name.split('.')[0]+'_boundingbox.txt')
data_bb = np.genfromtxt(data_bb_path, delimiter=' ')
data_path = os.path.join('compound/Image/original', data_name)
raf_c_dict[i] = {'img': data_path, 'em': data_label, 'bb': data_bb }
# add multi db
multi_path = os.path.join(DB_PATH, 'multi')
labels = np.genfromtxt(os.path.join(multi_path,'EmoLabel','distribution.txt'), delimiter=' ', dtype=str)
for i,data in enumerate(labels):
data_name = data[0]
data_label = emo_rafm2fer((data[1:]).astype(float))
data_bb_path = os.path.join(multi_path, 'Annotation/manual', data_name.split('.')[0]+'_manu_ldmk.txt')
data_bb = np.genfromtxt(data_bb_path, delimiter='\t', dtype=float)
if data_bb.ndim <2:
#print data_name
data_bb = np.genfromtxt(data_bb_path, delimiter=' ', dtype=float, skip_footer=3)[:,:2]
xmin = np.min(data_bb[:,0])
xmax = np.max(data_bb[:,0])
ymin = np.min(data_bb[:,1])
ymax = np.max(data_bb[:,1])
w = xmax-xmin
h = ymax-ymin
m = 0.5 # h/w face margin ratio
data_bb_mod = np.array([xmin-w*m, ymin-h*m, xmax+w*m, ymax+h*m])
data_path = os.path.join('multi/Image/original', data_name)
raf_m_dict[i] = {'img': data_path, 'em': data_label, 'bb': data_bb_mod }
i = 0
for db in raf_b_dict.keys():
raf_dict[i] = raf_b_dict[db]
i += 1
for db in raf_c_dict.keys():
raf_dict[i] = raf_c_dict[db]
i += 1
for db in raf_m_dict.keys():
raf_dict[i] = raf_m_dict[db]
i += 1
print i
np.save('../../dicts/raf_parsed.npy', raf_dict, allow_pickle=True)
print 'saved'
data = raf_dict[20000]
print data['em']
data['bb'] = data['bb'].astype(int)
im = plt.imread(os.path.join(DB_PATH, data['img']))
im = cv2.rectangle(im, (data['bb'][0],data['bb'][1]), (data['bb'][2],data['bb'][3]), (255,0,255), 5)
plt.imshow(im)
raf_dict[0]
```
| github_jupyter |
```
from IPython.display import Markdown as md
### change to reflect your notebook
_nb_loc = "05_create_dataset/05_audio.ipynb"
_nb_title = "Vision ML on Audio, Video, Text, etc."
### no need to change any of this
_nb_safeloc = _nb_loc.replace('/', '%2F')
_nb_safetitle = _nb_title.replace(' ', '+')
md("""
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://console.cloud.google.com/ai-platform/notebooks/deploy-notebook?name={1}&url=https%3A%2F%2Fgithub.com%2FGoogleCloudPlatform%2Fpractical-ml-vision-book%2Fblob%2Fmaster%2F{2}&download_url=https%3A%2F%2Fgithub.com%2FGoogleCloudPlatform%2Fpractical-ml-vision-book%2Fraw%2Fmaster%2F{2}">
<img src="https://raw.githubusercontent.com/GoogleCloudPlatform/practical-ml-vision-book/master/logo-cloud.png"/> Run in AI Platform Notebook</a>
</td>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/GoogleCloudPlatform/practical-ml-vision-book/blob/master/{0}">
<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/GoogleCloudPlatform/practical-ml-vision-book/blob/master/{0}">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://raw.githubusercontent.com/GoogleCloudPlatform/practical-ml-vision-book/master/{0}">
<img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
""".format(_nb_loc, _nb_safetitle, _nb_safeloc))
```
# Vision ML on Audio, Video, Text, etc.
This notebook shows you how to use the spectrogram
of an audio file as a grayscale image input to an
ML model.
```
!gsutil cp gs://ml-design-patterns/audio_train/00353774.wav cello.wav
!gsutil cp gs://ml-design-patterns/audio_train/001ca53d.wav sax.wav
import matplotlib.pyplot as plt
from scipy import signal
from scipy.io import wavfile
import numpy as np
fig, ax = plt.subplots(2, 2, figsize=(15, 10))
for idx, instr in enumerate(['sax', 'cello']):
sample_rate, samples = wavfile.read(instr + '.wav')
ax[idx][0].plot(samples)
_, _, spectro = signal.spectrogram(samples, sample_rate)
img = np.log(spectro)
ax[idx][1].imshow(img, cmap='gray', aspect='auto');
ax[idx][1].set_title(instr)
print(img.shape)
```
## Vision ML on video
Video consists of frames, each of which is an image.
```
!curl -O https://www.engr.colostate.edu/me/facil/dynamics/files/flame.avi
## Frame-by-frame
import cv2
import numpy as np
import matplotlib.pyplot as plt
cap = cv2.VideoCapture('flame.avi')
num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(num_frames)
fig, ax = plt.subplots(1, 4, figsize=(20, 10))
for i in range(num_frames):
ret, frame = cap.read()
if ret:
img = np.asarray(frame)
if i%30 == 0:
ax[i//30].imshow(img)
## Rolling average of 30 frames at a time
def rolling_average(cap, N):
img = None;
n = 0
for i in range(N):
ret, frame = cap.read()
if ret:
frame = np.asarray(frame)
if n > 0:
img = frame + img
else:
img = frame
n += 1
if n > 0:
return img / n
return img
cap = cv2.VideoCapture('flame.avi')
fig, ax = plt.subplots(1, 4, figsize=(20, 10))
for i in range(4):
img = rolling_average(cap, 25)
ax[i].imshow(img)
# read into a 4D shape
import tensorflow as tf
def read_video(filename):
cap = cv2.VideoCapture(filename)
num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frames = []
for i in range(num_frames):
ret, frame = cap.read()
if ret:
frames.append(np.asarray(frame))
return tf.convert_to_tensor(frames)
img4d = read_video('flame.avi')
print(img4d.shape)
```
## Text
We can break down a paragraph into sentences.
And we can do sentence-embedding to get a numeric representation of each sentence.
A paragraph now becomes an image!
```
import tensorflow_hub as hub
paragraph = """
Siddhartha gave his clothes to a poor Brahmin on the road and
only retained his loincloth andearth-colored unstitched cloak.
He only ate once a day and never cooked food. He fasted fourteen
days. He fasted twenty-eight days. The flesh disappeared from
his legs and cheeks. Strange dreams were reflected in his enlarged
eyes. The nails grew long on his thin fingers and a dry, bristly
beard appeared on his chin. His glance became icy when he
encountered women; his lips curled with contempt when he passed
through a town of well-dressed people. He saw businessmen trading,
princes going to the hunt, mourners weeping over their dead,
prostitutes offering themselves, doctors attending the sick,
priests deciding the day for sowing, lovers making love, mothers
soothing their children -and all were not worth a passing glance,
everything lied, stank of lies; they were all illusions of sense,
happiness and beauty. All were doomed to decay. The world tasted
bitter. Life was pain.
"""
print(paragraph.split('.'))
embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
embeddings = embed(paragraph.split('.'))
import matplotlib.pyplot as plt
plt.figure(figsize=(5,10))
plt.imshow(embeddings.numpy(), aspect=25.0, cmap='gray');
```
Copyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| github_jupyter |
# Example: CanvasXpress violin Chart No. 14
This example page demonstrates how to, using the Python package, create a chart that matches the CanvasXpress online example located at:
https://www.canvasxpress.org/examples/violin-14.html
This example is generated using the reproducible JSON obtained from the above page and the `canvasxpress.util.generator.generate_canvasxpress_code_from_json_file()` function.
Everything required for the chart to render is included in the code below. Simply run the code block.
```
from canvasxpress.canvas import CanvasXpress
from canvasxpress.js.collection import CXEvents
from canvasxpress.render.jupyter import CXNoteBook
cx = CanvasXpress(
render_to="violin14",
data={
"y": {
"smps": [
"Var1",
"Var2",
"Var3",
"Var4",
"Var5",
"Var6",
"Var7",
"Var8",
"Var9",
"Var10",
"Var11",
"Var12",
"Var13",
"Var14",
"Var15",
"Var16",
"Var17",
"Var18",
"Var19",
"Var20",
"Var21",
"Var22",
"Var23",
"Var24",
"Var25",
"Var26",
"Var27",
"Var28",
"Var29",
"Var30",
"Var31",
"Var32",
"Var33",
"Var34",
"Var35",
"Var36",
"Var37",
"Var38",
"Var39",
"Var40",
"Var41",
"Var42",
"Var43",
"Var44",
"Var45",
"Var46",
"Var47",
"Var48",
"Var49",
"Var50",
"Var51",
"Var52",
"Var53",
"Var54",
"Var55",
"Var56",
"Var57",
"Var58",
"Var59",
"Var60"
],
"data": [
[
4.2,
11.5,
7.3,
5.8,
6.4,
10,
11.2,
11.2,
5.2,
7,
16.5,
16.5,
15.2,
17.3,
22.5,
17.3,
13.6,
14.5,
18.8,
15.5,
23.6,
18.5,
33.9,
25.5,
26.4,
32.5,
26.7,
21.5,
23.3,
29.5,
15.2,
21.5,
17.6,
9.7,
14.5,
10,
8.2,
9.4,
16.5,
9.7,
19.7,
23.3,
23.6,
26.4,
20,
25.2,
25.8,
21.2,
14.5,
27.3,
25.5,
26.4,
22.4,
24.5,
24.8,
30.9,
26.4,
27.3,
29.4,
23
]
],
"vars": [
"len"
]
},
"x": {
"supp": [
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"VC",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ",
"OJ"
],
"order": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
],
"dose": [
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2
]
}
},
config={
"axisAlgorithm": "rPretty",
"axisTickScaleFontFactor": 1.8,
"axisTitleFontStyle": "bold",
"axisTitleScaleFontFactor": 1.8,
"background": "white",
"backgroundType": "window",
"backgroundWindow": "#E5E5E5",
"colorBy": "dose",
"colorScheme": "GGPlot",
"graphOrientation": "vertical",
"graphType": "Boxplot",
"groupingFactors": [
"dose",
"supp"
],
"guides": "solid",
"guidesColor": "white",
"legendScaleFontFactor": 1.8,
"showBoxplotIfViolin": True,
"showLegend": True,
"showViolinBoxplot": True,
"smpLabelRotate": 90,
"smpLabelScaleFontFactor": 1.8,
"smpTitle": "dose",
"smpTitleFontStyle": "bold",
"smpTitleScaleFontFactor": 1.8,
"stringSampleFactors": [
"dose"
],
"title": "The Effect of Vitamin C on Tooth Growth in Guinea Pigs",
"xAxis2Show": False,
"xAxisMinorTicks": False,
"xAxisTickColor": "white",
"xAxisTitle": "len"
},
width=613,
height=613,
events=CXEvents(),
after_render=[
[
"switchNumericToString",
[
"dose",
True
]
]
],
other_init_params={
"version": 35,
"events": False,
"info": False,
"afterRenderInit": False,
"noValidate": True
}
)
display = CXNoteBook(cx)
display.render(output_file="violin_14.html")
```
| github_jupyter |
<a href="https://colab.research.google.com/github/IEwaspbusters/KopuruVespaCompetitionIE/blob/main/Competition_subs/2021-04-28_submit/batch_LARVAE/HEX.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# XGBoost Years: Prediction with Cluster Variables and selected Weather Variables (according to Feature importance)
## Import the Data & Modules
```
# Base packages -----------------------------------
import pandas as pd
import numpy as np
# Data Viz -----------------------------------
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (15, 10) # to set figure size when ploting feature_importance
# XGBoost -------------------------------
import xgboost as xgb
from xgboost import XGBRegressor
from xgboost import plot_importance # built-in function to plot features ordered by their importance
# SKLearn -----------------------------------------
from sklearn import preprocessing # scaling data
#Cluster
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from plotnine import *
# Function that checks if final Output is ready for submission or needs revision
def check_data(HEX):
def template_checker(HEX):
submission_df = (HEX["CODIGO MUNICIPIO"].astype("string")+HEX["NOMBRE MUNICIPIO"]).sort_values().reset_index(drop=True)
template_df = (template["CODIGO MUNICIPIO"].astype("string")+template["NOMBRE MUNICIPIO"]).sort_values().reset_index(drop=True)
check_df = pd.DataFrame({"submission_df":submission_df,"template_df":template_df})
check_df["check"] = check_df.submission_df == check_df.template_df
if (check_df.check == False).any():
pd.options.display.max_rows = 112
return check_df.loc[check_df.check == False,:]
else:
return "All Municipality Names and Codes to be submitted match the Template"
print("Submission form Shape is", HEX.shape)
print("Number of Municipalities is", HEX["CODIGO MUNICIPIO"].nunique())
print("The Total 2020 Nests' Prediction is", int(HEX["NIDOS 2020"].sum()))
assert HEX.shape == (112, 3), "Error: Shape is incorrect."
assert HEX["CODIGO MUNICIPIO"].nunique() == 112, "Error: Number of unique municipalities is correct."
return template_checker(HEX)
# Importing datasets from GitHub as Pandas Dataframes
queen_train = pd.read_csv("../Feeder_years/WBds03_QUEENtrainYEARS.csv", encoding="utf-8") #2018+2019 test df
queen_predict = pd.read_csv("../Feeder_years/WBds03_QUEENpredictYEARS.csv", encoding="utf-8") #2020 prediction df
template = pd.read_csv("../../../Input_open_data/ds01_PLANTILLA-RETO-AVISPAS-KOPURU.csv",sep=";", encoding="utf-8")
den_com = pd.read_excel("../../../Other_open_data/densidad comercial.xlsx")
```
## Further Clean the Data
```
# Remove the Municipalities to which we did not assign a Cluster, since there was not reliable data for us to predict
queen_train = queen_train.loc[~queen_train.municip_code.isin([48071, 48074, 48022, 48088, 48051, 48020]),:]
queen_predict = queen_predict.loc[~queen_predict.municip_code.isin([48071, 48074, 48022, 48088, 48051, 48020]),:]
```
# New queen Train dataset
```
den_com_18= den_com.loc[:,['Código municipio','2018']]
den_com_18.rename({'2018': 'dens_com','Código municipio':'municip_code'}, axis=1, inplace=True)
den_com_18['year_offset']='2018'
den_com_17= den_com.loc[:,['Código municipio','2017']]
den_com_17.rename({'2017': 'dens_com','Código municipio':'municip_code'}, axis=1, inplace=True)
den_com_17['year_offset']='2017'
den_com_19= den_com.loc[:,['Código municipio','2019']]
den_com_19.rename({'2019': 'dens_com','Código municipio':'municip_code'}, axis=1, inplace=True)
den_com_19['year_offset']='2019'
densidad_comercial= den_com_18.append(den_com_17).append(den_com_19)
densidad_comercial['cod_aux']=densidad_comercial.apply(lambda x:'%s_%s' % (x['municip_code'],x['year_offset']),axis=1)
aux_train= queen_train.copy()
aux_train['cod_aux']=aux_train.apply(lambda x:'%s_%s' % (x['municip_code'],x['year_offset']),axis=1)
queen_train_mischief= aux_train.loc[:,
['municip_code','municip_name','weath_meanTemp',
'population','cod_aux','NESTS']].merge(densidad_comercial, how='left', on='cod_aux')
queen_train_mischief.drop(['cod_aux','municip_code_y'], axis=1, inplace=True)
queen_train_mischief.rename({'municip_code_x': 'municip_code'}, axis=1, inplace=True)
queen_train_mischief["dens_com"] = queen_train_mischief["dens_com"].apply(lambda x: x.replace(",", "."))
```
# New queen predict dataset
```
queen_predict_mischief= queen_predict.loc[:,['municip_code','municip_name','weath_meanTemp','year_offset','population']]
queen_predict_mischief['cod_aux']= queen_predict_mischief.apply(lambda x:'%s_%s' % (x['municip_code'],x['year_offset']),axis=1)
queen_predict_mischief= queen_predict_mischief.merge(densidad_comercial, how='left', on='cod_aux')
queen_predict_mischief.drop(['cod_aux','municip_code_y','year_offset_x','year_offset_y'], axis=1, inplace=True)
queen_predict_mischief.rename({'municip_code_x': 'municip_code'}, axis=1, inplace=True)
queen_predict_mischief["dens_com"] = queen_predict_mischief["dens_com"].apply(lambda x: x.replace(",", "."))
predict_20=queen_predict_mischief.loc[:,['weath_meanTemp', 'population', 'dens_com']]
```
## Get the Prediction
### Arrange data into a features matrix and target vector
```
# selecting the train X & y variables
# Y will be the response variable (filter for the number of wasp nests - waspbust_id)
y = queen_train_mischief.NESTS
# X will be the explanatory variables. Remove response variable and non desired categorical columns such as (municip code, year, etc...)
X = queen_train_mischief.loc[:,['weath_meanTemp', 'population', 'dens_com']]
```
### Scale the Data in order to filter the relevant variables using Feature Importance
#### Arrange data into a features matrix and target vector
```
# Scale the datasets using MinMaxScaler
X_scaled = preprocessing.minmax_scale(X) # this creates a numpy array
```
#### Choose a class of model by importing the appropriate estimator class
```
# selecting the XGBoost model and fitting with the train data
model = XGBRegressor()
```
#### Fit the model to your data by calling the `.fit()` method of the model instance
```
# selecting the XGBoost model and fitting with the train data for each cluster
model.fit(X_scaled, y)
```
#### Selecting the Relevant Variables and filtering according to the results
```
# Plot the Relevant Variables in order to filter the relevant ones per Cluster
plot_importance(model,height=0.5,xlabel="F-Score",ylabel="Feature Importance",grid=False)
plt.show()
```
### Fit the model to your data by calling the `.fit()` method of the model instance
### Apply the model to new data:
- For supervised learning, predict labels for unknown data using the `.predict()` method
```
# make a prediction
X_scaled_pred = preprocessing.minmax_scale(predict_20)
queen_predict_mischief['nests_2020'] = model.predict(X_scaled_pred)
```
## Add Each Cluster Predictions to the original DataFrame and Save it as a `.csv file`
```
# Create a new DataFrame with the Municipalities to insert manualy
HEX_aux = pd.DataFrame({"CODIGO MUNICIPIO":[48022, 48071, 48088, 48074, 48051, 48020],\
"NOMBRE MUNICIPIO":["Karrantza Harana/Valle de Carranza","Muskiz","Ubide","Urduña/Orduña","Lanestosa","Bilbao"],\
"NIDOS 2020":[0,0,1,0,1,0]})
HEX = queen_predict_mischief.loc[:,["municip_code","municip_name","nests_2020"]].round() # create a new Dataframe for Kopuru submission
HEX.columns = ["CODIGO MUNICIPIO","NOMBRE MUNICIPIO","NIDOS 2020"] # change column names to Spanish (Decidata template)
HEX = HEX.append(HEX_aux, ignore_index=True) # Add rows of municipalities to add manually
# Final check
check_data(HEX)
# reset max_rows to default values (used in function to see which rows did not match template)
pd.reset_option("max_rows")
# Save the new dataFrame as a .csv in the current working directory on Windows
HEX.to_csv("WaspBusters_20210519_XGyears_NOcluster_PC2.csv", index=False)
```
| github_jupyter |
```
1, 2, 3, 4 # int – целые числа
int(3.5)
round(4.5)
round(5.5)
import numpy as np
np.round(3.5, 0) # первый аргумент – число, которое округляем, второй – сколько знаков после запятой
3.5, 4.5, 5.5 # float
'строка' # string
True, False # bool
5 == 7
145 / 3 >= 12 *8
a, b = [int(i) for i in input().split()]
if a > b:
print('>')
elif a == b:
print('=')
#elif
#elif
else:
print('<')
if a > b:
print(0)
if a > b:
print(0)
if a > b:
print(0)
a
b
inp = input()
inp.split()
```
типы данных:
* int
* float
* string
* boolean
```
myList = []
myList = list()
myList = [1, 2, 3, 5.2, 'cat', 'dog']
myList[0]
myList[2:4]
myList[::2]
myList[::-1]
matrix = [[1, 2, 3], [4, 5, 6]]
matrix
matrix[0][1]
sentence = input()
sentence.split()
myList
myList.append(18) # добавить элемент в конец
myList
[1, 2, 3] + [4, 5, 6]
myList.remove(18)
myList
myList.pop() # удалит последний элемент и выведет его на экран
myList
myList.count('cat')
a, b = map(int, input().split())
a, b
input().split()
a = [7, 3, 8, 2, 91, 15]
sorted(a)
sorted(a, reverse=True)
a
a.sort()
a
z = 1, 2
z
type(z) # кортеж
a = [0, 1, 2]
a[1] = 999
a
b = (0, 1, 2)
b[1] = 999
```
структуры данных:
* списки
* кортежи
Для могущественного магического ритуала Гендальфу нужно быстро подсчитывать площадь своего амулета, который умеет менять размеры. Известно, что амулет имеет форму круга, а Гендальф знает его радиус. Напишите код для подсчёта площади амулета по его радиусу.
```
import math
r = float(input())
ans = math.pi * (r ** 2)
print(ans)
```
Пятачок хочет запрограммировать разложение в ряд Маклорена экспоненты, но ему нужна ваша помощь. Напишите программку, которая считает ряд Маклорена для ЭКСПОНЕНТЫ и на каждом шагу выдает значение ошибки вычисления с помощью ряда Маклорена (модуль разницы значений полученных с помощью ряда Маклорена и с помощью функции из пакета math)
```
import math
x = float(input())
N = int(input())
count = 1
for i in range(1, N+1):
res = count - (math.e ** x)
count += (x ** i) / math.factorial(i)
print("%.10f"% math.fabs(res))
math.e
```
* `range(finish)` – последовательность чисел от 0 до finish не включительно (последним числом будет finish-1)
* `range(start, finish)` – последовательность чисел от start до finis не вкл
* `range(start, finish, step)` – последовательность чисел от start до finis не вкл с шагом step
```
list(range(10))
list(range(1, 11))
list(range(1, 11, 2))
list(range(1, 11, 3))
```
Филипп не успел во-время подготовить первый семинар. Теперь он должен остальным семинаристам волшебную жижу.
Макс, Ахмед, Настя, Артур и Артем уже стоят в очереди за волшебной жижей. Других людей в очереди нет. Когда первый в очереди (Макс) пьёт жижу, он удваивается, и два Макса идут назад, в конец очереди. Следующий в очереди (Ахмед) также пьет, удваивается, и идет в конец, и так далее.
В итоге, после того, как Макс и Ахмед выпьют жижу, очередь выглядит вот так:
Настя, Артур, Артем, Макс, Макс, Ахмед, Ахмед
Третью жижу будет пить Настя.
Напишите программу, которая вернет имя человека, который выпьет n-ю жижу.
```
n = int(input())
sem = ['Макс', 'Ахмед', 'Настя', 'Артур', 'Артем']
for i in range(1, n+1):
sem = sem + [sem[0]] * 2
sem = sem[1:]
print(sem[-1])
[sem[0]] * 2
[sem[0]] * 2
sem = sem + [sem[0]] * 2
sem
sem[1:]
sem[-1]
```
Маша отправилась в горное путешествие. В каждый момент ее пути высота меняется. Высота задается натуральным числом. Маше интересно: какое минимальное расстояние между горными вершинами на ее пути. Маша заканчивает свое путешествие у моря, поэтому высота там всегда равна 0. Вершиной называется место, которое больше своих соседей по высоте.
Если на пути меньше чем 2 вершины, то выведите 0. Начало и конец пути вершинами не считаются.
```
points = []
peak = -1
while peak != 0:
peak = int(input())
points.append(peak)
points = points[:-1]
peaks = []
for i in range(1, len(points)-1):
if points[i-1] < points[i] > points[i+1]:
peaks.append(i)
points
peaks
diff = []
for i in range(len(peaks)-1):
d = peaks[i+1] - peaks[i]
print(d)
diff.append(d)
diff
if len(diff) == 0:
print(0)
else:
print(min(diff))
# собираем все целиком
# считываем данные
points = []
peak = -1
while peak != 0:
peak = int(input())
points.append(peak)
# отрезаем нолик
points = points[:-1]
# находим ИНДЕКСЫ вершин и сохраняем в список
peaks = []
for i in range(1, len(points)-1):
if points[i-1] < points[i] > points[i+1]:
peaks.append(i)
# считаем расстояния между вершинами и сохраняем в список
diff = []
for i in range(len(peaks)-1):
d = peaks[i+1] - peaks[i]
diff.append(d)
# выводим минимум из списка с расстояниями вершин. но! добавили проверку, что список не пустой
if len(diff) == 0:
print(0)
else:
print(min(diff))
```
| github_jupyter |
# <div style="text-align: center">A Data Science Framework for Elo </div>
### <div align="center"><b>Quite Practical and Far from any Theoretical Concepts</b></div>
<div style="text-align:center">last update: <b>11/28/2018</b></div>
<img src='http://s8.picofile.com/file/8344134250/KOpng.png'>
You can Fork and Run this kernel on **Github**:
> ###### [ GitHub](https://github.com/mjbahmani/10-steps-to-become-a-data-scientist)
<a id="1"></a> <br>
## 1- Introduction
**[Elo](https://www.cartaoelo.com.br/)** has defined a competition in **Kaggle**. A realistic and attractive data set for data scientists.
on this notebook, I will provide a **comprehensive** approach to solve Elo Recommendation problem.
I am open to getting your feedback for improving this **kernel**.
<a id="top"></a> <br>
## Notebook Content
1. [Introduction](#1)
1. [Data Science Workflow for Elo](#2)
1. [Problem Definition](#3)
1. [Business View](#4)
1. [Real world Application Vs Competitions](#31)
1. [Problem feature](#7)
1. [Aim](#8)
1. [Variables](#9)
1. [ Inputs & Outputs](#10)
1. [Evaluation](#10)
1. [Select Framework](#11)
1. [Import](#12)
1. [Version](#13)
1. [Setup](#14)
1. [Exploratory data analysis](#15)
1. [Data Collection](#16)
1. [data_dictionary Analysis](#17)
1. [Explorer Dataset](#18)
1. [Data Cleaning](#19)
1. [Data Preprocessing](#20)
1. [Data Visualization](#23)
1. [countplot](#61)
1. [pie plot](#62)
1. [Histogram](#63)
1. [violin plot](#64)
1. [kdeplot](#65)
1. [Apply Learning](#24)
1. [Conclusion](#25)
1. [References](#26)
-------------------------------------------------------------------------------------------------------------
**I hope you find this kernel helpful and some <font color="red"><b>UPVOTES</b></font> would be very much appreciated**
-----------
<a id="2"></a> <br>
## 2- A Data Science Workflow for Elo
Of course, the same solution can not be provided for all problems, so the best way is to create a **general framework** and adapt it to new problem.
**You can see my workflow in the below image** :
<img src="http://s8.picofile.com/file/8342707700/workflow2.png" />
**You should feel free to adjust this checklist to your needs**
###### [Go to top](#top)
<a id="3"></a> <br>
## 3- Problem Definition
I think one of the important things when you start a new machine learning project is Defining your problem. that means you should understand business problem.( **Problem Formalization**)
<img src='http://s8.picofile.com/file/8344103134/Problem_Definition2.png' width=400 height=400>
> We are predicting a **loyalty score** for each card_id represented in test.csv and sample_submission.csv.
## 3-1 About Elo
[Elo](https://www.cartaoelo.com.br/) is one of the largest **payment brands** in Brazil, has built partnerships with merchants in order to offer promotions or discounts to cardholders. But
1. do these promotions work for either the consumer or the merchant?
1. Do customers enjoy their experience?
1. Do merchants see repeat business?
**Personalization is key**.
<a id="4"></a> <br>
## 3-2 Business View
**Elo** has built machine learning models to understand the most important aspects and preferences in their customers’ lifecycle, from food to shopping. But so far none of them is specifically tailored for an individual or profile. This is where you come in.
<a id="31"></a> <br>
### 3-2-1 Real world Application Vs Competitions
Just a simple comparison between real-world apps with competitions:
<img src="http://s9.picofile.com/file/8339956300/reallife.png" height="600" width="500" />
###### [Go to top](#top)
<a id="7"></a> <br>
## 4- Problem Feature
Problem Definition has four steps that have illustrated in the picture below:
1. Aim
1. Variable
1. Inputs & Outputs
1. Evaluation
<a id="8"></a> <br>
### 4-1 Aim
Develop algorithms to identify and serve the most relevant opportunities to individuals, by uncovering signal in customer loyalty.
We are predicting a **loyalty score** for each card_id represented in test.csv and sample_submission.csv.
<a id="9"></a> <br>
### 4-2 Variables
The data is formatted as follows:
train.csv and test.csv contain card_ids and information about the card itself - the first month the card was active, etc. train.csv also contains the target.
historical_transactions.csv and new_merchant_transactions.csv are designed to be joined with train.csv, test.csv, and merchants.csv. They contain information about transactions for each card, as described above.
merchants can be joined with the transaction sets to provide additional merchant-level information.
<a id="10"></a> <br>
### 4-3 Inputs & Outputs
we use train.csv and test.csv as Input and we should upload a submission.csv as Output
### 4-4 Evaluation
Submissions are scored on the root mean squared error. RMSE(Root Mean Squared Error) is defined as:
<img src='https://www.includehelp.com/ml-ai/Images/rmse-1.jpg'>
where y^ is the predicted loyalty score for each card_id, and y is the actual loyalty score assigned to a card_id.
**<< Note >>**
> You must answer the following question:
How does your company expect to use and benefit from **your model**.
###### [Go to top](#top)
<a id="11"></a> <br>
## 5- Select Framework
After problem definition and problem feature, we should select our **framework** to solve the **problem**.
What we mean by the framework is that the programming languages you use and by what modules the problem will be solved.
###### [Go to top](#top)
<a id="12"></a> <br>
## 5-2 Import
```
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
from pandas import get_dummies
import matplotlib as mpl
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib
import warnings
import sklearn
import scipy
import numpy
import json
import sys
import csv
import os
```
<a id="13"></a> <br>
## 5-3 version
```
print('matplotlib: {}'.format(matplotlib.__version__))
print('sklearn: {}'.format(sklearn.__version__))
print('scipy: {}'.format(scipy.__version__))
print('seaborn: {}'.format(sns.__version__))
print('pandas: {}'.format(pd.__version__))
print('numpy: {}'.format(np.__version__))
print('Python: {}'.format(sys.version))
```
<a id="14"></a> <br>
## 5-4 Setup
A few tiny adjustments for better **code readability**
```
sns.set(style='white', context='notebook', palette='deep')
warnings.filterwarnings('ignore')
sns.set_style('white')
%matplotlib inline
```
<a id="15"></a> <br>
## 6- EDA
In this section, you'll learn how to use graphical and numerical techniques to begin uncovering the structure of your data.
* Which variables suggest interesting relationships?
* Which observations are unusual?
* Analysis of the features!
By the end of the section, you'll be able to answer these questions and more, while generating graphics that are both insightful and beautiful. then We will review analytical and statistical operations:
1. Data Collection
1. Visualization
1. Data Cleaning
1. Data Preprocessing
<img src="http://s9.picofile.com/file/8338476134/EDA.png">
###### [Go to top](#top)
<a id="16"></a> <br>
## 6-1 Data Collection
**Data collection** is the process of gathering and measuring data, information or any variables of interest in a standardized and established manner that enables the collector to answer or test hypothesis and evaluate outcomes of the particular collection.[techopedia]
I start Collection Data by the training and testing datasets into **Pandas DataFrames**.
###### [Go to top](#top)
```
train = pd.read_csv('../input/train.csv', parse_dates=["first_active_month"] )
test = pd.read_csv('../input/test.csv' ,parse_dates=["first_active_month"] )
merchants=pd.read_csv('../input/merchants.csv')
```
**<< Note 1 >>**
* Each **row** is an observation (also known as : sample, example, instance, record).
* Each **column** is a feature (also known as: Predictor, attribute, Independent Variable, input, regressor, Covariate).
###### [Go to top](#top)
## 6-1-1 data_dictionary Analysis
Elo Provides a excel file to describe about data. It has four sheet and we have just read them with below code:
```
data_dictionary_train=pd.read_excel('../input/Data_Dictionary.xlsx',sheet_name='train')
data_dictionary_history=pd.read_excel('../input/Data_Dictionary.xlsx',sheet_name='history')
data_dictionary_new_merchant_period=pd.read_excel('../input/Data_Dictionary.xlsx',sheet_name='new_merchant_period')
data_dictionary_merchant=pd.read_excel('../input/Data_Dictionary.xlsx',sheet_name='merchant')
```
### 6-1-1-1 data_dictionary_train
```
data_dictionary_train.head(10)
# what we know about train:
```
### 6-1-1-2 data_dictionary_history
```
data_dictionary_history.head(10)
# what we know about history:
```
### 6-1-1-3 data_dictionary_new_merchant_period
```
data_dictionary_new_merchant_period.head(10)
# what we know about new_merchant_period:
```
### 6-1-1-4 data_dictionary_merchant:
```
data_dictionary_merchant.head(30)
# what we know about merchant:
```
## 6-1-2 Train Analysis
```
train.sample(1)
test.sample(1)
```
Or you can use others command to explorer dataset, such as
```
train.tail(1)
```
<a id="17"></a> <br>
## 6-1-1 Features
Features can be from following types:
* numeric
* categorical
* ordinal
* datetime
* coordinates
Find the type of features in **Qoura dataset**?!
For getting some information about the dataset you can use **info()** command.
```
print(train.info())
print(test.info())
```
<a id="18"></a> <br>
## 6-1-2 Explorer Dataset
1- Dimensions of the dataset.
2- Peek at the data itself.
3- Statistical summary of all attributes.
4- Breakdown of the data by the class variable.
Don’t worry, each look at the data is **one command**. These are useful commands that you can use again and again on future projects.
###### [Go to top](#top)
```
# shape for train and test
print('Shape of train:',train.shape)
print('Shape of test:',test.shape)
#columns*rows
train.size
```
After loading the data via **pandas**, we should checkout what the content is, description and via the following:
```
type(train)
type(test)
train.describe()
```
To pop up 5 random rows from the data set, we can use **sample(5)** function and find the type of features.
```
train.sample(5)
```
<a id="19"></a> <br>
## 6-2 Data Cleaning
When dealing with real-world data, dirty data is the norm rather than the exception. We continuously need to predict correct values, impute missing ones, and find links between various data artefacts such as schemas and records. We need to stop treating data cleaning as a piecemeal exercise (resolving different types of errors in isolation), and instead leverage all signals and resources (such as constraints, available statistics, and dictionaries) to accurately predict corrective actions.
The primary goal of data cleaning is to detect and remove errors and **anomalies** to increase the value of data in analytics and decision making. While it has been the focus of many researchers for several years, individual problems have been addressed separately. These include missing value imputation, outliers detection, transformations, integrity constraints violations detection and repair, consistent query answering, deduplication, and many other related problems such as profiling and constraints mining.[4]
###### [Go to top](#top)
How many NA elements in every column!!
Good news, it is Zero!
To check out how many null info are on the dataset, we can use **isnull().sum()**.
```
train.isnull().sum()
```
But if we had , we can just use **dropna()**(be careful sometimes you should not do this!)
```
# remove rows that have NA's
print('Before Droping',train.shape)
train = train.dropna()
print('After Droping',train.shape)
```
We can get a quick idea of how many instances (rows) and how many attributes (columns) the data contains with the shape property.
To print dataset **columns**, we can use columns atribute.
```
train.columns
```
You see number of unique item for Target with command below:
```
train_target = train['target'].values
np.unique(train_target)
```
To check the first 5 rows of the data set, we can use head(5).
```
train.head(5)
```
Or to check out last 5 row of the data set, we use tail() function.
```
train.tail()
```
To give a **statistical summary** about the dataset, we can use **describe()**
```
train.describe()
```
As you can see, the statistical information that this command gives us is not suitable for this type of data
**describe() is more useful for numerical data sets**
<a id="20"></a> <br>
## 6-3 Data Preprocessing
**Data preprocessing** refers to the transformations applied to our data before feeding it to the algorithm.
Data Preprocessing is a technique that is used to convert the raw data into a clean data set. In other words, whenever the data is gathered from different sources it is collected in raw format which is not feasible for the analysis.
there are plenty of steps for data preprocessing and we just listed some of them in general(Not just for Quora) :
1. removing Target column (id)
1. Sampling (without replacement)
1. Making part of iris unbalanced and balancing (with undersampling and SMOTE)
1. Introducing missing values and treating them (replacing by average values)
1. Noise filtering
1. Data discretization
1. Normalization and standardization
1. PCA analysis
1. Feature selection (filter, embedded, wrapper)
1. Etc.
What methods of preprocessing can we run on Quora?!
###### [Go to top](#top)
**<< Note 2 >>**
in pandas's data frame you can perform some query such as "where"
```
train.where(train ['target']==1).count()
```
As you can see in the below in python, it is so easy perform some query on the dataframe:
```
train[train['target']<-32].head(5)
train[train['target']==1].head(5)
train.feature_1.unique()
train.feature_2.unique()
train.feature_3.unique()
train.first_active_month.unique()
```
**<< Note >>**
>**Preprocessing and generation pipelines depend on a model type**
<a id="23"></a> <br>
## 6-4 Data Visualization
**Data visualization** is the presentation of data in a pictorial or graphical format. It enables decision makers to see analytics presented visually, so they can grasp difficult concepts or identify new patterns.
> * Two** important rules** for Data visualization:
> 1. Do not put too little information
> 1. Do not put too much information
###### [Go to top](#top)
<a id="63"></a> <br>
## 6-4-1 Histogram
```
train["target"].hist();
# histograms
train.hist(figsize=(15,20))
plt.figure()
f,ax=plt.subplots(1,2,figsize=(20,10))
train[train['feature_3']==0].target.plot.hist(ax=ax[0],bins=20,edgecolor='black',color='red')
ax[0].set_title('feature_3= 0')
x1=list(range(0,85,5))
ax[0].set_xticks(x1)
train[train['feature_3']==1].target.plot.hist(ax=ax[1],color='green',bins=20,edgecolor='black')
ax[1].set_title('feature_3= 1')
x2=list(range(0,85,5))
ax[1].set_xticks(x2)
plt.show()
f,ax=plt.subplots(1,2,figsize=(18,8))
train['feature_3'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],shadow=True)
ax[0].set_title('feature_3')
ax[0].set_ylabel('')
sns.countplot('feature_3',data=train,ax=ax[1])
ax[1].set_title('feature_3')
plt.show()
f,ax=plt.subplots(1,2,figsize=(18,8))
train[['feature_3','feature_2']].groupby(['feature_3']).mean().plot.bar(ax=ax[0])
ax[0].set_title('Survived vs feature_2')
sns.countplot('feature_3',hue='feature_2',data=train,ax=ax[1])
ax[1].set_title('feature_3:feature')
plt.show()
```
## 6-4-2 distplot
```
sns.distplot(train['target'])
```
## 6-4-3 violinplot
```
sns.violinplot(data=train, x="feature_1", y='target')
```
## 6-2-4 Scatter plot
Scatter plot Purpose to identify the type of relationship (if any) between two quantitative variables
```
# Modify the graph above by assigning each species an individual color.
g = sns.FacetGrid(train, hue="feature_3", col="feature_2", margin_titles=True,
palette={1:"blue", 0:"red"} )
g=g.map(plt.scatter, "first_active_month", "target",edgecolor="w").add_legend();
```
## 6-4-5 Box
In descriptive statistics, a box plot or boxplot is a method for graphically depicting groups of numerical data through their quartiles. Box plots may also have lines extending vertically from the boxes (whiskers) indicating variability outside the upper and lower quartiles, hence the terms box-and-whisker plot and box-and-whisker diagram.[wikipedia]
```
sns.boxplot(x="feature_3", y="feature_2", data=test )
plt.show()
```
<a id="24"></a> <br>
## 7- Apply Learning
How to understand what is the best way to solve our problem?!
The answer is always "**It depends**." It depends on the **size**, **quality**, and **nature** of the **data**. It depends on what you want to do with the answer. It depends on how the **math** of the algorithm was translated into instructions for the computer you are using. And it depends on how much **time** you have. Even the most **experienced data scientists** can't tell which algorithm will perform best before trying them.(see a nice [cheatsheet](https://github.com/mjbahmani/10-steps-to-become-a-data-scientist/blob/master/cheatsheets/microsoft-machine-learning-algorithm-cheat-sheet-v7.pdf) for this section)
Categorize the problem
The next step is to categorize the problem. This is a two-step process.
1. **Categorize by input**:
1. If you have labelled data, it’s a supervised learning problem.
1. If you have unlabelled data and want to find structure, it’s an unsupervised learning problem.
1. If you want to optimize an objective function by interacting with an environment, it’s a reinforcement learning problem.
1. **Categorize by output**.
1. If the output of your model is a number, it’s a regression problem.
1. If the output of your model is a class, it’s a classification problem.
1. If the output of your model is a set of input groups, it’s a clustering problem.
1. Do you want to detect an anomaly ? That’s anomaly detection
1. **Understand your constraints**
1. What is your data storage capacity? Depending on the storage capacity of your system, you might not be able to store gigabytes of classification/regression models or gigabytes of data to clusterize. This is the case, for instance, for embedded systems.
1. Does the prediction have to be fast? In real time applications, it is obviously very important to have a prediction as fast as possible. For instance, in autonomous driving, it’s important that the classification of road signs be as fast as possible to avoid accidents.
1. Does the learning have to be fast? In some circumstances, training models quickly is necessary: sometimes, you need to rapidly update, on the fly, your model with a different dataset.
1. **Find the available algorithms**
1. Now that you a clear understanding of where you stand, you can identify the algorithms that are applicable and practical to implement using the tools at your disposal. Some of the factors affecting the choice of a model are:
1. Whether the model meets the business goals
1. How much pre processing the model needs
1. How accurate the model is
1. How explainable the model is
1. How fast the model is: How long does it take to build a model, and how long does the model take to make predictions.
1. How scalable the model is
<a id="25"></a> <br>
# 8- Conclusion
This kernel is not completed yet , I have tried to cover all the parts related to the process of **Elo problem** with a variety of Python packages and I know that there are still some problems then I hope to get your feedback to improve it.
you can Fork and Run this kernel on **Github**:
> ###### [ GitHub](https://github.com/mjbahmani/10-steps-to-become-a-data-scientist)
#### The kernel is not completed and will be updated soon !!!
| github_jupyter |
# Index
- B*Tree 인덱스는 나뭇잎으로 무성한 나무를 뒤집어 놓은 듯한 모습
- Root에서 Leaf 블럭까지의 거리를 깊이 (Height) 라고 부르며, 인덱스의 반복 탐색시 성능에 영향을 미치는 요소
- Root / Branch 블럭은 하위 노드들의 데이터 값 범위를 나타내는 Key 값과, 키 값에 해당하는 블록 주소 정보를 가지고 있음
- Leaf 블럭은 인덱스 키 값을 가지고, 그 키값에 해당하는 테이블 레코드를 찾아갈 때 필요한 주소 정보(row id)를 가짐
- 같은 키 값일때 row id순으로 정렬
- 인덱스 키(key) 값 순으로 정렬되어 있어 Range Scan이 가능하고 정방향/역방향 (ASC/DESC) 스캔이 가능한 양방향 연결 리스트 구조!
- **Range 범위가 넓은 경우엔, Index를 타는 것보다 Full Scan이 빠른 경우도 있음!**
- Random IO : 블락 1개에서 데이터 1개 접근
- Sequential IO : 블락 1개에서 데이터 여러개 접근
## 1.1 목표 ( 인덱스 => 정렬)
1. 수직적 Search 효율화
2. 수평적 탐색 선택도 최대화
3. 테이블 Random Access ( Random IO ) 최소화
- 수직적 Search : 수평적 탐색을 위한 시작 지점을 찾는 과정
- 수평적 탐색 : Leaf 블럭에 저장된 레코드끼리 연결된 순서에 따른 스캔
* 비용 : 테이블 Random IO > 수직적 Search > 수평적 탐색
## 1.2 인덱스의 구조
1. Root Node : 가장 상위 노드 / 하위으 Branch Node 수만큼 Row를 가지고 있음
2. Branch Node : Root와 Leaf의 연결 고리 / 자기 하위의 LEaf Node 수만큼 Row를 가지고 있음
3. Leaf Node : Key + RowID로 구성 / Key 순서대로 정렬되어 있고, 이전 이후 Leaf의 Chain
### 수직적 탐색
- Root - Branch - Leaf
- 읽고자 하는 시작점 검색
- Random IO
### 수평적 탐색
- Leaf Block의 시작점부터 종료점까지
- Sequential IO
## 1.3 인덱스의 기본 원리
- 인덱스 사용이 불가능하거나 범위 스캔(Range Scan)이 불가능한 경우
1. 인덱스 컬럼의 가공(좌변 가공) : 좌변을 가공하지 않고 우변을 가공하거나 사용합니다
> SELECT * FROM 업체 WHERE substr(업체명, 1, 2) = '대한'; (X)
> SELECT * FROM 업체 WHERE 업체명 like '대한%'; (O)
> SELECT * FROM 사원 WHERE 월급여 x 12 = 50000000; (X)
> SELECT * FROM 사원 WHERE 월급여 = 50000000 / 12; (O)
> SELECT * FROM 주문 WHERE to_char(일시, 'yyyymmdd') = :dt (X)
> SELECT * FROM 주문 WHERE 일시 >= to_date(:dt, 'yyyymmdd') and 일시 < to_date(:dt, 'yyyymmdd')+1 (O)
> and so on..
2. Null의 검색 : Null 검색은 인덱스를 탈 수 없습니다
> SELECT * FROM 고객 WHERE 고객번호 IS NULL (X)
3. 묵시적 형변환 : 컬럼과 상수의 Data Type이 상시할 경우. 문자를 숫자 변환 후 비교! but A001 같이 변환 불가능할 경우 에러 발생
> SELECT * FROM 고객 WHERE 고객번호 = 100 (X)
## 1.4 다양한 인덱스 스캔 방식
### Index Range Scan
- between, unique값이 아닌 경우 사용-!
- 인덱스를 타는 대부분의 스캔 방식 중 99%가 Range Scan
- 그러나 항상 빠른 속도를 보장하진 않는다 ( 범위가 넓으면 full scan이 나음 )
- 인덱스 스캔하는 범위를 얼마나 줄일 수 있는가?
- 테이블로 액세스하는 회수를 얼만큼 줄일 수 있는가?
- SQL 튜닝 핵심 원리
- 인덱스를 구성하는 선두 컬럼을 조건절에 사용
> 인덱스 : 부서코드 + 이름
> SELECT * FROM 사원 WHERE 이름 = '홍길동' ( X ) => 부서코드가 정렬이 되어있지 않음..!
> 인덱스 : 이름 + 부서코드
> SELECT * FROM 사원 WHERE 이름 = '홍길동' ( O ) => 이름이 정렬되어 있음!
- 진행 순서는 같은 길이라면 위 -> 아래 / 우측 -> 좌측으로 진행
<img src = 'http://www.dbguide.net/publishing/img/knowledge/SQL_331.jpg' />
### Index Range Scan Descending
- 인덱스를 뒤에서부터 앞쪽으로 스캔
- 나머지는 Index Range Scan과 동일
<img src='http://www.dbguide.net/publishing/img/knowledge/SQL_338.jpg' />
### Index Full Scan
- 적당한 인덱스가 없을 경우 Table Full Scan 수행
- 조회 조건의 인덱스가 있지만 선두 컬럼이 아닌 경우, 옵티마이저가 인덱스 활용시 이익이 있다고 판단할 경우 사용
- 많다 적다의 판단은 Trace를 떠보고 결정
- 최종 결과 값이 적을 경우는 Full Table Scan보다 Indexl Full Scan이 효율적
- 최종 결과 값이 많을 경우는 Full Table Scan이 효율적
<img src ='http://www.dbguide.net/publishing/img/knowledge/SQL_332.jpg' />
### Index Unique Scan
- 수직적 스캔만 발생 ( 수평적 탐색은 없음 )
- Unique 인덱스일 경우 사용
- = 조건일 경우만 사용! between조건이 들어가면 당연히 수평적 탐색을 수행합니다
<img src='http://www.dbguide.net/publishing/img/knowledge/SQL_335.jpg' />
### Index Skip Scan
- 조회 조건이 인덱스 선두 컬럼이 아니며, 인덱스 선두 컬럼의 Distinct가 매우 낮을 때 사용 (=데이터 값의 개수가 적어서 정렬할 수 있음)
- 인덱스 선두 컬럼이 between, like, 부등호일 때도 사용 가능
<img src='http://www.dbguide.net/publishing/img/knowledge/SQL_336.jpg' />
### Index Fast Full Scan
- 전체 Index를 Full Scan
- Multi-Block IO
- 파라미터의 db_file_multiblock_read_count 개수만큼 한번에 read!
- Index의 논리적 순서와 무관하게 물리적 순서대로 Read
- 속도가 빠름
- 결과는 인덱스 키 컬럼의 순서와 무관
- 디스크에 인접한 것들을 뭉뜩그려서 가져옴
<img src='http://www.dbguide.net/publishing/img/knowledge/SQL_337.jpg' />
# Oracle DBMS 구조
- 오라클 DBMS는 database와 instance로 나뉩니다
<img src ="http://cfile22.uf.tistory.com/image/273AA23553449D50205700" />
## 1) database
1. datafiles
2. Control files : 데이터베이스 전체의 정보를 지니고 있는 Oracle server Instance 를 open 할 때 두번 째 단계인 mount 단계로 가기 위해서 필요한 파일(Instance open 순서: nomount -> mount -> open)
3. Redo Log files : 데이터의 변경이 생길 때 마다 장애를 대비해 변경되기 전과 후의 내용들 기록해 두는 파일 (Redo log buffer 에서 내려쓰는 log 파일)
## 2) instance
#### 1. background
(1) CKPT : 체크포인트(CKPT)는 LGWR 프로세스에 의해 활동하며 사용자가 COMMIT문을 실행할 때마다 오라클 서버가 관리하는 시스템 변경번호(SYSTEM CHANGE NUMBER) 및 데이터베이스의 상태정보를 컨트롤 파일과 데이터 파일에 저장하는 작업을 하게됩니다. 또한, CKPT 프로세스가 발생하면 연속적으로 DBWR 프로세스가 작업을 수행
(2) LGWR : 사용자가 실행한 SQL문을 커밋(Commit)하면 화면에 '커밋이 성공적이다'라는 메시지를 보여줍니다. 이때 커밋했던 모든 작업내용을 리두로그 파일에 백업 하게되는데 이러한 작업을 로그 기록기(LGWR)가 처리해 줍니다. 모든 작업내역을 리두로그 파일에 저장하는 이유는 갑작스런 시스템의 다운 또는 데이터베이스의 다운 시 처리하고 있던 모든 작업내용을 다시 복구하기 위함!
(3) DBWR : 데이터베이스 기록기(DBWR)는 사용자가 실행한 SQL문에 의해 데이터의 변경내역(입력, 수정, 삭제)을 테이블에 저장하는 작업을 수행합니다. 예를 들어, 사용자가 UPDATE문을 실행하고 커밋(Commit)문을 실행할 때 테이블에 데이터를 저장하는 작업을 데이터베이스 기록기 프로세스가 처리합니다. 데이터베이스 기록기(DBWR)와 로그 기록기(LGWR)는 데이터베이스를 시작하면 자동으로 생성되고 종료하면 없어지는 백그라운드 프로세스
(4) SMON : 시스템 모니터(SMON)는 백그라운드 프로세스와 데이터베이스 메모리 영역의 상태를 감시하며 데이터베이스가 다운된 후 다시 시작될 때 자동적인 복구작업을 수행
(5) PMON : 사용자들이 데이터베이스에 접속하면 한번의 접속 요구마다 사용자 프로세스가 하나씩 생성됩니다. 프로세스 모니터(PMON)는 이러한 사용자 프로세스들의 상태를 감시합니다. 만약 어떤 사용자 프로세스에 오류가 발생하거나(예를 들어, SQL*PLUS에서 SQL문을 실행하는 중에 윈도우를 닫게 된다면) 또는 사용자 프로세스가 비정상적으로 종료된 경우 모든 작업을 자동적으로 롤백(Rollback) 시켜줍니다.
#### 2. SGA
(1) Shared Area : 다른 사용자들과 어떤 대상을 공유하기 위해 만들어진 곳이다. 여러개의 공간으로 나누어 진다.(Library Cache / Data Dictionary Cache / Server Result Cache / Reserved Pool)
(2) Data Buffer Cache : 실제 데이터의 조회와 변경 등의 작업이 일어나는 공간으로 사용자가 조회하거나 변경하려는 모든 데이터는 이 곳에 있어야만 한다. 즉, 파일에 저장되어 있는 어떤 데이터를 조회하거나 변경하려면, 해당 데이터가 있는 블록을 복사해서 이 곳으로 가져와서 작업을 진행한다. 이렇게 하는 이유는 디스크에서 작업하는 속도와 메모리에서 작업하는 속도를 비교했을 때 메모리가 훨씬 빠르기 때문
(3) Redo Log Buffer : DDL이나 DML 이 실행될 경우 (즉, 데이터의 변경이 생길 경우) , 해당 변경 내용을 기록해 두는 역할(장애시 복구하기 위함)
## 3) 기타
1. PGA ( Program Global Area ): SGA 가 공유 메모리라면, PGA 는 각 process 들이 개별적으로 사용하는 메모리 공간이다. 즉, 모든 server process 나 background process 들은 전부 각각의 PGA 를 가지고 있다.
2. Server Process
# Reference
- [참고 블로그](http://ann-moon.tistory.com/34)
| github_jupyter |
```
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
import keras
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
import matplotlib.pyplot as plt
def char_to_vocab (sentence):
vocabulary = ['а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я',
'А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У','Ф','Х','Ц','Ч','Ш','Щ','Ъ','Ы','Ь','Э','Ю','Я',
'!','@','#','$','%','^','&','*','(',')',':',';','/',',','.','%','№','?','~','-','+','=',' ',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
result = []
for char in sentence:
if char in vocabulary:
result.append(vocabulary.index(char)+1)
result = np.array(result)
#encoded = one_hot(sentence)
if len(result)<500:
result = np.concatenate((result, np.zeros(500-result.shape[0])))
if len(result)>500:
result = result[:500]
return result
def all_to_vocab(comments):
X_train_new = []
for sentence in tqdm(comments):
X_train_new.append(char_to_vocab(sentence))
X_train_new = np.array(X_train_new)
return X_train_new
def predict(model, X, y, bins = 50):
y_pred = model.predict(X)
y_pred = np.clip(y_pred, 1, 5)
mse = mean_squared_error(y, y_pred)
mae = mean_absolute_error(y, y_pred)
medianae = median_absolute_error(y, y_pred)
r2 = r2_score(y, y_pred)
print('MSE:{}; MAE:{}; MedianAE:{}; R2 Score:{}.'.format(mse, mae, medianae, r2))
plt.figure(figsize=(20,5))
plt.plot(y_pred[::bins])
plt.plot(y[::bins])
plt.show()
#загрузка данных и модели. Для загрузки своих данных введите путь до вашего csv файла (в нем должны содержаться колонки с названиями reting, comment)
data = pd.read_csv('data/reviews_test.csv')
X_test = data.comment.values
y_test = data.reting.values
X_test = all_to_vocab(X_test)
model = keras.models.load_model('models/NN_1_score_1.035-0.55')
# на данном этапе выводятся результаты, для видеокарты с 4ГБ памяти максимальное количество коментариев 3000!
predict(model, X_test, y_test)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/Serbeld/Practicas-de-Python/blob/master/Matriz4x4_10.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# Empresa Yogur
# Funcion que crea Matriz_de_frutas
def Matriz_de_frutas():
#Fresa, Mora, Melocoton y Wiki
#Primer mes
#Ingresa el numero de frutas a comprar el primer mes
print("Ingrese las frutas compradas el primer mes")
print("Ingrese el numero de Fresas compradas:")
fresa_1 = int(input())
print("Ingrese el numero de Moras compradas:")
mora_1 = int(input())
print("Ingrese el numero de Melocotones comprados:")
melocoton_1 = int(input())
print("Ingrese el numero de Wikis comprados:")
kiwi_1 = int(input())
print()
#Segundo mes
#Ingresa el numero de frutas a comprar el segundo mes
print("Ingrese las frutas compradas el segundo mes")
print("Ingrese el numero de Fresas compradas:")
fresa_2 = int(input())
print("Ingrese el numero de Moras compradas:")
mora_2 = int(input())
print("Ingrese el numero de Melocotones comprados:")
melocoton_2 = int(input())
print("Ingrese el numero de Wikis comprados:")
kiwi_2 = int(input())
print()
#Tercer mes
#Ingresa el numero de frutas a comprar el tercer mes
print("Ingrese las frutas compradas el tercer mes")
print("Ingrese el numero de Fresas compradas:")
fresa_3 = int(input())
print("Ingrese el numero de Moras compradas:")
mora_3 = int(input())
print("Ingrese el numero de Melocotones comprados:")
melocoton_3 = int(input())
print("Ingrese el numero de Wikis comprados:")
kiwi_3 = int(input())
print()
#Cuarto mes
#Ingresa el numero de frutas a comprar el cuarto mes
print("Ingrese las frutas compradas el cuarto mes")
print("Ingrese el numero de Fresas compradas:")
fresa_4 = int(input())
print("Ingrese el numero de Moras compradas:")
mora_4 = int(input())
print("Ingrese el numero de Melocotones comprados:")
melocoton_4 = int(input())
print("Ingrese el numero de Wikis comprados:")
kiwi_4 = int(input())
print()
#Se construye la matris de frutas
matriz_de_frutas = [[fresa_1, mora_1, melocoton_1, kiwi_1],
[fresa_2, mora_2, melocoton_2, kiwi_2],
[fresa_3, mora_3, melocoton_3, kiwi_3],
[fresa_4, mora_4, melocoton_4, kiwi_4]]
return(matriz_de_frutas)
#Funcion para hallar los costos de las frutas
def costos_por_fruta(Matriz_de_frutas):
#Precio de la fruta por kilogramo
costo_por_fruta = 6000
#Se multiplica todos los elementos del numero de kilos de fruta por su costo
for filas in range(0,len(Matriz_de_frutas)):
for columnas in range(0,len(Matriz_de_frutas)):
Matriz_de_frutas[filas][columnas] = Matriz_de_frutas[filas][columnas] * costo_por_fruta
return(Matriz_de_frutas)
#Funcion para hallar el dinero promedio gastado en frutas en los 4 meses anteriores
def promedio_costos(matriz_de_costos):
#Acumulador
promedio = 0
#Contador
contador = 0
#Se multiplica todos los elementos del numero de kilos de fruta por su costo
for filas in range(0,len(matriz_de_costos)):
for columnas in range(0,len(matriz_de_costos)):
promedio = promedio + matriz_de_costos[filas][columnas]
contador = contador + 1
promedio = promedio / contador
return(promedio)
################################################################################
#Se utiliza la funcion matriz de frutas
matriz_frutas = Matriz_de_frutas()
#Imprime la matriz de frutas fila por fila de la matriz
print("Matriz de kilogramos por fruta con respecto a los 4 meses evaluados")
print("Fresa, Mora, Melocoton, Kiwi")
print(matriz_frutas[0][:])
print(matriz_frutas[1][:])
print(matriz_frutas[2][:])
print(matriz_frutas[3][:])
print()
#Se evaluan los costos de la matriz de frutas
costos = costos_por_fruta(matriz_frutas)
#Imprime la matriz de frutas fila por fila de la matriz
print("Matriz de costos por fruta con respecto a los 4 meses evaluados")
print("Fresa, Mora, Melocoton, Kiwi")
print(costos[0][:])
print(costos[1][:])
print(costos[2][:])
print(costos[3][:])
print()
#Se evaluan los costos promedios de toda la matriz
costos_prom = promedio_costos(costos)
#Costos promedios
print("Los costos promedios del total de frutas comprada los anteriores 4 meses fue de: ")
print(costos_prom)
```
| github_jupyter |
# Basic training functionality
```
from fastai.basic_train import *
from fastai.gen_doc.nbdoc import *
from fastai.vision import *
from fastai.distributed import *
```
[`basic_train`](/basic_train.html#basic_train) wraps together the data (in a [`DataBunch`](/basic_data.html#DataBunch) object) with a pytorch model to define a [`Learner`](/basic_train.html#Learner) object. This is where the basic training loop is defined for the [`fit`](/basic_train.html#fit) function. The [`Learner`](/basic_train.html#Learner) object is the entry point of most of the [`Callback`](/callback.html#Callback) functions that will customize this training loop in different ways (and made available through the [`train`](/train.html#train) module), notably:
- [`Learner.lr_find`](/train.html#lr_find) will launch an LR range test that will help you select a good learning rate
- [`Learner.fit_one_cycle`](/train.html#fit_one_cycle) will launch a training using the 1cycle policy, to help you train your model fast.
- [`Learner.to_fp16`](/train.html#to_fp16) will convert your model in half precision and help you launch a training in mixed precision.
```
show_doc(Learner, title_level=2)
```
The main purpose of [`Learner`](/basic_train.html#Learner) is to train `model` using [`Learner.fit`](/basic_train.html#Learner.fit). After every epoch, all *metrics* will be printed, and will also be available to callbacks.
The default weight decay will be `wd`, which will be handled using the method from [Fixing Weight Decay Regularization in Adam](https://arxiv.org/abs/1711.05101) if `true_wd` is set (otherwise it's L2 regularization). If `bn_wd` is False then weight decay will be removed from batchnorm layers, as recommended in [Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour](https://arxiv.org/abs/1706.02677). You can ensure that batchnorm layer learnable params are trained even for frozen layer groups, by enabling `train_bn`.
To use [discriminative layer training](#Discriminative-layer-training) pass an [`nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) for each layer group to be optimized with different settings.
Any model files created will be saved in `path`/`model_dir`.
You can pass a list of [`callbacks`](/callbacks.html#callbacks) that you have already created, or (more commonly) simply pass a list of callback functions to `callback_fns` and each function will be called (passing `self`) on object initialization, with the results stored as callback objects. For a walk-through, see the [training overview](/training.html) page. You may also want to use an `application` to fit your model, e.g. using the [`create_cnn`](/vision.learner.html#create_cnn) method:
```
path = untar_data(URLs.MNIST_SAMPLE)
data = ImageDataBunch.from_folder(path)
learn = create_cnn(data, models.resnet18, metrics=accuracy)
learn.fit(1)
```
### Model fitting methods
```
show_doc(Learner.fit)
```
Uses [discriminative layer training](#Discriminative-layer-training) if multiple learning rates or weight decay values are passed. To control training behaviour, use the [`callback`](/callback.html#callback) system or one or more of the pre-defined [`callbacks`](/callbacks.html#callbacks).
```
show_doc(Learner.fit_one_cycle)
```
Uses the [`OneCycleScheduler`](/callbacks.one_cycle.html#OneCycleScheduler) callback.
```
show_doc(Learner.lr_find)
```
Runs the learning rate finder defined in [`LRFinder`](/callbacks.lr_finder.html#LRFinder), as discussed in [Cyclical Learning Rates for Training Neural Networks](https://arxiv.org/abs/1506.01186).
### See results
```
show_doc(Learner.get_preds)
show_doc(Learner.validate)
show_doc(Learner.show_results)
show_doc(Learner.predict)
show_doc(Learner.pred_batch)
show_doc(Learner.interpret, full_name='interpret')
jekyll_note('This function only works in the vision application.')
```
### Model summary
```
show_doc(Learner.summary)
```
### Test time augmentation
```
show_doc(Learner.TTA, full_name = 'TTA')
```
Applies Test Time Augmentation to `learn` on the dataset `ds_type`. We take the average of our regular predictions (with a weight `beta`) with the average of predictions obtained through augmented versions of the training set (with a weight `1-beta`). The transforms decided for the training set are applied with a few changes `scale` controls the scale for zoom (which isn't random), the cropping isn't random but we make sure to get the four corners of the image. Flipping isn't random but applied once on each of those corner images (so that makes 8 augmented versions total).
### Gradient clipping
```
show_doc(Learner.clip_grad)
```
### Mixed precision training
```
show_doc(Learner.to_fp16)
```
Uses the [`MixedPrecision`](/callbacks.fp16.html#MixedPrecision) callback to train in mixed precision (i.e. forward and backward passes using fp16, with weight updates using fp32), using all [NVIDIA recommendations](https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html) for ensuring speed and accuracy.
```
show_doc(Learner.to_fp32)
```
### Distributed training
```
show_doc(Learner.distributed, full_name='distributed')
```
### Discriminative layer training
When fitting a model you can pass a list of learning rates (and/or weight decay amounts), which will apply a different rate to each *layer group* (i.e. the parameters of each module in `self.layer_groups`). See the [Universal Language Model Fine-tuning for Text Classification](https://arxiv.org/abs/1801.06146) paper for details and experimental results in NLP (we also frequently use them successfully in computer vision, but have not published a paper on this topic yet). When working with a [`Learner`](/basic_train.html#Learner) on which you've called `split`, you can set hyperparameters in four ways:
1. `param = [val1, val2 ..., valn]` (n = number of layer groups)
2. `param = val`
3. `param = slice(start,end)`
4. `param = slice(end)`
If we chose to set it in way 1, we must specify a number of values exactly equal to the number of layer groups. If we chose to set it in way 2, the chosen value will be repeated for all layer groups. See [`Learner.lr_range`](/basic_train.html#Learner.lr_range) for an explanation of the `slice` syntax).
Here's an example of how to use discriminative learning rates (note that you don't actually need to manually call [`Learner.split`](/basic_train.html#Learner.split) in this case, since fastai uses this exact function as the default split for `resnet18`; this is just to show how to customize it):
```
# creates 3 layer groups
learn.split(lambda m: (m[0][6], m[1]))
# only randomly initialized head now trainable
learn.freeze()
learn.fit_one_cycle(1)
# all layers now trainable
learn.unfreeze()
# optionally, separate LR and WD for each group
learn.fit_one_cycle(1, max_lr=(1e-4, 1e-3, 1e-2), wd=(1e-4,1e-4,1e-1))
show_doc(Learner.lr_range)
```
Rather than manually setting an LR for every group, it's often easier to use [`Learner.lr_range`](/basic_train.html#Learner.lr_range). This is a convenience method that returns one learning rate for each layer group. If you pass `slice(start,end)` then the first group's learning rate is `start`, the last is `end`, and the remaining are evenly geometrically spaced.
If you pass just `slice(end)` then the last group's learning rate is `end`, and all the other groups are `end/10`. For instance (for our learner that has 3 layer groups):
```
learn.lr_range(slice(1e-5,1e-3)), learn.lr_range(slice(1e-3))
show_doc(Learner.unfreeze)
```
Sets every layer group to *trainable* (i.e. `requires_grad=True`).
```
show_doc(Learner.freeze)
```
Sets every layer group except the last to *untrainable* (i.e. `requires_grad=False`).
```
show_doc(Learner.freeze_to)
show_doc(Learner.split)
```
A convenience method that sets `layer_groups` based on the result of [`split_model`](/torch_core.html#split_model). If `split_on` is a function, it calls that function and passes the result to [`split_model`](/torch_core.html#split_model) (see above for example).
### Saving and loading models
Simply call [`Learner.save`](/basic_train.html#Learner.save) and [`Learner.load`](/basic_train.html#Learner.load) to save and load models. Only the parameters are saved, not the actual architecture (so you'll need to create your model in the same way before loading weights back in). Models are saved to the `path`/`model_dir` directory.
```
show_doc(Learner.load)
show_doc(Learner.save)
```
### Deploying your model
When you are ready to put your model in production, export the minimal state of your [`Learner`](/basic_train.html#Learner) with
```
show_doc(Learner.export)
```
Then you can load it with the following function.
```
show_doc(load_learner)
```
You can find more information and multiple examples in [this tutorial](/tutorial.inference.html)
### Other methods
```
show_doc(Learner.init)
```
Initializes all weights (except batchnorm) using function `init`, which will often be from PyTorch's [`nn.init`](https://pytorch.org/docs/stable/nn.html#torch-nn-init) module.
```
show_doc(Learner.mixup)
```
Uses [`MixUpCallback`](/callbacks.mixup.html#MixUpCallback).
```
show_doc(Learner.backward)
show_doc(Learner.create_opt)
```
You generally won't need to call this yourself - it's used to create the [`optim`](https://pytorch.org/docs/stable/optim.html#module-torch.optim) optimizer before fitting the model.
```
show_doc(Learner.dl)
show_doc(Recorder, title_level=2)
```
A [`Learner`](/basic_train.html#Learner) creates a [`Recorder`](/basic_train.html#Recorder) object automatically - you do not need to explicitly pass it to `callback_fns` - because other callbacks rely on it being available. It stores the smoothed loss, hyperparameter values, and metrics for each batch, and provides plotting methods for each. Note that [`Learner`](/basic_train.html#Learner) automatically sets an attribute with the snake-cased name of each callback, so you can access this through `Learner.recorder`, as shown below.
### Plotting methods
```
show_doc(Recorder.plot)
```
This is mainly used with the learning rate finder, since it shows a scatterplot of loss vs learning rate.
```
learn = create_cnn(data, models.resnet18, metrics=accuracy)
learn.lr_find()
learn.recorder.plot()
show_doc(Recorder.plot_losses)
```
Note that validation losses are only calculated once per epoch, whereas training losses are calculated after every batch.
```
learn.fit_one_cycle(2)
learn.recorder.plot_losses()
show_doc(Recorder.plot_lr)
learn.recorder.plot_lr(show_moms=True)
show_doc(Recorder.plot_metrics)
```
Note that metrics are only collected at the end of each epoch, so you'll need to train at least two epochs to have anything to show here.
```
learn.recorder.plot_metrics()
```
### Callback methods
You don't call these yourself - they're called by fastai's [`Callback`](/callback.html#Callback) system automatically to enable the class's functionality.
```
show_doc(Recorder.on_backward_begin)
show_doc(Recorder.on_batch_begin)
show_doc(Recorder.on_epoch_end)
show_doc(Recorder.on_train_begin)
```
### Inner functions
The following functions are used along the way by the [`Recorder`](/basic_train.html#Recorder) or can be called by other callbacks.
```
show_doc(Recorder.add_metrics)
show_doc(Recorder.add_metric_names)
show_doc(Recorder.format_stats)
```
## Module functions
Generally you'll want to use a [`Learner`](/basic_train.html#Learner) to train your model, since they provide a lot of functionality and make things easier. However, for ultimate flexibility, you can call the same underlying functions that [`Learner`](/basic_train.html#Learner) calls behind the scenes:
```
show_doc(fit)
```
Note that you have to create the `Optimizer` yourself if you call this function, whereas [`Learn.fit`](/basic_train.html#fit) creates it for you automatically.
```
show_doc(train_epoch)
```
You won't generally need to call this yourself - it's what [`fit`](/basic_train.html#fit) calls for each epoch.
```
show_doc(validate)
```
This is what [`fit`](/basic_train.html#fit) calls after each epoch. You can call it if you want to run inference on a [`DataLoader`](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) manually.
```
show_doc(get_preds)
show_doc(loss_batch)
```
You won't generally need to call this yourself - it's what [`fit`](/basic_train.html#fit) and [`validate`](/basic_train.html#validate) call for each batch. It only does a backward pass if you set `opt`.
## Other classes
```
show_doc(LearnerCallback, title_level=3)
show_doc(RecordOnCPU, title_level=3)
```
## Undocumented Methods - Methods moved below this line will intentionally be hidden
```
show_doc(Learner.tta_only)
show_doc(Learner.TTA)
show_doc(RecordOnCPU.on_batch_begin)
```
## New Methods - Please document or move to the undocumented section
| github_jupyter |
# Python Developers Survey 2017
## Exploratory Data Analysis
Data source: [Python Developers Survey 2017](https://www.jetbrains.com/research/python-developers-survey-2017/)
This notebook demonstrates how the simple summary techniques we've learned in the [workshop](https://jenfly.github.io/pydata-intro-workshop/) can help you navigate and analyze a large CSV file. In this example, we will analyze responses to the survey questions "What do you use Python for?" and "What do you use Python for *the most*?"
- The DataFrame attributes `shape`, `dtypes` and `columns` will help us quickly find and extract the columns of interest from a CSV file with a whopping **162 columns**!
This example also demonstrates other handy techniques we learned in the workshop, such as:
- Applying string methods to parse information from text data
- Counting the unique values in a column with the `value_counts` method
- Using a filter Series to extract a subset of data
- Computing sums along rows and columns of a DataFrame
### Initial Setup
```
# Import libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Display graphs inline
%matplotlib inline
# Use styles from the Seaborn library to make graphs look nicer
sns.set()
```
### Load Data
#### Read the CSV file into a DataFrame
```
survey = pd.read_csv('data/pythondevsurvey2017_raw_data.csv')
survey.head()
```
#### How big is our DataFrame?
```
survey.shape
```
Yikes! The data has 9506 rows (i.e. 9506 total respondents to the survey) and 162 columns. Trying to make sense of such a huge number of columns in Excel would likely be an unwieldy and unpleasant task.
Let's save the number of respondents to a variable so we can use it later:
```
n_respondents = survey.shape[0]
n_respondents
```
### Data Columns
Let's figure what the heck is in all these columns. We can use the `dtypes` attribute to get the name and data type of each column. If we simply display `survey.dtypes` in the cell below, it will only show the first 30 rows and last 30 rows, with `...` in between.
- We could tinker with some settings by running the code `pd.set_option('display.max_rows', 1000)` or using other solutions described [here](https://stackoverflow.com/questions/19124601/is-there-a-way-to-pretty-print-the-entire-pandas-series-dataframe), or we could use a `for` loop to print the items in `dtypes` in a slightly more compact way. I'll use the latter approach.
- I'm also using [f-strings](https://realpython.com/python-f-strings/), a really neat feature of Python 3 (version 3.6 and later) as a shortcut to construct a string containing the values of variables.
```
# Iterate over the items in survey.dtypes
for column, dtype in survey.dtypes.items():
# Print the data type and the column name, separated by a tab (\t)
# -- The syntax below is equivalent to: print(str(dtype) + '\t' + column)
print(f'{dtype} \t {column}')
```
Skimming through the column names, we can see there are a bunch of them ending with the string `'What do you use Python for?'`, for example:
- `'Educational purposes: What do you use Python for?'`
- `'Data analysis: What do you use Python for?'`
- etc.
These represent different multiple choice answers to the survey question "What do you use Python for?", where respondents were able to select more than one answer to the question. This kind of structure is quite common in the raw data you get from various online survey apps.
After these columns, the next column name is: `'What do you use Python for the most?'`. We'll analyze the data in this column too.
### Answers to the question: "What do you use Python for?"
#### (multiple choice survey question)
We want to extract the subset of data containing answers to this question. To do this, we need to find all the columns whose name contains the phrase 'What do you use Python for?'
- First we create a filter Series using the string method `endswith` on the column names in `survey.columns`
```
usage_filter = survey.columns.str.endswith('What do you use Python for?')
usage_filter
```
- Next, we use the filter to find the names of the relevant columns:
```
cols_usage = survey.columns[usage_filter]
cols_usage
```
What values are in each of these columns?
```
for col in cols_usage:
print(survey[col].value_counts(dropna=False))
print('\n')
```
The output above shows that the values in these columns are such that they can be stacked together into one giant Series, and then we can simply count the values in that Series using the `value_counts` method:
```
# Stack the columns into a giant Series
usages = survey[cols_usage].stack()
# Total number of answers to this survey question
n_answers = len(usages)
print(f'We have {n_answers} answers to this question, from the {n_respondents} respondents')
# Display the first 20 items in the Series
# (converting to a list first so that the output displays more nicely)
print('The first 20 answers are:')
list(usages.head(20))
# Get the counts for each value
usage_counts = usages.value_counts()
usage_counts
```
Let's calculate these totals as a fraction of the total number of respondents who answered the question "What do you use Python for?". This is a bit complicated, because the information is spread over multiple columns and we need to exclude rows where the respondent didn't answer the question at all.
First, we calculate how many answers each respondent gave to this survey question:
```
# Use the `notnull` method and sum across columns to calculate
# how many answers each respondent provided for this question
num_answers = survey[cols_usage].notnull().sum(axis=1)
num_answers.head(10)
len(num_answers)
```
Each value in the Series `num_answers` correspondents to one respondent (9506 respondents in total). A value of 0 means the respondent didn't answer this survey question. Any value greater than 0 means that the respondent provided one or more answers to the question.
```
num_answers.value_counts()
```
We can see that respondents provided up to 16 answers to the question, and the most common number of answers was 3.
Next, create a filter identifying whether or not a respondent answered the question:
```
# Create a filter to identify which respondents had more than 0 answers to this question
answered_ques = num_answers > 0
answered_ques.head()
```
To find the number of respondents who answered the question, we sum the values in the `answered_ques` Series:
```
n_ques_respondents = answered_ques.sum()
n_ques_respondents
```
Finally, we can compute the totals for each Python usage as a fraction of the number of respondents who answered the survey question:
```
usage_frac = usage_counts / n_ques_respondents
usage_frac
```
### Visualizing the Results
Let's plot the results as a horizontal bar chart. First we'll define a function to create our plot, so that we can re-use it for other plots.
```
def plot_barh(series, title=None, figsize=(7, 7)):
"""Plot a horizontal bar chart with tick labels in percent format"""
# Sort the series in ascending order, so that in the horizontal bar chart,
# the largest values are on top and smallest at the bottom
series_sorted = series.sort_values(ascending=True)
# We will use dark blue from the Seaborn default colour palette
blue = sns.color_palette()[0]
# Create a horizontal bar chart and customize the labels and formatting
ax = series_sorted.plot(kind='barh', color=blue, figsize=figsize)
ax.set_xticklabels([f'{val:.0%}' for val in ax.get_xticks()])
ax.tick_params(labelsize='large')
if title is not None:
ax.set_title(title, fontsize='large', fontweight='bold');
```
#### Create the bar chart
```
plot_barh(usage_frac, title='What do you use Python for?\n(multiple answers)')
```
### Answers to the question: "What do you use Python for *the most*?"
#### (single choice survey question)
This data is easier to analyze because all the answers to the question are in a single column. All we need to do is extract the column and use the `value_counts` method to tally up the answers. For convenience, we can also use the keyword argument `normalize=True` to compute the totals directly as a fraction of the number of respondents. *(This approach wouldn't have worked in the previous section because the data was spread over multiple columns and there were multiple choices per respondent.)*
```
column = 'What do you use Python for the most?'
primary_usage_frac = survey[column].value_counts(normalize=True)
primary_usage_frac
plot_barh(primary_usage_frac, title='What do you use Python for the most?\n(single answer)')
```
## Conclusions
Web development and data analysis are clear frontrunners as the most popular types of Python development.
- While **26% of developers indicated web development as their primary usage for Python**, 18% chose data analysis and 9% chose machine learning (a field of data science).
- Consolidating data analysis and machine learning together as a "data science" category reveals that **27% of developers use Python primarily for data science**.
- Many developers use Python for more than one type of development. 50% of all respondents indicated that they use Python for data analysis, and 49% of all respondents use Python for web development.
We can compare our results with: https://www.jetbrains.com/research/python-developers-survey-2017/#types-of-development.
- Perfect match—hurray!
| github_jupyter |
More Functions
===
Earlier we learned the most bare-boned versions of functions. In this section we will learn more general concepts about functions, such as how to use functions to return values, and how to pass different kinds of data structures between functions.
<a name="top"></a>Contents
===
- [Default argument values](#default_values)
- [Exercises](#exercises_default_values)
- [Positional arguments](#positional_arguments)
- [Exercises](#exercises_positional_arguments)
- [Keyword arguments](#keyword_arguments)
- [Mixing positional and keyword arguments](#positional_and_keyword)
- [Exercises](#exercises_keyword_arguments)
- [Accepting an arbitrary number of arguments](#arbitrary_arguments)
- [Accepting a sequence of arbitrary length](#arbitrary_sequence)
- [Accepting an arbitrary number of keyword arguments](#arbitrary_keyword_arguments)
<a name='default_values'></a>Default argument values
===
When we first introduced functions, we started with this example:
```
def thank_you(name):
# This function prints a two-line personalized thank you message.
print("\nYou are doing good work, %s!" % name)
print("Thank you very much for your efforts on this project.")
thank_you('Adriana')
thank_you('Billy')
thank_you('Caroline')
```
This function works fine, but it fails if you don't pass in a value:
```
def thank_you(name):
# This function prints a two-line personalized thank you message.
print("\nYou are doing good work, %s!" % name)
print("Thank you very much for your efforts on this project.")
thank_you('Billy')
thank_you('Caroline')
thank_you()
```
That makes sense; the function needs to have a name in order to do its work, so without a name it is stuck.
If you want your function to do something by default, even if no information is passed to it, you can do so by giving your arguments default values. You do this by specifying the default values when you define the function:
```
def thank_you(name='everyone'):
# This function prints a two-line personalized thank you message.
# If no name is passed in, it prints a general thank you message
# to everyone.
print("\nYou are doing good work, %s!" % name)
print("Thank you very much for your efforts on this project.")
thank_you('Billy')
thank_you('Caroline')
thank_you()
```
This is particularly useful when you have a number of arguments in your function, and some of those arguments almost always have the same value. This allows people who use the function to only specify the values that are unique to their use of the function.
[top](#top)
<a name='exercises_default_values'></a>Exercises
---
#### Ex 8.1: Games
- Write a function that accepts the name of a game and prints a statement such as, "I like playing chess!"
- Give the argument a default value, such as `chess`.
- Call your function at least three times. Make sure at least one of the calls includes an argument, and at least one call includes no arguments.
#### Ex 8.2: Favorite Movie
- Write a function that accepts the name of a movie, and prints a statement such as, "My favorite movie is The Princess Bride."
- Give the argument a default value, such as `The Princess Bride`.
- Call your function at least three times. Make sure at least one of the calls includes an argument, and at least one call includes no arguments.
```
# Ex 8.1 : Games
# put your code here
# Ex 8.2 : Favorite Movie
# put your code here
```
[top](#top)
<a name="positional_arguments"></a>Positional Arguments
===
Much of what you will have to learn about using functions involves how to pass values from your calling statement to the function itself. The example we just looked at is pretty simple, in that the function only needed one argument in order to do its work. Let's take a look at a function that requires two arguments to do its work.
Let's make a simple function that takes in three arguments. Let's make a function that takes in a person's first and last name, and then prints out everything it knows about the person.
Here is a simple implementation of this function:
```
def describe_person(first_name, last_name, age):
# This function takes in a person's first and last name,
# and their age.
# It then prints this information out in a simple format.
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
print("Age: %d\n" % age)
describe_person('brian', 'kernighan', 71)
describe_person('ken', 'thompson', 70)
describe_person('adele', 'goldberg', 68)
```
The arguments in this function are `first_name`, `last_name`, and `age`. These are called *positional arguments* because Python knows which value to assign to each by the order in which you give the function values. In the calling line
describe_person('brian', 'kernighan', 71)
we send the values *brian*, *kernighan*, and *71* to the function. Python matches the first value *brian* with the first argument `first_name`. It matches the second value *kernighan* with the second argument `last_name`. Finally it matches the third value *71* with the third argument `age`.
This is pretty straightforward, but it means we have to make sure to get the arguments in the right order.
If we mess up the order, we get nonsense results or an error:
```
def describe_person(first_name, last_name, age):
# This function takes in a person's first and last name,
# and their age.
# It then prints this information out in a simple format.
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
print("Age: %d\n" % age)
describe_person(71, 'brian', 'kernighan')
describe_person(70, 'ken', 'thompson')
describe_person(68, 'adele', 'goldberg')
```
This fails because Python tries to match the value 71 with the argument `first_name`, the value *brian* with the argument `last_name`, and the value *kernighan* with the argument `age`. Then when it tries to print the value `first_name.title()`, it realizes it can't use the `title()` method on an integer.
[top](#top)
<a name='exercises_positional_arguments'></a>Exercises
---
#### Ex 8.3: Favorite Colors
- Write a function that takes two arguments, a person's name and their favorite color. The function should print out a statement such as "Hillary's favorite color is blue."
- Call your function three times, with a different person and color each time.
#### Ex 8.4: Phones
- Write a function that takes two arguments, a brand of phone and a model name. The function should print out a phrase such as "iPhone 6 Plus".
- Call your function three times, with a different combination of brand and model each time.
```
# Ex 8.3 : Favorite Colors
# put your code here
# Ex 8.4 : Phones
# put your code here
```
[top](#top)
<a name='keyword_arguments'></a>Keyword arguments
===
Python allows us to use a syntax called *keyword arguments*. In this case, we can give the arguments in any order when we call the function, as long as we use the name of the arguments in our calling statement. Here is how the previous code can be made to work using keyword arguments:
```
def describe_person(first_name, last_name, age):
# This function takes in a person's first and last name,
# and their age.
# It then prints this information out in a simple format.
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
print("Age: %d\n" % age)
describe_person(age=71, first_name='brian', last_name='kernighan')
describe_person(age=70, first_name='ken', last_name='thompson')
describe_person(age=68, first_name='adele', last_name='goldberg')
```
This works, because Python does not have to match values to arguments by position. It matches the value 71 with the argument `age`, because the value 71 is clearly marked to go with that argument. This syntax is a little more typing, but it makes for very readable code.
<a name='positional_and_keyword'></a>Mixing positional and keyword arguments
---
It can make good sense sometimes to mix positional and keyword arguments. In our previous example, we can expect this function to always take in a first name and a last name. Before we start mixing positional and keyword arguments, let's add another piece of information to our description of a person. Let's also go back to using just positional arguments for a moment:
```
def describe_person(first_name, last_name, age, favorite_language):
# This function takes in a person's first and last name,
# their age, and their favorite language.
# It then prints this information out in a simple format.
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
print("Age: %d" % age)
print("Favorite language: %s\n" % favorite_language)
describe_person('brian', 'kernighan', 71, 'C')
describe_person('ken', 'thompson', 70, 'Go')
describe_person('adele', 'goldberg', 68, 'Smalltalk')
```
We can expect anyone who uses this function to supply a first name and a last name, in that order. But now we are starting to include some information that might not apply to everyone. We can address this by keeping positional arguments for the first name and last name, but expect keyword arguments for everything else. We can show this works by adding a few more people, and having different information about each person:
```
def describe_person(first_name, last_name, age=None, favorite_language=None, died=None):
"""
This function takes in a person's first and last name, their age,
and their favorite language.
It then prints this information out in a simple format.
"""
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
# Optional information:
if age:
print("Age: %d" % age)
if favorite_language:
print("Favorite language: %s" % favorite_language)
if died:
print("Died: %d" % died)
# Blank line at end.
print("\n")
describe_person('brian', 'kernighan', favorite_language='C')
describe_person('adele', 'goldberg', age=68, favorite_language='Smalltalk')
describe_person('dennis', 'ritchie', favorite_language='C', died=2011)
describe_person('guido', 'van rossum', favorite_language='Python')
```
Everyone needs a first and last name, but everthing else is optional. This code takes advantage of the Python keyword `None`, which acts as an empty value for a variable. This way, the user is free to supply any of the 'extra' values they care to. Any arguments that don't receive a value are not displayed. Python matches these extra values by name, rather than by position. This is a very common and useful way to define functions.
[top](#top)
<a name='exercises_keyword_arguments'></a>Exercises
---
#### Ex 8.5: Sports Teams
- Write a function that takes in two arguments, the name of a city and the name of a sports team from that city.
- Call your function three times, using a mix of positional and keyword arguments.
#### Ex 8.6: World Languages
- Write a function that takes in two arguments, the name of a country and a major language spoken there.
- Call your function three times, using a mix of positional and keyword arguments.
```
# Ex 8.5 : Sports Team
# put your code here
# Ex 8.6 : Word Languages
# put your code here
```
[top](#top)
<a name='arbitrary_arguments'></a>Accepting an arbitrary number of arguments
===
We have now seen that using keyword arguments can allow for much more flexible calling statements.
- This benefits you in your own programs, because you can write one function that can handle many different situations you might encounter.
- This benefits you if other programmers use your programs, because your functions can apply to a wide range of situations.
- This benefits you when you use other programmers' functions, because their functions can apply to many situations you will care about.
There is another issue that we can address, though. Let's consider a function that takes two number in, and prints out the sum of the two numbers:
```
def adder(num_1, num_2):
# This function adds two numbers together, and prints the sum.
sum = num_1 + num_2
print("The sum of your numbers is %d." % sum)
# Let's add some numbers.
adder(1, 2)
adder(-1, 2)
adder(1, -2)
```
This function appears to work well. But what if we pass it three numbers, which is a perfectly reasonable thing to do mathematically?
```
def adder(num_1, num_2):
# This function adds two numbers together, and prints the sum.
sum = num_1 + num_2
print("The sum of your numbers is %d." % sum)
# Let's add some numbers.
adder(1, 2, 3)
```
This function fails, because no matter what mix of positional and keyword arguments we use, the function is only written two accept two arguments. In fact, a function written in this way will only work with *exactly* two arguments.
<a name='arbitrary_sequence'></a>Accepting a sequence of arbitrary length
---
Python gives us a syntax for letting a function accept an arbitrary number of arguments. If we place an argument at the end of the list of arguments, with an asterisk in front of it, that argument will collect any remaining values from the calling statement into a tuple. Here is an example demonstrating how this works:
```
def example_function(arg_1, arg_2, *arg_3):
# Let's look at the argument values.
print('\narg_1:', arg_1)
print('arg_2:', arg_2)
print('arg_3:', arg_3)
example_function(1, 2)
example_function(1, 2, 3)
example_function(1, 2, 3, 4)
example_function(1, 2, 3, 4, 5)
```
You can use a for loop to process these other arguments:
```
def example_function(arg_1, arg_2, *arg_3):
# Let's look at the argument values.
print('\narg_1:', arg_1)
print('arg_2:', arg_2)
for value in arg_3:
print('arg_3 value:', value)
example_function(1, 2)
example_function(1, 2, 3)
example_function(1, 2, 3, 4)
example_function(1, 2, 3, 4, 5)
```
We can now rewrite the adder() function to accept two or more arguments, and print the sum of those numbers:
```
def adder(*nums):
"""This function adds the given numbers together and prints the sum."""
s = 0
for num in nums:
s = s + num
# Print the results.
print("The sum of your numbers is %d." % s)
# Let's add some numbers.
adder(1, 2, 3)
def adder(*nums):
"""This function adds the given numbers together and prints the sum."""
# Print the results.
print("The sum of your numbers is %d." % sum(nums))
# Let's add some numbers.
adder(1, 2, 3)
```
In this new version, Python does the following:
- stores the first value in the calling statement in the argument `num_1`;
- stores the second value in the calling statement in the argument `num_2`;
- stores all other values in the calling statement as a tuple in the argument `nums`.
We can then "unpack" these values, using a for loop. We can demonstrate how flexible this function is by calling it a number of times, with a different number of arguments each time.
```
def adder(num_1, num_2, *nums):
# This function adds the given numbers together,
# and prints the sum.
# Start by adding the first two numbers, which
# will always be present.
sum = num_1 + num_2
# Then add any other numbers that were sent.
for num in nums:
sum = sum + num
# Print the results.
print("The sum of your numbers is %d." % sum)
# Let's add some numbers.
adder(1, 2)
adder(1, 2, 3)
adder(1, 2, 3, 4)
adder(1, 2, 3, 4, 5)
```
[top](#top)
<a name='arbitrary_keyword_arguments'></a>Accepting an arbitrary number of keyword arguments
---
Python also provides a syntax for accepting an arbitrary number of keyword arguments. The syntax looks like this:
```
import sys
f = open('./data/test.txt', 'w')
FILE_OUT = f #sys.stdout
def example_function(*args, **kwargs):
print(*args, sep='++', end=' ', file=FILE_OUT)
for k, v in kwargs.items():
print(k, ': ', v, end=' ', file=FILE_OUT)
example_function(1, 2, 4, 5)
example_function(1, 3, value=1, name=5)
example_function(store='ff', quote='Do. Or do not. There is no try.')
f.close()
def example_function(arg_1, arg_2, **kwargs):
# Let's look at the argument values.
print('\narg_1:', arg_1)
print('arg_2:', arg_2)
print('arg_3:', kwargs)
example_function('a', 'b')
example_function('a', 'b', value_3='c')
example_function('a', 'b', value_3='c', value_4='d')
example_function('a', 'b', value_3='c', value_4='d', value_5='e')
```
The third argument has two asterisks in front of it, which tells Python to collect all remaining key-value arguments in the calling statement. This argument is commonly named *kwargs*. We see in the output that these key-values are stored in a dictionary. We can loop through this dictionary to work with all of the values that are passed into the function:
```
def example_function(arg_1, arg_2, **kwargs):
# Let's look at the argument values.
print('\narg_1:', arg_1)
print('arg_2:', arg_2)
for key, value in kwargs.items():
print('arg_3 value:', value)
example_function('a', 'b')
example_function('a', 'b', value_3='c')
example_function('a', 'b', value_3='c', value_4='d')
example_function('a', 'b', value_3='c', value_4='d', value_5='e')
def example_function(**kwargs):
print(type(kwargs))
for key, value in kwargs.items():
print('{}:{}'.format(key, value))
example_function(first=1, second=2, third=3)
example_function(first=1, second=2, third=3, fourth=4)
example_function(name='Valerio', surname='Maggio')
```
Earlier we created a function that let us describe a person, and we had three things we could describe about a person. We could include their age, their favorite language, and the date they passed away. But that was the only information we could include, because it was the only information that the function was prepared to handle:
```
def describe_person(first_name, last_name, age=None, favorite_language=None, died=None):
# This function takes in a person's first and last name,
# their age, and their favorite language.
# It then prints this information out in a simple format.
# Required information:
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
# Optional information:
if age:
print("Age: %d" % age)
if favorite_language:
print("Favorite language: %s" % favorite_language)
if died:
print("Died: %d" % died)
# Blank line at end.
print("\n")
describe_person('brian', 'kernighan', favorite_language='C')
describe_person('ken', 'thompson', age=70)
describe_person('adele', 'goldberg', age=68, favorite_language='Smalltalk')
describe_person('dennis', 'ritchie', favorite_language='C', died=2011)
describe_person('guido', 'van rossum', favorite_language='Python')
```
We can make this function much more flexible by accepting any number of keyword arguments. Here is what the function looks like, using the syntax for accepting as many keyword arguments as the caller wants to provide:
```
def describe_person(first_name, last_name, **kwargs):
# This function takes in a person's first and last name,
# and then an arbitrary number of keyword arguments.
# Required information:
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
# Optional information:
for key in kwargs:
print("%s: %s" % (key.title(), kwargs[key]))
# Blank line at end.
print("\n")
describe_person('brian', 'kernighan', favorite_language='C')
describe_person('ken', 'thompson', age=70)
describe_person('adele', 'goldberg', age=68, favorite_language='Smalltalk')
describe_person('dennis', 'ritchie', favorite_language='C', died=2011)
describe_person('guido', 'van rossum', favorite_language='Python')
```
This is pretty neat. We get the same output, and we don't have to include a bunch of if tests to see what kind of information was passed into the function. We always require a first name and a last name, but beyond that the caller is free to provide any keyword-value pair to describe a person. Let's show that any kind of information can be provided to this function. We also clean up the output by replacing any underscores in the keys with a space.
```
def describe_person(first_name, last_name, **kwargs):
# This function takes in a person's first and last name,
# and then an arbitrary number of keyword arguments.
# Required information:
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
# Optional information:
for key in kwargs:
print("%s: %s" % (key.title().replace('_', ' '), kwargs[key]))
# Blank line at end.
print("\n")
describe_person('brian', 'kernighan', favorite_language='C', famous_book='The C Programming Language')
describe_person('ken', 'thompson', age=70, alma_mater='UC Berkeley')
describe_person('adele', 'goldberg', age=68, favorite_language='Smalltalk')
describe_person('dennis', 'ritchie', favorite_language='C', died=2011, famous_book='The C Programming Language')
describe_person('guido', 'van rossum', favorite_language='Python', company='Dropbox')
```
There is plenty more to learn about using functions, but with all of this flexibility in terms of how to accept arguments for your functions you should be able to write simple, clean functions that do exactly what you need them to do.
[top](#top)
| github_jupyter |
# Reconhecimento de atividade humana usando conjunto de dados de smartphones
## Random Forest com classificação e clustering - Preditor de atividade humana
A Contoso Behavior Systems está desenvolvendo uma ferramenta de IA que tentará reconhecer a atividade humana (1-Walking, 2-Walking upstairs, 3-Walking downstairs, 4-Sentado, 5-Standing ou 6-Laying) usando os sensores do smartphone. O que significa que, usando os métodos a seguir, o smartphone pode detectar o que estamos fazendo no momento.
O banco de dados do Human Activity Recognition foi construído a partir de gravações de 30 participantes do estudo realizando atividades de vida diária (AVD) enquanto carregavam um smartphone montado na cintura com sensores inerciais embutidos. O objetivo é classificar as atividades em uma das seis atividades realizadas.
### Descrição do experimento
Os experimentos foram realizados com um grupo de 30 voluntários em uma faixa etária de 19 a 48 anos. Cada pessoa realizou seis atividades (1-Walking, 2-Walking upstairs, 3-Walking downstairs, 4-Sentado, 5-Standing ou 6-Laying) usando um smartphone (Samsung Galaxy S II) na cintura. Usando seu acelerômetro e giroscópio embutidos, capturamos a aceleração linear 3-axial e a velocidade angular 3-axial a uma taxa constante de 50Hz. Os experimentos foram gravados em vídeo para rotular os dados manualmente. O conjunto de dados obtido foi particionado aleatoriamente em dois conjuntos, onde 70% dos voluntários foram selecionados para gerar os dados de treinamento e 30% os dados de teste.
Os sinais do sensor (acelerômetro e giroscópio) foram pré-processados pela aplicação de filtros de ruído e então amostrados em janelas deslizantes de largura fixa de 2,56 seg e sobreposição de 50% (128 leituras/janela). O sinal de aceleração do sensor, que possui componentes gravitacionais e de movimento corporal, foi separado por meio de um filtro passa-baixo Butterworth em gravidade e aceleração do corpo. A força gravitacional é considerada como tendo apenas componentes de baixa frequência, portanto, um filtro com frequência de corte de 0,3 Hz foi usado. De cada janela, um vetor de features foi obtido pelo cálculo de variáveis no domínio do tempo e da frequência.
### Informações de atributo
* Para cada registro no conjunto de dados, o seguinte é fornecido:
* Aceleração triaxial do acelerômetro (aceleração total) e a aceleração corporal estimada.
* Velocidade angular triaxial do giroscópio.
* Um vetor de 561 features com variáveis de domínio de tempo e frequência.
* Seu rótulo de atividade.
* Um identificador do sujeito que realizou o experimento.
### Planejamento
Quando temos um problema que sabemos resolver, podemos criar uma lista de etapas para nos guiar pelo experimento.
1. Importe as bibliotecas Python necessárias
2. Carregue e analise os dados
3. Encontre correlações entre as features
4. Divida os dados em dados de treinamento e teste (dados de validação)
5. Preveja a atividade usando Regressão Logística
### 1. Importe as bibliotecas Python necessárias
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support as error_metric
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.feature_selection import VarianceThreshold
```
### 2. Carregue e analise os dados
```
#train = pd.read_csv("https://github.com/microsoft/Reactors/raw/main/workshop-resources/data-science-and-machine-learning/Data_Science_2/human-behavior-project/Data/train.csv")
train = pd.read_csv("Data/train.csv")
#test = pd.read_csv("https://github.com/microsoft/Reactors/raw/main/workshop-resources/data-science-and-machine-learning/Data_Science_2/human-behavior-project/Data/test.csv")
test = pd.read_csv("Data/test.csv")
print("--------- Training Data ---------")
print(train.head())
print("--------- Test Data ---------")
print(test.head())
```
#### Verifique se há valores nulos nos dados
```
print("Training Data:",train.isnull().values.any())
print("Testing Data:",test.isnull().values.any())
```
Sem valores nulos, vamos prosseguir
```
train.info()
test.info()
```
#### Removendo dados que não usaremos, neste caso não nos importamos com quem foi o "sujeito"
Olhando os valores principais, podemos notar que a coluna subject não será útil aqui, então vamos retirá-la de ambos os conjuntos de dados. Como há muitas colunas nos dados, você pode não tê-la notado, mas é apenas um número que foi usado arbitrariamente para identificar os indivíduos.
### Eliminando dados
Lembre-se de que podemos usar o método built-in .drop para remover colunas do conjunto de dados. Podemos usar a ajuda interativa para ter certeza de que sabemos quais são todos os parâmetros - para acessar a ajuda, digite train.drop? o ponto de interrogação permite ao interpretador saber que queremos ajuda.
No método [pandas.DataFrame.drop](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html), o parâmetro 'axis' significa que estamos descartando uma coluna e o parâmetro 'inplace' significa exatamente isso: faça a operação no local e retorne None.
```
# We can do these both at once:
train.drop('subject', axis =1, inplace=True)
test.drop('subject', axis =1, inplace=True)
# Verify that the column was dropped
print("--------- Training Data ---------")
print(train.head())
print("--------- Test Data ---------")
print(test.head())
# Let's creat a list of all the column labels.
rem_cols2 = test.columns.tolist()
rem_cols2
# We should also verify the different datatypes in our data, in this case we can see we have
# 561 float type data dimensions and 1 object dimension.
print('----------TRAIN------------')
print(train.dtypes.value_counts())
print('----------TEST------------')
print(test.dtypes.value_counts())
train.info()
test.info()
```
### Checkpoint
Devemos reescalar os dados? A reescalação de um conjunto de dados geralmente produz um conjunto de dados melhor e previsões mais precisas. Primeiro, verificamos o intervalo (o mínimo e o máximo) para cada um dos conjuntos de dados. Vamos tentar usar o método .describe() e vamos excluir a coluna de atividade que é a última coluna.
### Reescalando dados
Quando 'reescalamos' os dados, adicionamos ou subtraímos uma constante e multiplicamos ou dividimos por constante para os valores originais. Um bom exemplo disso é quando convertemos ou transformamos os dados de temperatura de Celsius para Fahrenheit.
### Padronização e normalização de nossos dados
Quando padronizamos e normalizamos dados, essencialmente estamos tentando criar dados que sejam facilmente comparáveis - como transformar uma comparação "maçãs com laranjas" em uma comparação "maçãs com maçãs". Padronizar as features em torno da média 0 com um desvio padrão de 1 é importante quando comparamos medidas que têm unidades diferentes. Variáveis que são medidas em escalas diferentes não contribuem igualmente para a análise e podem acabar criando um viés.
Da mesma forma, o objetivo da normalização é alterar os valores das colunas numéricas no conjunto de dados para uma escala comum, sem distorcer as diferenças nos intervalos de valores. Para aprendizado de máquina, nem todo conjunto de dados requer normalização. É necessário apenas quando as features têm intervalos diferentes.
### Quando devemos normalizar ou padronizar?
**Normalização** é uma boa técnica para usar quando você não sabe a distribuição de seus dados ou quando sabe que a distribuição não é Gaussiana (uma curva em sino). A normalização é útil quando seus dados têm escalas variáveis e o algoritmo que você está usando não faz suposições sobre a distribuição de seus dados, como vizinhos k-mais próximos e redes neurais artificiais.
**Padronização** assume que seus dados têm uma distribuição gaussiana. Isso não precisa ser estritamente verdadeiro, mas a técnica é mais eficaz se a distribuição de seus atributos for gaussiana. A padronização é útil quando seus dados têm escalas variáveis e o algoritmo que você está usando faz suposições sobre seus dados terem uma distribuição Gaussiana, como regressão linear, regressão logística e análise de discriminante linear.
```
print('----------TRAIN------------')
print(train.describe())
print('----------TEST------------')
print(test.describe())
```
### Escalando
Agora que entendemos por que escalamos os dados, devemos fazer isso aqui?
Aqui não é necessário. Vemos que o min = -1 e o max = +1, portanto, não há necessidade de dimensionar esses dados. Não parece haver dados estranhos ou remotos. Em outras palavras, todos os dados estão dentro de uma faixa que faz sentido. Vamos continuar.
```
# Notice how we can use .tail() to also examine the datatypes of the last
train.dtypes.tail()
```
Eles têm os mesmos tipos de dados. Ou seja, a maioria das features é float e uma é do tipo objeto. Vamos ver o que está na feature 'Activity', do tipo objeto, e separá-la do resto.
```
object_feature = train.dtypes == np.object
object_feature = train.columns[object_feature]
object_feature
```
Como podemos ver, o único tipo de dados de objeto no conjunto de dados de treinamento e teste é o recurso Activity. Vamos dar uma olhada nisso ...
```
train.Activity.value_counts()
```
Precisamos codificar a coluna Activity porque sklearn não aceitará dados categóricos como nossos rótulos de coluna. Usaremos [LabelEncoder] (https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html) para codificar a coluna 'Activity'.
#### LabelEndcoder em sklearn
A função LabelEncoder pode fazer algumas coisas por nós. Ele pode normalizar nomes de coluna de rótulo ou também pode converter rótulos categóricos em valores numéricos, semelhante ao processo de ["one-hot-encoding" no Azure ML Studio] (https://docs.microsoft.com/en-us/azure/machine-learning/ studio-module-reference/convert-to-indicator-values), que essencialmente nos permite criar um sistema binário para converter dados categóricos em números.
Vamos fazer isso aqui com o LabelEncoder:
```
le = LabelEncoder()
for x in [train, test]:
x['Activity'] = le.fit_transform(x.Activity)
train.Activity.sample(5)
test.Activity.sample(5)
```
### 3 Encontrando a correlação / relações entre as features
Correlação refere-se à relação mútua e associação entre quantidades e é geralmente usada para expressar uma quantidade em termos de sua relação com outras quantidades. A correlação pode ser positiva (as variáveis mudam na mesma direção), negativa (as variáveis mudam na direção oposta ou neutra (sem correlação).
As variáveis em um conjunto de dados podem estar relacionadas de várias maneiras e por vários motivos:
- Elas podem depender de valores de outras variáveis
- Elas podem estar associadas entre si
- Ambas podem depender de uma terceira variável.
Para este projeto, usaremos o método pandas .corr() para calcular a correlação entre as colunas do dataframe.
```
# Exclude the Activity column
feature_cols = train.columns[: -1]
# Calculate the correlation values
correlated_values = train[feature_cols].corr()
# Stack the data and convert to a dataframe
correlated_values = (correlated_values.stack().to_frame().reset_index()
.rename(columns={'level_0': 'Feature_1', 'level_1': 'Feature_2', 0:'Correlations'}))
correlated_values.head()
# Create an abs_correlation column
correlated_values['abs_correlation'] = correlated_values.Correlations.abs()
correlated_values.head()
# Picking most correlated features
train_fields = correlated_values.sort_values('Correlations', ascending = False).query('abs_correlation>0.8')
train_fields.sample(5)
```
### 4 Dividindo os dados em DataFrames de treinamento e validação
Se treinarmos um modelo e testá-lo com os mesmos dados, veremos algo muito interessante - provavelmente nada além de pontuações perfeitas e não conseguirá prever nada de útil em novos dados.
Quando essa situação surge, ocorre o chamado de overfitting, que é algo que discutiremos mais em nossos workshops de aprendizado de máquina. Para isso, é prática comum, ao realizar um experimento de aprendizado de máquina (supervisionado), manter parte dos dados disponíveis como um conjunto de teste x_test, y_test. Também realizaremos uma etapa de validação cruzada na próxima seção.
Aprender os parâmetros de uma função de previsão e testá-la com os mesmos dados é um erro metodológico: um modelo que apenas repetisse os rótulos das amostras que acabou de ver teria uma pontuação perfeita, mas não conseguiria prever nada de útil nos dados ainda não vistos. Essa situação é chamada de overfitting.
O que podemos fazer é realizar um processo de validação cruzada no treinamento do modelo. Os melhores parâmetros podem ser determinados por técnicas de grid search. Em nosso exemplo abaixo, usaremos [sklearn.model_selection.StratifiedShuffleSplit] (https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html) para realizar nossas etapas de validação cruzada.
```
#Getting the split indexes
split_data = StratifiedShuffleSplit(n_splits = 3, test_size = 0.3, random_state = 42)
train_idx, val_idx = next(split_data.split(train[feature_cols], train.Activity))
#creating the dataframes
x_train = train.loc[train_idx, feature_cols]
y_train = train.loc[train_idx, 'Activity']
x_val = train.loc[val_idx, feature_cols]
y_val = train.loc[val_idx, 'Activity']
y_train.value_counts(normalize = True)
y_val.value_counts(normalize = True)
```
#### Mesma proporção de classes nos dados de treinamento e validação graças ao StratifiedShuffleSplit
StratifiedShuffleSplit é um validador cruzado que fornece índices de treinamento/teste para dividir dados em conjuntos de treinamento/teste.
Este objeto de validação cruzada é uma fusão de StratifiedKFold e ShuffleSplit, que retorna dobras estratificadas aleatórias. As dobras são feitas preservando o percentual de amostras de cada classe.
Observe que as proporções no dataframe y_train e no dataframe y_val são quase iguais. Isso nos diz que o desempenho de nosso modelo é consistente em todas as três divisões que criamos. Abordaremos mais sobre os conceitos de validação cruzada em nosso próximo workshop de aprendizado de máquina.
### 5. Modelagem Preditiva
A modelagem preditiva usa estatísticas para prever resultados. Na maioria das vezes, o evento que se deseja prever está no futuro, mas a modelagem preditiva pode ser aplicada a qualquer tipo de evento desconhecido, independentemente de quando ocorreu.
A regressão logística, apesar do nome, é um modelo linear para classificação em vez de regressão. A regressão logística também é conhecida na literatura como regressão logit, classificação de entropia máxima (MaxEnt) ou classificador log-linear. Neste modelo, as probabilidades que descrevem os resultados possíveis de um único ensaio são modeladas usando uma função logística.
A regressão logística é implementada em LogisticRegression. Esta implementação pode se ajustar à regressão logística binária, One-vs-Rest ou multinomial com regularização opcional l1, l2 ou Elastic-Net. [Saiba mais sobre regressão logística visitando o guia do usuário.] (Https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegressionCV.html?highlight=logisticregressioncv#sklearn.linear_model.LogisticRegressionCV)
```
# Our standard Logistic Regression algorithm
lr = LogisticRegression()
# We'll also use the Logistic Regression CV (Cross-Validation), with 4 folds.
# Here are the parameters and what each one of them does.
# Cs - List of ints of floats, default value is 10
# Each of the values in Cs describes the inverse of regularization strength.
# If Cs is as an int, then a grid of Cs values are chosen in a logarithmic scale between
# 1e-4 and 1e4. Like in support vector machines, smaller values specify stronger regularization.
# cv - Cross-validation generator
# penalty - Used to specify the norm used in the penalization. The ‘newton-cg’, ‘sag’ and ‘lbfgs’
# solvers support only l2 penalties. ‘elasticnet’ is only supported by the ‘saga’ solver.
# max-iter - Maximum number of iterations of the optimization algorithm.
lr_l2 = LogisticRegressionCV(Cs=10, cv=4, penalty='l2', max_iter=120)
# RandomForestClassifier - n_estimators =The number of trees in the forest. Default is 100
rf = RandomForestClassifier(n_estimators = 10)
lr = lr.fit(x_train, y_train)
rf = rf.fit(x_train, y_train)
lr_l2 = lr_l2.fit(x_train, y_train)
#predict the classes and probability for each
y_predict = list()
y_proba = list()
labels = ['lr', 'lr_l2', 'rf']
models = [lr, lr_l2, rf]
for lab, mod in zip(labels, models):
y_predict.append(pd.Series(mod.predict(x_val), name = lab))
y_proba.append(pd.Series(mod.predict_proba(x_val).max(axis=1), name = lab))
#.max(axis = 1) for a 1 dimensional dataframe
y_predict = pd.concat(y_predict, axis = 1)
y_proba = pd.concat(y_proba, axis = 1)
y_predict['true'] = y_val.values
y_proba['true'] = y_val.values
y_predict.head()
(y_predict['rf'] == y_predict['true']).mean()
y_proba.head(10)
```
### Os resultados são bons - Conclusão
Olhando para os resultados da regressão logística, regressão logística com regularização L2 e o classificador de floresta aleatório, estamos vendo uma boa precisão de nossos modelos. Parece que os melhores resultados são do modelo lr_l2, o que faz sentido, pois é onde estamos realizando a regularização (para lidar com outliers) e a etapa de validação cruzada que também está ocorrendo. Para todos os efeitos, nosso experimento está concluído - no entanto, aprenderemos sobre as métricas de erro e para que servem.
### 6. Calculating the Error Metrics
Regressions are one of the most commonly used tools in a data scientist’s kit. When you learn Python, you gain the ability to create regressions in single lines of code without having to deal with the underlying mathematical theory.
This ease can cause us to forget to evaluate our regressions to ensure that they are a sufficient enough representation of our data. We can plug our data back into our regression equation to see if the predicted output matches corresponding observed value seen in the data.
The quality of a regression model is how well its predictions match up against actual values, but how do we actually evaluate quality? Luckily, smart statisticians have developed error metrics to judge the quality of a model and enable us to compare regresssions against other regressions with different parameters. These metrics are short and useful summaries of the quality of our data.
We will look at the Precision, Recall, F-Score, and Accuracy as our error metrics. We are trying to figure our whether or not our model gives us more false/true positives(FP/TP) or more false/true negative responses(FN/TN). First of all, let's make sure we understand that all true positives and true negatives are usually good scores, depending on the type of data. Let's go over the error metrics in this project.
#### Accuracy
Accuracy is the most straightforward metric, it's simply answers the question how many times did the model accurately predict the phone user's behavior.
**Accuracy = (TP+TN)/(TP+FP+FN+TN)**
#### Recall (aka Sensitivity)
Recall is the ratio of the activities that were predicted compared to activites that were actually observed in real life. Recall answers the following question: Of all the subject's activities that we predicted them to be doing at any given time, how many of thm were correct?
**Recall = TP/(TP+FN)**
#### Precision
Precision is the ratio of the correctly labeled activities by our program to all the activities labeled.
Precision answers the following: How many of those who we labeled doing an activity were actually doing the activity?
**Precision = TP/(TP+FP)**
#### F1-score (aka F-Score / F-Measure)
F1 Score considers both precision and recall. It is the harmonic mean(average) of the precision and recall.
F1 Score is best if there is some sort of balance between precision (p) & recall (r) in the system. Oppositely F1 Score isn’t so high if one measure is improved at the expense of the other.
For example, if P is 1 & R is 0, F1 score is 0.
F1 Score = 2*(Recall * Precision) / (Recall + Precision)
```
# Let's calculate the error metrics here,
# We will also use a confusion matrix to better see where our results are coming from.
metrics = list()
confusion_m = dict()
for lab in labels:
precision, recall, f_score, _ = error_metric(y_val, y_predict[lab], average = 'weighted')
accuracy = accuracy_score(y_val, y_predict[lab])
confusion_m[lab] = confusion_matrix(y_val, y_predict[lab])
metrics.append(pd.Series({'Precision': precision, 'Recall': recall,
'F_score': f_score, 'Accuracy': accuracy}, name = lab))
metrics= pd.concat(metrics, axis =1)
metrics
```
### Confusion Matrix
One great tool for evaluating the behavior and understanding the effectiveness of a binary or categorical classifier is the Confusion Matrix.
You can see that all of the metris we are seeing are giving us very high marks. This tells us that our model is performing very well. Let's plot the lr (logistic regression), and lr_l2 (Level 2 regularization), and the rf (random forests) in confusion matrices.
We've already fit a logistic regression model, the confusion matrix can be calculated manually, or since we are talented smart data scientists, we can just use the confusion_matrix function from sklearn.
The code below fits a Logistic Regression Model and outputs the confusion matrix. The 'lab' object are loaded with the data frames of our preditions. Be sure to use the interactive help to figure our what line of code does.
```
fig, axList = plt.subplots(nrows=2, ncols=2)
axList = axList.flatten()
fig.set_size_inches(12, 10)
axList[-1].axis('off')
for ax,lab in zip(axList[:-1], labels):
sns.heatmap(confusion_m[lab], ax=ax, annot=True, fmt='d');
ax.set(title=lab);
plt.tight_layout()
```
### Observations about Error Metrics and Ridge Regression
We can see that the Logistic regression with L2 regularization gives slightly better error metric than the other models. The question we ask here is: What happens when we discard the most correlated feature? Will we have a better model? The answer is typically yes, we will get better results with we remove highly correlated features. We are addressing the 'curse of dimensionality' and the idea that too much correlated data in our experiment can cause it to be 'overfit' and will not be very effective working with similar data.
In following workshops, we'll learn more about cross-validation and using confusion matrices to check the performance and accuracy of our models.
| github_jupyter |
## scRNA-seq analysis (dimensionality reduction, clustering, identifying DE genes)
Now that we've rigourously QC'd and normalized our data to remove confounders, we can move on to the interesting part! Of course, analysis steps will vary depending on the biological question, but there a few things we can do that are useful in a wide range of contexts.
Use readRDS() to load in the Darmanis Seurat object we pre-processed in the last in-class assignment:
### PCA
One of the first things we can do is run PCA on our data. Doing a linear dimensionality reduction can not only help us visualize the data, but also identify "metafeatures" of correlated gene sets. These metafeatures are more robust to noise and will be used as input features for more sophisticated dimensionality reduction methods that we'll use later.
Seurat provides a function RunPCA() that will perform PCA on the scaled data for us. We can specify the input features to use using the *features* argument. In this case, we want to use the highly variable genes we previously identified.
```
library(Seurat)
sc <- RunPCA(object=sc, features=VariableFeatures(object=sc), verbose=F)
```
We can visualize our PCA using DimPlot(), which will plot PC1 and PC2. We set the *reduction* argument to "pca", and color the dots by the cell type annotation stored in sc@meta.data.
```
DimPlot(object=sc, reduction="pca", pt.size=0.3, group.by="celltype")
```
We can look at the top genes that define each principal component:
```
print(x = sc[["pca"]], dims=1:3, nfeatures=6)
```
What do you notice about the PCA plot?
One question we must answer is how many principal components are important? There are several independent ways to estimate this! Seurat implements the JackStraw procedure used in Macosko et al (https://www.cell.com/fulltext/S0092-8674(15)00549-8).
Seurat can also visualize an Elbow plot, which tells us the percentage of variation explained by each principal component. These plots are often used to determine the number of PCs needed to capture the majority of the signal. Since the JackStraw procedure takes a long time on large datasets, we'll roughly estimate the dimensionality of the data with an Elbow plot.
```
ElbowPlot(object=sc)
# If you wanted to implement JackStraw procedure...
# sc <- JackStraw(object=sc, num.replicate=100)
# sc <- ScoreJackStraw(object=sc, dims=1:20)
# JackStrawPlot(object=sc, dims=1:16)
```
**Based on the elbow plot, how many PCs do you think we should use?**
Let's decide on 15 PCs to use for downstream clustering and visualization. You can change this number based on your interpretation of the plots!
```
num_dims <- 15
```
### Clustering
There are many, many single-cell clustering algorithms available these days, and each have their strengths and weaknesses. We will use Seurat's graph-based clustering algorithm to identify distinct clusters in our data.
Clustering happens in two parts. First, FindNeighbors() will construct a K-nearest neighbor graph with the number of specified PCs. Second, FindClusters() will apply the Louvain algorithm to partition the graph into highly inter-connected "communities".
```
sc <- FindNeighbors(object=sc, dims=1:num_dims)
sc <- FindClusters(object=sc, resolution=0.4)
```
You can access the cluster IDs in the @active.ident slot. **How many clusters did Seurat find in our data?**
Note that there is a *resolution* parameter that sets the "granularity" of the downsteam clustering. The higher this value, the more clusters we will obtain. For a dataset with 3000 cells, Seurat suggests setting this value to 0.4-1.2. As the number of cells increases, the resolution value should increase as well.
Let's see how this resolution parameter might affect our clustering.
**How many clusters do we get with resolution values of 0.1? 1.2? 5?**
Let's try clustering with each resolution value:
```
res <- c(0.1, 1.2, 5)
for(i in 1:length(res)) {
sc <- FindNeighbors(object=sc, dims=1:num_dims)
sc <- FindClusters(object=sc, resolution=res[i])
print(paste("res=", res[i], "; number of communities=", length(levels(sc@active.ident)), sep=""))
}
```
Fill in the number of clusters at each resolution setting:
**Let's set the resolution parameter to 0.4 for our downstream analysis.**
```
sc <- FindNeighbors(object=sc, dims=1:num_dims)
sc <- FindClusters(object=sc, resolution=0.4)
```
### Dimensionality reduction and visualization - UMAP and tSNE
We'll often want to use non-linear dimensionality reduction techniques to visualize and explore scRNA-seq datasets. The goal of both UMAP and tSNE is to place similar cells together in a low-dimensional space. Cells of the same type or in the same cluster should appear together on the 2D plots.
Again, we'll use the same PCs as input for dimensionality reductions.
Let's run UMAP twice. In the first, we'll color the cells by their cluster assignments from the previous step. In the second, we'll color them by their cell type annotation. **Is the clustering biologically relevant? Does the UMAP visualization correspond to our clustering?**
```
# Color by cluster ID
sc <- RunUMAP(object=sc, dims=1:num_dims)
p1 <- DimPlot(object=sc, reduction="umap", pt.size=0.2)
# Color by cell type annotation
sc <- RunUMAP(object=sc, dims=1:num_dims)
p2 <- DimPlot(object=sc, reduction="umap", pt.size=0.2, group.by="celltype")
CombinePlots(list(p1, p2), ncol=2)
```
Now let's try another dimensionality reduction method - tSNE. We'll color them the same way as for UMAP.
**Is the clustering biologically relevant? Does the tSNE visualization correspond to our clustering?**
```
# Color by cluster ID
sc <- RunTSNE(object=sc, dims=1:num_dims)
p1 <- DimPlot(object=sc, reduction="tsne", pt.size=0.2)
# Color by cell type annotation
sc <- RunTSNE(object=sc, dims=1:num_dims)
p2 <- DimPlot(object=sc, reduction="tsne", pt.size=0.2, group.by="celltype")
CombinePlots(list(p1, p2), ncol=2)
```
How do the UMAP and tSNE dimensionality reductions compare? Plot the two visualizations side by side. **Replace <DIM_PLOT> with the correct method.**
```
# Compare UMAP and TSNE plots
p1 <- DimPlot(object=sc, reduction=<DIM_PLOT>, pt.size=0.2)
p2 <- DimPlot(object=sc, reduction=<DIM_PLOT>, pt.size=0.2)
CombinePlots(list(p1, p2), ncol=2)
```
### Identify biomarkers for each cluster
Seurat also has a function for identifying biomarkers that define a cluster. These genes are differntially expressed in a cluster compared to all the other cells. See the Seurat documentation for many more parameter options for this function.
```
sc.markers <- FindAllMarkers(object=sc, only.pos=TRUE, min.pct=0.25, logfc.threshold=0.25)
# List biomarkers for each cluster
genes.markers <- lapply(0:(length(unique(sc.markers$cluster))-1), function(x) {
print(paste("cluster ", x, sep=""))
genes <- sc.markers$gene[which(sc.markers$cluster == x)]
return(genes)
})
genes.markers
```
**Let's plot the expression of a few genes that define clusters.** Each of these genes were identified with FindAllMarkers() as one of the top differentially expressed genes for a cluster.
```
FeaturePlot(object = sc, features = c("IFI30", "CCL3", "CDR1", "CRYAB", "WIF1", "GJB1"), pt.size=0.05)
```
### Homework (10 pts)
###### We're now going to return to the Zheng dataset we processed in the previous homework. Recall that this dataset consists of purified immune cell populations. These populations include B cells, naive CD4+, cytotoxic CD8+, regulatory T cells, NK cells, and monocytes. We've provided lists of marker genes that define a cell type (from Jerby-Arnon et al. 2018 https://www.ncbi.nlm.nih.gov/pubmed/30388455).
###### Using what you learned above, annotate the immune cells based on marker expression. Again, you should NOT run every step - only run the essential steps for our goal of annotating cells.
###### These steps include:
1. Load in the processed Zheng seurat object
2. Run PCA and determine dimensionality of dataset
3. Using PCs as input, cluster the cells
4. Visualize clusters by UMAP - check that cells within clusters group together
5. Identify markers that define each cluster by differential expression
6. Make a composite feature of each immune cell type signature by averaging the z-scored expression values of the genes in each signature.
7. Plot the composite features to see in which clusters they are overexpressed.
8. Given the differentially expressed markers and the expression of immune cell signatures, manually annotate the clusters.
###### Make sure to include all essential code!
###### Q1 (3 pts). Run PCA, cluster cells with resolution=0.8, and visualize clusters with UMAP. Be sure to determine the dimensionality of the dataset by your method of choice, and use that number of PCs for downstream clustering and visualization.
###### How many PCs did you use for clustering? How many clusters did you end up with? Do the clusters group together with UMAP dimensionality reduction?
###### Q2 (2 pts). Identify markers that define each cluster by differential expression.
###### Q3 (3 pts). Use the code below to make composite features of each immune cell type with their given signature genes. Briefly describe what the code is doing in your own words.
```
# We have to scale *all* genes beacuse need to match to gene sets, not just use PCs for dimensionality reduction.
sc <- ScaleData(object=sc, features=rownames(sc))
celltypes <- c("Bcell", "CD4_naive", "cytotoxic_CD8", "Treg", "macrophage", "NK")
# Load in cell type markers
celltype.markers <- lapply(celltypes, function(x) {
markers <- read.table(paste("immune_markers_JerbyArnon/", x, "_markers.txt", sep=""), header= F)
markers <- as.character(markers$V1)
return(markers)
})
names(celltype.markers) <- celltypes
# Get scaled data matrix
sc.mat_scaled <- sc[["RNA"]]@scale.data
# For each immune signature, take the mean of the z-scored expression values for each cell.
meta_celltype_exps <- lapply(1:length(celltype.markers), function(x) {
mat <- sc.mat_scaled[na.omit(match(celltype.markers[[x]], rownames(sc))), ]
meta_celltype_exp <- as.numeric(colMeans(t(scale(t(mat)))))
return(meta_celltype_exp)
})
names(meta_celltype_exps) <- celltypes
mat.meta_celltype_exps <- do.call(rbind, meta_celltype_exps)
# Add composite features to the data matrix of a duplicate seurat object, sc1
sc1 <- sc
sc1[["RNA"]]@data <- rbind(sc[["RNA"]]@scale.data, mat.meta_celltype_exps)
# Plot composite features of immune signatures
FeaturePlot(object = sc1, features = c("Bcell", "CD4_naive", "cytotoxic_CD8", "Treg", "macrophage", "NK"), pt.size=0.1)
```
###### Q4 (2 pts). Based on the differentially expressed markers and the expression of immune signatures, manually annotate the clusters. Some clusters will be very difficult to annotate, which is often the case in real single cell data. Don't worry too much about those, just try your best! We will only grade on the clearest clusters
| github_jupyter |
<a href="https://colab.research.google.com/github/googol88/intro-to-tensorflow/blob/main/l08c05_forecasting_with_machine_learning.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
##### 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.
```
# Forecasting with machine learning
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l08c05_forecasting_with_machine_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/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l08c05_forecasting_with_machine_learning.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
## Setup
```
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
keras = tf.keras
def plot_series(time, series, format="-", start=0, end=None, label=None):
plt.plot(time[start:end], series[start:end], format, label=label)
plt.xlabel("Time")
plt.ylabel("Value")
if label:
plt.legend(fontsize=14)
plt.grid(True)
def trend(time, slope=0):
return slope * time
def seasonal_pattern(season_time):
"""Just an arbitrary pattern, you can change it if you wish"""
return np.where(season_time < 0.4,
np.cos(season_time * 2 * np.pi),
1 / np.exp(3 * season_time))
def seasonality(time, period, amplitude=1, phase=0):
"""Repeats the same pattern at each period"""
season_time = ((time + phase) % period) / period
return amplitude * seasonal_pattern(season_time)
def white_noise(time, noise_level=1, seed=None):
rnd = np.random.RandomState(seed)
return rnd.randn(len(time)) * noise_level
time = np.arange(4 * 365 + 1)
slope = 0.05
baseline = 10
amplitude = 40
series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)
noise_level = 5
noise = white_noise(time, noise_level, seed=42)
series += noise
plt.figure(figsize=(10, 6))
plot_series(time, series)
plt.show()
```
## Forecasting with Machine Learning
First, we will train a model to forecast the next step given the previous 30 steps, therefore, we need to create a dataset of 30-step windows for training.
```
def window_dataset(series, window_size, batch_size=32,
shuffle_buffer=1000):
dataset = tf.data.Dataset.from_tensor_slices(series)
dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
dataset = dataset.shuffle(shuffle_buffer)
dataset = dataset.map(lambda window: (window[:-1], window[-1]))
dataset = dataset.batch(batch_size).prefetch(1)
return dataset
split_time = 1000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
```
### Linear Model
```
keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
window_size = 30
train_set = window_dataset(x_train, window_size)
valid_set = window_dataset(x_valid, window_size)
model = keras.models.Sequential([
keras.layers.Dense(1, input_shape=[window_size])
])
optimizer = keras.optimizers.SGD(lr=1e-5, momentum=0.9)
model.compile(loss=keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
model.fit(train_set, epochs=100, validation_data=valid_set)
keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
window_size = 30
train_set = window_dataset(x_train, window_size)
model = keras.models.Sequential([
keras.layers.Dense(1, input_shape=[window_size])
])
lr_schedule = keras.callbacks.LearningRateScheduler(
lambda epoch: 1e-6 * 10**(epoch / 30))
optimizer = keras.optimizers.SGD(lr=1e-6, momentum=0.9)
model.compile(loss=keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])
plt.semilogx(history.history["lr"], history.history["loss"])
plt.axis([1e-6, 1e-3, 0, 20])
keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
window_size = 30
train_set = window_dataset(x_train, window_size)
valid_set = window_dataset(x_valid, window_size)
model = keras.models.Sequential([
keras.layers.Dense(1, input_shape=[window_size])
])
optimizer = keras.optimizers.SGD(lr=1e-5, momentum=0.9)
model.compile(loss=keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
early_stopping = keras.callbacks.EarlyStopping(patience=10)
model.fit(train_set, epochs=500,
validation_data=valid_set,
callbacks=[early_stopping])
def model_forecast(model, series, window_size):
ds = tf.data.Dataset.from_tensor_slices(series)
ds = ds.window(window_size, shift=1, drop_remainder=True)
ds = ds.flat_map(lambda w: w.batch(window_size))
ds = ds.batch(32).prefetch(1)
forecast = model.predict(ds)
return forecast
lin_forecast = model_forecast(model, series[split_time - window_size:-1], window_size)[:, 0]
lin_forecast.shape
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid)
plot_series(time_valid, lin_forecast)
keras.metrics.mean_absolute_error(x_valid, lin_forecast).numpy()
```
### Dense Model Forecasting
```
keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
window_size = 30
train_set = window_dataset(x_train, window_size)
model = keras.models.Sequential([
keras.layers.Dense(10, activation="relu", input_shape=[window_size]),
keras.layers.Dense(10, activation="relu"),
keras.layers.Dense(1)
])
lr_schedule = keras.callbacks.LearningRateScheduler(
lambda epoch: 1e-7 * 10**(epoch / 20))
optimizer = keras.optimizers.SGD(lr=1e-7, momentum=0.9)
model.compile(loss=keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])
plt.semilogx(history.history["lr"], history.history["loss"])
plt.axis([1e-7, 5e-3, 0, 30])
keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
window_size = 30
train_set = window_dataset(x_train, window_size)
valid_set = window_dataset(x_valid, window_size)
model = keras.models.Sequential([
keras.layers.Dense(10, activation="relu", input_shape=[window_size]),
keras.layers.Dense(10, activation="relu"),
keras.layers.Dense(1)
])
optimizer = keras.optimizers.SGD(lr=1e-5, momentum=0.9)
model.compile(loss=keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
early_stopping = keras.callbacks.EarlyStopping(patience=10)
model.fit(train_set, epochs=500,
validation_data=valid_set,
callbacks=[early_stopping])
dense_forecast = model_forecast(
model,
series[split_time - window_size:-1],
window_size)[:, 0]
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid)
plot_series(time_valid, dense_forecast)
keras.metrics.mean_absolute_error(x_valid, dense_forecast).numpy()
```
| github_jupyter |
# Network Measures
Generating metrics of walking edge lengths and intersection density for a hex grid
First we need to download OSM network data using OSMNX. The data is to big to download and process at once, so we do this in chunks, for each of the 17 census divisions in the region, and then patch it back together with some `ogr2ogr` merging.
```
%matplotlib inline
import pandas as pd
import geopandas as gpd
import osmnx as ox
import matplotlib.pyplot as plt
# read the shp with the boundaries
dfcd = gpd.read_file("../input_data/spatial_boundaries/CensusDivisions/2016/CensusDivisions_GGH_utm17n.shp")
# convert to WGS84 for download
dfcd = dfcd.to_crs(epsg=4326)
# setup the query for downloading data
filter_drive = ('["area"!~"yes"]'
'["highway"!~"motor|trunk|foot|proposed|construction|abandoned|platform|raceway|foot|cycleway|path|secondary_link|primary_link"]'
'["service"!~"driveway|emergency_access|parking_aisle|drive-through"]'
'["access"!~"private"]')
filter_walk = ('["area"!~"yes"]'
'["highway"!~"motor|trunk|proposed|construction|abandoned|platform|raceway"]'
'["foot"!~"no"]'
'["footway"!~"sidewalk"]'
'["service"!~"private|parking_aisle"]'
'["access"!~"private"]')
# loop over each census division boundary, downloading nodes and edges from the OSM network
# using just the streets for nodes, but all walking paths for edges
x = 0
while x < (len(dfcd)):
print(x,name)
boundary = dfcd.loc[x,"geometry"]
name = dfcd.loc[x,"CDNAME"]
x += 1
G = ox.graph_from_polygon(boundary, custom_filter=filter_drive)
G = ox.project_graph(G)
# grab nodes and put into data-frame
nodes_all = ox.graph_to_gdfs(G, edges=False)
nodes_all = nodes_all.to_crs(epsg=32617)
streets_per_node = ox.count_streets_per_node(G) # count streets per node - and join to the spatial file
streets_per_node = pd.DataFrame.from_dict(data=streets_per_node,orient='index')
streets_per_node.columns = ["streets_n"]
nodes_all = nodes_all.join(streets_per_node)
nodes_all = nodes_all.query('streets_n >= 3')
nodes_all[['lat','lon','geometry','streets_n']]
nodes_all.to_file(driver = 'ESRI Shapefile', filename= "temp/nodes/" + name + ".shp")
G = ox.graph_from_polygon(boundary, custom_filter=filter_walk)
G = ox.project_graph(G)
edges_all = ox.graph_to_gdfs(G, nodes=False)
edges_all = edges_all[["u","v","geometry"]]
edges_all.to_file(driver = 'ESRI Shapefile', filename= "temp/edges/" + name + ".shp")
```
Merge the nodes and edges in each folder using this `ogrg2ogr` snippet:
```sh
for file in *.shp
do
if [ -f merged.shp ]
then
ogr2ogr -f "ESRI Shapefile" merged.shp $file -update -append -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
else
ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
fi
done
```
Reproject in epsg 32617 (the UTM zone for the region)
```sh
ogr2ogr -t_srs EPSG:32617 merged_edges_utm.shp merged_edges.shp
ogr2ogr -t_srs EPSG:32617 merged_nodes_utm.shp merged_nodes.shp
```
Then send the merged data into the PostGIS database
```sh
shp2pgsql -I -s 32617 -W "latin1" input_data/osm_data/merged_edges_utm.shp OSM_edges_walk | psql -U ja -d urban_form_toronto
shp2pgsql -I -s 32617 -W "latin1" input_data/osm_data/merged_nodes_utm.shp OSM_nodes_streets | psql -U ja -d urban_form_toronto
```
## Edge Density
Generating the length of walking edges per hex grid in PostGIS
```sql
-- creating a spatial index for the sake of brevity
DROP INDEX IF EXISTS hex_grid_200m_gix;
CREATE INDEX hex_grid_200m_gix ON hex_grid_200m USING GIST (geom);
DROP INDEX IF EXISTS OSM_edges_walk_gix;
CREATE INDEX OSM_edges_walk_gix ON OSM_edges_walk USING GIST (geom);
-- intersect the edges with the grid, summing the edge length in each grid cells
DROP TABLE IF EXISTS out_data_hex_osmwalkedge2018;
CREATE TABLE out_data_hex_osmwalkedge2018 AS (
SELECT
hex_grid_200m.id AS hexid,
coalesce(sum
(ST_Length(
ST_Intersection(OSM_edges_walk.geom,hex_grid_200m.geom)
)),0) AS edge_length
FROM OSM_edges_walk RIGHT JOIN hex_grid_200m ON
ST_Intersects(OSM_edges_walk.geom,hex_grid_200m.geom)
GROUP BY hexid
);
-- output
\COPY out_data_hex_osmwalkedge2018 TO 'out_data_hex_osmwalkedge2018.csv' WITH (FORMAT CSV, HEADER);
```
## Intersection Density
Clustering Points
```sql
-- first we settin' up dat spatial index
DROP INDEX IF EXISTS OSM_nodes_streets_gix;
CREATE INDEX OSM_nodes_streets_gix ON OSM_nodes_streets USING GIST (geom);
-- cluster the nodes, as to not have several points at parrelel street intersections
-- built from
-- https://gis.stackexchange.com/questions/11567/spatial-clustering-with-postgis
DROP TABLE IF EXISTS temp_cluster_nodes;
CREATE TABLE temp_cluster_nodes AS
(
SELECT
row_number() over () AS gid,
-- gc AS geom_collection,
ST_Buffer(ST_Centroid(gc),25) AS geom
-- ST_MinimumBoundingCircle(gc) AS circle
FROM (
SELECT
unnest(ST_ClusterWithin(geom, 25)) AS gc
FROM OSM_nodes_streets
) f
);
-- join and count the number of streets per intersection to the clustered points
DROP TABLE IF EXISTS OSM_nodes_streets_clustered;
CREATE TABLE OSM_nodes_streets_clustered AS (
SELECT
sum(coalesce(OSM_nodes_streets.streets_n,0)) AS n_streets,
ST_Centroid(temp_cluster_nodes.geom) AS geom,
temp_cluster_nodes.gid AS gid
FROM
OSM_nodes_streets RIGHT OUTER JOIN temp_cluster_nodes ON ST_Intersects(OSM_nodes_streets.geom,temp_cluster_nodes.geom)
GROUP BY temp_cluster_nodes.gid, temp_cluster_nodes.geom
);
-- create spatial index on this new set of points
DROP INDEX IF EXISTS OSM_nodes_streets_clustered_gix;
CREATE INDEX OSM_nodes_streets_clustered_gix ON OSM_nodes_streets_clustered USING GIST (geom);
-- subset for equal to 3 streets, and greater than 3 streets
DROP TABLE IF EXISTS temp_i3;
CREATE TABLE temp_i3 AS (
SELECT * FROM OSM_nodes_streets_clustered
WHERE n_streets < 4
);
DROP TABLE IF EXISTS temp_i4;
CREATE TABLE temp_i4 AS (
SELECT * FROM OSM_nodes_streets_clustered
WHERE n_streets > 3
);
-- spatial index on these new points
DROP INDEX IF EXISTS temp_i3_gix;
CREATE INDEX temp_i3_gix ON temp_i3 USING GIST (geom);
DROP INDEX IF EXISTS temp_i4_gix;
CREATE INDEX temp_i4_gix ON temp_i4 USING GIST (geom);
-- count points per polygon (hex)
DROP TABLE IF EXISTS out_data_hex_int3way2018;
CREATE TABLE out_data_hex_int3way2018 AS (
SELECT
coalesce(count(temp_i3.n_streets),0) AS int3way,
hex_grid_200m.id AS hexid
FROM
temp_i3 RIGHT OUTER JOIN hex_grid_200m ON ST_Intersects(temp_i3.geom,hex_grid_200m.geom)
GROUP BY hexid
);
DROP TABLE IF EXISTS out_data_hex_int4way2018;
CREATE TABLE out_data_hex_int4way2018 AS (
SELECT
coalesce(count(temp_i4.n_streets),0) AS int4way,
hex_grid_200m.id AS hexid
FROM
temp_i4 RIGHT OUTER JOIN hex_grid_200m ON ST_Intersects(temp_i4.geom,hex_grid_200m.geom)
GROUP BY hexid
);
-- output the data
\COPY out_data_hex_int4way2018 TO 'out_data_hex_int4way2018.csv' WITH (FORMAT CSV, HEADER);
\COPY out_data_hex_int3way2018 TO 'out_data_hex_int3way2018.csv' WITH (FORMAT CSV, HEADER);
```
| github_jupyter |
## Q-learning
This notebook will guide you through implementation of vanilla Q-learning algorithm.
You need to implement QLearningAgent (follow instructions for each method) and use it on a number of tests below.
```
# In google collab, uncomment this:
# !wget https://bit.ly/2FMJP5K -q -O setup.py
# !bash setup.py 2>&1 1>stdout.log | tee stderr.log
# This code creates a virtual display to draw game images on.
# If you are running locally, just ignore it
# import os
# if type(os.environ.get("DISPLAY")) is not str or len(os.environ.get("DISPLAY")) == 0:
# !bash ../xvfb start
# %env DISPLAY = : 1
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
%%writefile qlearning.py
from collections import defaultdict
import random
import math
import numpy as np
class QLearningAgent:
def __init__(self, alpha, epsilon, discount, get_legal_actions):
"""
Q-Learning Agent
based on https://inst.eecs.berkeley.edu/~cs188/sp19/projects.html
Instance variables you have access to
- self.epsilon (exploration prob)
- self.alpha (learning rate)
- self.discount (discount rate aka gamma)
Functions you should use
- self.get_legal_actions(state) {state, hashable -> list of actions, each is hashable}
which returns legal actions for a state
- self.get_qvalue(state,action)
which returns Q(state,action)
- self.set_qvalue(state,action,value)
which sets Q(state,action) := value
!!!Important!!!
Note: please avoid using self._qValues directly.
There's a special self.get_qvalue/set_qvalue for that.
"""
self.get_legal_actions = get_legal_actions
self._qvalues = defaultdict(lambda: defaultdict(lambda: 0))
self.alpha = alpha
self.epsilon = epsilon
self.discount = discount
def get_qvalue(self, state, action):
""" Returns Q(state,action) """
return self._qvalues[state][action]
def set_qvalue(self, state, action, value):
""" Sets the Qvalue for [state,action] to the given value """
self._qvalues[state][action] = value
#---------------------START OF YOUR CODE---------------------#
def get_value(self, state):
"""
Compute your agent's estimate of V(s) using current q-values
V(s) = max_over_action Q(state,action) over possible actions.
Note: please take into account that q-values can be negative.
"""
possible_actions = self.get_legal_actions(state)
# If there are no legal actions, return 0.0
if len(possible_actions) == 0:
return 0.0
<YOUR CODE HERE >
return value
def update(self, state, action, reward, next_state):
"""
You should do your Q-Value update here:
Q(s,a) := (1 - alpha) * Q(s,a) + alpha * (r + gamma * V(s'))
"""
# agent parameters
gamma = self.discount
learning_rate = self.alpha
<YOUR CODE HERE >
self.set_qvalue(state, action, < YOUR_QVALUE > )
def get_best_action(self, state):
"""
Compute the best action to take in a state (using current q-values).
"""
possible_actions = self.get_legal_actions(state)
# If there are no legal actions, return None
if len(possible_actions) == 0:
return None
<YOUR CODE HERE >
return best_action
def get_action(self, state):
"""
Compute the action to take in the current state, including exploration.
With probability self.epsilon, we should take a random action.
otherwise - the best policy action (self.get_best_action).
Note: To pick randomly from a list, use random.choice(list).
To pick True or False with a given probablity, generate uniform number in [0, 1]
and compare it with your probability
"""
# Pick Action
possible_actions = self.get_legal_actions(state)
action = None
# If there are no legal actions, return None
if len(possible_actions) == 0:
return None
# agent parameters:
epsilon = self.epsilon
<YOUR CODE HERE >
return chosen_action
```
### Try it on taxi
Here we use the qlearning agent on taxi env from openai gym.
You will need to insert a few agent functions here.
```
import gym
env = gym.make("Taxi-v2")
n_actions = env.action_space.n
from qlearning import QLearningAgent
agent = QLearningAgent(
alpha=0.5,
epsilon=0.25,
discount=0.99,
get_legal_actions=lambda s: range(n_actions))
def play_and_train(env, agent, t_max=10**4):
"""
This function should
- run a full game, actions given by agent's e-greedy policy
- train agent using agent.update(...) whenever it is possible
- return total reward
"""
total_reward = 0.0
s = env.reset()
for t in range(t_max):
# get agent to pick action given state s.
a = <YOUR CODE >
next_s, r, done, _ = env.step(a)
# train (update) agent for state s
<YOUR CODE HERE >
s = next_s
total_reward += r
if done:
break
return total_reward
from IPython.display import clear_output
rewards = []
for i in range(1000):
rewards.append(play_and_train(env, agent))
agent.epsilon *= 0.99
if i % 100 == 0:
clear_output(True)
print('eps =', agent.epsilon, 'mean reward =', np.mean(rewards[-10:]))
plt.plot(rewards)
plt.show()
```
# Binarized state spaces
Use agent to train efficiently on CartPole-v0.
This environment has a continuous set of possible states, so you will have to group them into bins somehow.
The simplest way is to use `round(x,n_digits)` (or numpy round) to round real number to a given amount of digits.
The tricky part is to get the n_digits right for each state to train effectively.
Note that you don't need to convert state to integers, but to __tuples__ of any kind of values.
```
env = gym.make("CartPole-v0")
n_actions = env.action_space.n
print("first state:%s" % (env.reset()))
plt.imshow(env.render('rgb_array'))
```
### Play a few games
We need to estimate observation distributions. To do so, we'll play a few games and record all states.
```
all_states = []
for _ in range(1000):
all_states.append(env.reset())
done = False
while not done:
s, r, done, _ = env.step(env.action_space.sample())
all_states.append(s)
if done:
break
all_states = np.array(all_states)
for obs_i in range(env.observation_space.shape[0]):
plt.hist(all_states[:, obs_i], bins=20)
plt.show()
```
## Binarize environment
```
from gym.core import ObservationWrapper
class Binarizer(ObservationWrapper):
def observation(self, state):
# state = <round state to some amount digits.>
# hint: you can do that with round(x,n_digits)
# you will need to pick a different n_digits for each dimension
return tuple(state)
env = Binarizer(gym.make("CartPole-v0"))
all_states = []
for _ in range(1000):
all_states.append(env.reset())
done = False
while not done:
s, r, done, _ = env.step(env.action_space.sample())
all_states.append(s)
if done:
break
all_states = np.array(all_states)
for obs_i in range(env.observation_space.shape[0]):
plt.hist(all_states[:, obs_i], bins=20)
plt.show()
```
## Learn binarized policy
Now let's train a policy that uses binarized state space.
__Tips:__
* If your binarization is too coarse, your agent may fail to find optimal policy. In that case, change binarization.
* If your binarization is too fine-grained, your agent will take much longer than 1000 steps to converge. You can either increase number of iterations and decrease epsilon decay or change binarization.
* Having 10^3 ~ 10^4 distinct states is recommended (`len(QLearningAgent._qvalues)`), but not required.
* A reasonable agent should get to an average reward of >=50.
```
agent = QLearningAgent(
alpha=0.5,
epsilon=0.25,
discount=0.99,
get_legal_actions=lambda s: range(n_actions))
rewards = []
for i in range(1000):
rewards.append(play_and_train(env, agent))
# OPTIONAL YOUR CODE: adjust epsilon
if i % 100 == 0:
clear_output(True)
print('eps =', agent.epsilon, 'mean reward =', np.mean(rewards[-10:]))
plt.plot(rewards)
plt.show()
```
| github_jupyter |
# The Matrix Profile
## Laying the Foundation
At its core, the STUMPY library efficiently computes something called a <i><b>matrix profile</b>, a vector that stores the [z-normalized Euclidean distance](https://youtu.be/LnQneYvg84M?t=374) between any subsequence within a time series and its nearest neigbor</i>.
To fully understand what this means, let's take a step back and start with a simple illustrative example along with a few basic definitions:
## Time Series with Length n = 13
```
time_series = [0, 1, 3, 2, 9, 1, 14, 15, 1, 2, 2, 10, 7]
n = len(time_series)
```
To analyze this time series with length `n = 13`, we could visualize the data or calculate global summary statistics (i.e., mean, median, mode, min, max). If you had a much longer time series, then you may even feel compelled to build an ARIMA model, perform anomaly detection, or attempt a forecasting model but these methods can be complicated and may often have false positives or no interpretable insights.

However, if we were to apply <i>Occam's Razor</i>, then what is the most <b>simple and intuitive</b> approach that we could take analyze to this time series?
To answer this question, let's start with our first defintion:
## Subsequence /ˈsəbsəkwəns/ noun
### <i>a part or section of the full time series</i>
So, the following are all considered subsequences of our `time_series` since they can all be found in the time series above.



```
print(time_series[0:2])
print(time_series[4:7])
print(time_series[2:10])
```
We can see that each subsequence can have a different sequence length that we'll call `m`. So, for example, if we choose `m = 4`, then we can think about how we might compare any two subsequences of the same length.
```
m = 4
i = 0 # starting index for the first subsequence
j = 8 # starting index for the second subsequence
subseq_1 = time_series[i:i+m]
subseq_2 = time_series[j:j+m]
print(subseq_1, subseq_2)
```

One way to compare any two subsequences is to calculate what is called the Euclidean distance.
## Euclidean Distance /yo͞oˈklidēən/ /ˈdistəns/ noun
### <i>the straight-line distance between two points</i>

```
import math
D = 0
for k in range(m):
D += (time_series[i+k] - time_series[j+k])**2
print(f"The square root of {D} = {math.sqrt(D)}")
```
## Distance Profile - Pairwise Euclidean Distances
Now, we can take this a step further where we keep one subsequence the same (reference subsequence), change the second subsequence in a sliding window manner, and compute the Euclidean distance for each window. The resulting vector of pairwise Euclidean distances is also known as a <i><b>distance profile</b></i>.

Of course, not all of these distances are useful. Specifically, the distance for the self match (or trivial match) isn't informative since the distance will be always be zero when you are comparing a subsequence with itself. So, we'll ignore it and, instead, take note of the next smallest distance from the distance profile and choose that as our best match:

Next, we can shift our reference subsequence over one element at a time and repeat the same sliding window process to compute the distance profile for each new reference subsequence.

## Distance Matrix
If we take all of the distance profiles that were computed for each reference subsequence and stack them one on top of each other then we get something called a <i><b>distance matrix</b></i>

## The Real Problem - The Brute Force Approach
Now, it might seem pretty straightforward at this point but what we need to do is consider how to compute this full distance matrix efficiently. Let's start with the brute force approach:
```
for i in range(n-m+1):
for j in range(n-m+1):
D = 0
for k in range(m):
D += (time_series[i+k] - time_series[j+k])**2
D = math.sqrt(D)
```
At first glance, this may not look too bad but if we start considering both the computational complexity as well as the spatial complexity then we begin to understand the real problem. It turns out that, for longer time series (i.e., <i>n >> 10,000</i>) the computational complexity is <i>O(n<sup>2</sup>m)</i> (as evidenced by the three for loops in the code above) and the spatial complexity for storing the full distance matrix is <i>O(n<sup>2</sup>)</i>.
To put this into perspective, imagine if you had a single sensor that collected data 20 times/min over the course of 5 years. This would result:
```
n = 20 * 60 * 24 * 364 * 5 # 20 times/min x 60 mins/hour x 24 hours/day x 365 days/year x 5 years
print(f"There would be n = {n} data points")
```
Assuming that each calculation in the inner loop takes 0.0000001 seconds then this would take:
```
time = 0.0000001 * (n * n - n)/2
print(f"It would take {time} seconds to compute")
```
<b>Which is equivalent to 1,598.7 days (or 4.4 years) and 11.1 PB of memory to compute!</b> So, it is clearly not feasible to compute the distance matrix using our naive brute force method. And this is where the <i><b>matrix profile</b></i> comes into play. Recall,
## Matrix Profile /ˈmātriks/ /ˈprōˌfīl/ noun
### a vector that stores the [(z-normalized) Euclidean distance](https://youtu.be/LnQneYvg84M?t=374) between any subsequence within a time series and its nearest neigbor
Practically, what this means is that the matrix profile is only interested in storing the smallest non-trivial distances from each distance profile, which significantly reduces the spatial complexity to O(n):

But we still haven't figured out how to reduce the computational complexity and this is precisely the problem that is being addressed by [STUMPY](https://github.com/TDAmeritrade/stumpy).
## STUMPY
In the fall of 2016, researchers from the [University of California, Riverside](https://www.cs.ucr.edu/~eamonn) and the [University of New Mexico](https://www.cs.unm.edu/~mueen/) published a beautiful set of [back-to-back papers](https://www.cs.ucr.edu/~eamonn/MatrixProfile.html) that described an <u>exact method</u> called <i><b>STOMP</b></i> for computing the matrix profile for any time series with a computational complexity of O(n<sup>2</sup>)! They also further demonstrated this using GPUs and this method approach is called <i><b>GPU-STOMP</b></i>.
With the academics, data scientists, and developers in mind, we have taken some of these concepts and have open sourced STUMPY, a powerful and scalable library that efficiently computes the matrix profile. And, thanks to other open source software such as [Numba](http://numba.pydata.org/) and [Dask](https://dask.org/), our implementation can be both highly parallelized (for a single server) and highly distributed (across multiple servers). We've tested STUMPY on as many as 256 CPU cores that are spread across 32 servers and have achieved similiar [performance](https://github.com/TDAmeritrade/stumpy#performance) to the published GPU-STOMP work.
## Conclusion
According to the original authors, "these are the best ideas in times series data mining in the last two decades" and "given the matrix profile, [most time series data mining problems are trivial to solve in a few lines of code](https://www.cs.ucr.edu/~eamonn/100_Time_Series_Data_Mining_Questions__with_Answers.pdf)".
From our experience, this is definitely true and we are excited to share STUMPY with you! Please reach out and tell us know how STUMPY has enabled your time series analysis work as we'd love to hear from you!
| github_jupyter |
```
!pip install numpy==1.20.3
!pip install sentencepiece==0.1.96
import csv
import re
import numpy as np
import sentencepiece as spm
from IPython.display import Audio
!git clone https://github.com/octanove/neuralmorse.git
token2symbol = {}
with open('neuralmorse/assignment.tsv') as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
token2symbol[row[0]] = row[1]
token2symbol['▁'] = ' '
sp = spm.SentencePieceProcessor(model_file='neuralmorse/neuralmorse.sp.model')
SR = 16000
unit = 0.1 # length of one dot
u = np.linspace(0, unit, int(unit*SR))
u3 = np.linspace(0, unit*3, int(unit*SR*3))
freq_e4 = 329.63
freq_a4 = 440.00
freq_b4 = 493.88
freq_e5 = 659.25
space = np.zeros_like(u)
fade_time = 0.003
fade_in = np.linspace(0, 1, int(fade_time*SR))
fade_out = np.linspace(1, 0, int(fade_time*SR))
sus_u = np.ones((int(unit*SR) - 2*int(fade_time*SR)))
sus_u3 = np.ones((int(unit*3*SR) - 2*int(fade_time*SR)))
env_u = np.concatenate((fade_in, sus_u, fade_out))
env_u3 = np.concatenate((fade_in, sus_u3, fade_out))
element2audio = {
'a': np.sin(2 * np.pi * freq_e4 * u) * env_u,
'A': np.sin(2 * np.pi * freq_e4 * u3) * env_u3,
'b': np.sin(2 * np.pi * freq_a4 * u) * env_u,
'B': np.sin(2 * np.pi * freq_a4 * u3) * env_u3,
'c': np.sin(2 * np.pi * freq_b4 * u) * env_u,
'C': np.sin(2 * np.pi * freq_b4 * u3) * env_u3,
'd': np.sin(2 * np.pi * freq_e5 * u) * env_u,
'D': np.sin(2 * np.pi * freq_e5 * u3) * env_u3,
' ': space,
}
def normalize(text):
text = text.lower()
text = text.replace("’", "'") # right single quotation mark -> apostrophe
text = text.replace("‘", "'") # left single quotation mark -> apostrophe
text = text.replace('“', '"') # left double quotation mark -> quotation mark
text = text.replace('”', '"') # right double quotation mark -> quotation mark
text = text.replace('–', '-') # en dash -> hyphen
text = text.replace('—', '-') # em dash -> hyphen
text = text.replace("\u00AD", '') # soft hyphen
return text
REPLACES = [
(" can ' t ", " ca n't "),
(" could n ' t ", " could n't "),
(" co ul d n ' t ", " could n't "),
(" won ' t ", " wo n't "),
(" would n ' t ", " would n't "),
(" don ' t ", " do n't "),
(" d on ' t ", " do n't "),
(" doesn ' t ", " does n't "),
(" do es n ' t ", " does n't "),
(" didn ' t ", " did n't "),
(" d id n ' t ", " did n't "),
(" have n ' t ", " have n't "),
(" has n ' t ", " has n't "),
(" had n ' t ", " had n't "),
(" are n ' t ", " are n't "),
(" is n ' t ", " is n't "),
(" was n ' t ", " was n't "),
(" were n ' t ", " were n't "),
(" should n ' t ", " should n't "),
(" must n ' t ", " must n't "),
(" might n ' t ", " might n't "),
(" need n ' t ", " need n't "),
(" ' m ", " 'm "),
(" ' d ", " 'd "),
(" ' s ", " 's "),
(" ' re ", " 're "),
(" ' ll ", " 'll "),
(" ' ve ", " 've "),
(" didn ", " did n "),
(" doesn ", " does n ")
]
def postprocess(text):
text = re.sub(r'▁([^ ])', '▁ \\1', text)
text = re.sub(r'^▁ ', '', text)
for before, after in REPLACES:
text = text.replace(before, after)
return text
def tokenize(text):
text = normalize(text)
token_ids = sp.encode(text)
tokens = sp.id_to_piece(token_ids)
tokens = postprocess(' '.join(tokens))
return tokens
def tokens2audio(tokens):
elements = []
for token in tokens.split(' '):
elements.append(' '.join(token2symbol[token]))
elements = ' '.join(elements)
audio = [element2audio[e] for e in elements]
audio = np.concatenate(audio)
return audio, elements
text = 'NeuralMorse is a method for encoding text with eight tonal alphabets'
tokens = tokenize(text)
print('tokens:', tokens)
audio, elements = tokens2audio(tokens)
print('elements:', elements)
Audio(audio, rate=SR)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/mbarbetti/unifi-physics-lab3/blob/main/CL_efficacia_vaccino.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Calcolo del livello di confidenza per l'efficacia di un vaccino sulla base dei dati riportati in tabella

```
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import binom
!pip install -q iminuit
from iminuit import Minuit
plt.rcParams['figure.figsize'] = [16, 8]
# data from table
nVtot = 5258
nVpos = 64
nCtot = 5210
nCpos = 154
#define negative log likelihood
#p = probability to be positive for the control sample
#eff = efficacy of vaccine defined such the p*(1-eff) = probability to be positive for the vaccinated sample
#the likelihood is defined as L(p,eff) = binomial(nCpos, nCtot,p)*binomial(nVpos,nVtot,p*(1-eff))
#hence the NLL is
def NLL(p, eff):
nlogL = -binom.logpmf(nCpos, nCtot, p)-binom.logpmf(nVpos, nVtot, p*(1-eff))
return nlogL
#find minimum of NLL vs p and eff
#starting points are taken from the table
m = Minuit(NLL, p=0.03, eff=0.595)
m.errordef = Minuit.LIKELIHOOD # == 0.5 calculate 68.3% (1 sigma) error
#m.errordef = Minuit.LIKELIHOOD*3.84 # == 0.5*3.84 calculate 95% CL interval
m.migrad()
m.hesse()
m.minos()
#m.migrad()
### Check results from Minuit and print confidence intervals at 95%
p_fit = m.values['p']
eff_fit = m.values['eff']
p_fit_err = m.errors['p']
eff_fit_err = m.errors['eff']
### Print the results
print(f'Parameters from fit:\n\tp = {p_fit:.3f} +- {p_fit_err:.3f} \n\teff = {eff_fit:.3f} +- {eff_fit_err:.3f}')
m.draw_mncontour('eff','p', cl=[0.39,0.68])
#calculate 95% interval with MINOS and print result
m.minos(cl=0.95)
eff_fit = m.values['eff']
eff_low_err = m.merrors['eff'].lower
eff_up_err = m.merrors['eff'].upper
### Print the results
print(f'Parameters from fit: \n\teff = {eff_fit:.3f} + {eff_up_err:.3f} {eff_low_err:.3f}')
print(f'Interval at 95% CL: [{eff_fit+eff_low_err:.3f},{eff_fit+eff_up_err:.3f}]')
#show NLL profile vs eff
m.draw_mnprofile('eff',bound=3)
plt.show()
```
| github_jupyter |
# A simple waveform demo
Select an audio file to explore. Use the tools on the left to navigate the waveform and click a button to play a portion of the waveform in your browser.
If running in a BinderHub instance instead of in a local notebook, it might be necessary to change the `default_jupyter_url` in the code.
```
from bokeh_phon.models.audio_plot import AudioPlot
from bokeh_phon.utils import remote_jupyter_proxy_url_callback, default_jupyter_url
from phonlab.utils import dir2df
from bokeh.models import Button, Select
from bokeh.io import show, output_notebook
from bokeh.layouts import column
import parselmouth
import numpy as np
output_notebook()
# The remote_jupyter_proxy_url function is required when running on a BinderHub instance.
# Change the default_jupyter_url value to match the hostname of your instance after it has
# started. The current value is the most frequent result when launching from mybinder.org.
# Note that default_jupyter_url must be import from bokeh_phon.utils in order for it to be
# available to the remote_jupyter_proxy_url function.
# Change to None if running locally.
default_jupyter_url = 'https://hub.gke.mybinder.org/'
#default_jupyter_url = None
def myapp(doc):
def load_wav_cb(attr, old, new):
snd = parselmouth.Sound(new)
samples = np.squeeze(snd.values).astype(np.float32)
ap.fs = np.float32(snd.sampling_frequency)
ap.wav.data_source.data = {
'times': np.arange(len(samples)) / ap.fs,
'samples': samples
}
ap.selbox.left = 0.0
ap.selbox.right = 0.0
ap.selbox.visible = False
fdf = dir2df('..', fnpat='.*\.wav$', dirpat='resource')
fdf['fpath'] = '../' + fdf.relpath.str.cat(fdf.fname, sep='/')
options = [('', 'Choose an audio file')] + list(fdf.loc[:,['fpath', 'fname']].itertuples(index=False, name=None))
fselect = Select(options=options)
fselect.on_change('value', load_wav_cb)
ap = AudioPlot(
samples=np.array([0, 0]),
fs=44100,
# Remaining arguments are passed to Figure().
plot_height=200,
toolbar_location='left'
)
playallbtn = Button(label='Play all')
playallbtn.js_on_event('button_click', ap.js_playall_cb)
playselbtn = Button(label='Play selection')
playselbtn.js_on_event('button_click', ap.js_playsel_cb)
playxrbtn = Button(label='Play x range')
playxrbtn.js_on_event('button_click', ap.js_playxr_cb)
col = column(fselect, playallbtn, playselbtn, playxrbtn, ap)
doc.add_root(col)
return doc
# The notebook_url parameter is required when running in a BinderHub instance.
# If running a local notebook, omit that parameter.
if default_jupyter_url is None:
show(myapp) # For running a local notebook
else:
show(myapp, notebook_url=remote_jupyter_proxy_url_callback)
```
| github_jupyter |
```
import pandas as pd
import re
from collections import defaultdict
df = pd.read_csv("../top1000.csv")
df_t = pd.read_csv("top1000_num.csv")
df
df_t
def fine_word(dft, word):
idx = dft.find(word)
if(idx<0):
return False
else:
return True
def find_dfs(df_t, word, num, go=0):
hangul = re.compile('[^ㄱ-ㅣ가-힣]+')
results = []
test = df_t[df_t['Pair'].apply(lambda x: fine_word(x,word))]
for i,t in test[:num*2].iterrows():
f_word = t['Pair'][t['Pair'].find(word)+len(word):]
result = hangul.sub('', f_word)
if(result):
if(go):
print(result, t["Num"])
results.append(result)
return results
def fine_list(dft, lists):
return (dft in lists)
def make_relation(df_t, word, num,):
hangul = re.compile('[^ㄱ-ㅣ가-힣]+')
words = []
words = find_dfs(df_t, word, num,go=1)
words.append(word)
print(words)
t = df[df["Source"]==words[0]]
for word in words:
t_df = df[df["Source"]==word]
t = t.append(t_df)
return t
def make_relation_network(df_t, word, num,data_num):
hangul = re.compile('[^ㄱ-ㅣ가-힣]+')
words = []
words = find_dfs(df_t, word, num,go=1)
words.append(word)
print(words)
t = df[df["Source"]==words[0]]
for word in words:
t_df = df[df["Source"]==word]
top_list = find_dfs(df_t, word, data_num)
t = t.append(t_df[(t_df['Target'].apply(lambda x: fine_list(x,top_list))) & (t_df['Source']== word)])
print(top_list)
return t
def make_and_save_netword(word):
node_num = 5
data_num = 10
make_relation(df_t, word , node_num).to_csv("data/" + word + str(node_num)+".csv",index=False)
#make_relation_network(df_t, word , node_num, data_num).to_csv("data/" + word + str(node_num)+"_num_"+ str(data_num)+".csv",index=False)
def top_keyword(word):
df = pd.read_csv("data/"+word+"5.csv")
dic = defaultdict(int)
for row in df.itertuples(index=True, name='Pandas'):
dic[getattr(row, "Source")]+=1
dic[getattr(row, "Target")]+=1
dic = dict(dic)
dic = sorted(dic.items(), key=lambda t : t[1], reverse=True)
return dict(dic)
make_and_save_netword("군대")
top_keyword("군대")
top_keyword("국회의원")
top_keyword("갑질")
make_and_save_netword("서민")
make_and_save_netword("소통")
make_and_save_netword("탄핵")
make_and_save_netword("대기업")
make_and_save_netword("성장")
make_and_save_netword("경제")
make_and_save_netword("국회의원")
make_and_save_netword("대통령")
make_and_save_netword("북한")
make_and_save_netword("갑질")
```
| github_jupyter |
# GAN
```
from keras.datasets import mnist
from keras.layers import Input, Dense, Reshape, Flatten, Dropout
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.models import Sequential, Model
from keras.optimizers import Adam
import matplotlib.pyplot as plt
import sys
import numpy as np
```
In a GAN we want to construct a distribution $\mathbb{P}_{g}$, called a generative distribution, which mimics the real distribution $\mathbb{P}_{r}$.
For that we use a neural network $G=g_{\theta}$, a noise $p(z)$ such that $x'=g_{\theta}(z), z \sim p(z)$ and a discriminator D:
$$\underset{D}{\text{max}} \ \underset{g_{\theta}}{\text{min}} \ L(D,g_{\theta}) = \underset{x \sim \mathbb{P}_{r}}{\mathbb{E}}[\log(D(x))]+ \underset{z \sim p(z)}{\mathbb{E}}[\log(1-D(g_{\theta}(z)))]$$
<img src="imgs/gan.png" alt="Drawing" style="width: 500px;"/>
Load the MNIST dataset
```
from keras.datasets import mnist
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Rescale -1 to 1
X_train = x_train / 127.5 - 1.
X_train = np.expand_dims(x_train, axis=3)
X_train.shape
x_test.shape
img_rows = 28
img_cols = 28
channels = 1
img_shape = (img_rows, img_cols, channels)
plt.imshow(X_train[46].reshape(28,28))
plt.gray()
plt.show()
```
##### Question 1. Create a generator model
The generator has the following layers :
- A dense layer of width 256 and take as input the dimension of the latent space (this is a paremeter that must be configurable
- A LeakyRelu activation with parameter alpha=0.2 : what does it correspond to ?
- We use batch normalization of momentum 0.8 : what does it correspond to ?
- A second dense layer of width 512
- We use same LeakyRelu and batch normalization for this layer
- A third Dense Layer of width 1024 with same batch normalization and LeakyRelu activation
- A last dense layer with width equal to the shape of the output image flattened
- The activation is tanh : what does is correspond to ?
The function must take as input a vector of dimension the dimension of the latent space and representing the noise and return Model
```
def build_generator(img_shape,latent_dim=100):
model = Sequential()
model.add(Dense(256, input_dim=latent_dim))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model.add(Dense(512))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model.add(Dense(1024))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model.add(Dense(np.prod(img_shape), activation='tanh'))
model.add(Reshape(img_shape))
noise = Input(shape=(latent_dim,))
img = model(noise)
return Model(noise, img)
gen=build_generator(img_shape=img_shape)
gen.summary()
```
##### Question 2. Build the discriminator
The discriminator has the following layers :
- A Dense layer of width 512 with LeakyRelu activation with parameter alpha=0.2
- A second Dense layer with LeakyRelu activation with parameter alpha=0.2
- A last Dense layer for the binary classification
The model must take as input an image and output the the classification result
```
def build_discriminator(img_shape):
model = Sequential()
model.add(Flatten(input_shape=img_shape))
model.add(Dense(512))
model.add(LeakyReLU(alpha=0.2))
model.add(Dense(256))
model.add(LeakyReLU(alpha=0.2))
model.add(Dense(1, activation='sigmoid'))
img = Input(shape=img_shape)
validity = model(img)
return Model(img, validity)
```
##### Question 3. Build the two neural networks with the MNIST configuration and print their properties. We will use 100 as the dimension of the latent space.
```
latent_dim=100
generator=build_generator(img_shape,latent_dim=latent_dim)
generator.layers[1].summary()
discriminator=build_discriminator(img_shape)
discriminator.layers[1].summary()
```
##### 4. Compile the model
The optimizer chosen is 'Adam' with parameters 0.0002 and 0.5 : what does it correspond to ?
First compile the discriminator
```
optimizer = Adam(0.0002, 0.5)
# Build and compile the discriminator
discriminator.compile(loss='binary_crossentropy',optimizer=optimizer,metrics=['accuracy'])
```
To compile the generator it is more tricky : (live explanations)
```
# The generator takes noise as input and generates imgs
z = Input(shape=(100,))
img = generator(z)
# For the combined model we will only train the generator
discriminator.trainable = False
# The discriminator takes generated images as input and determines validity
validity = discriminator(img)
# The combined model (stacked generator and discriminator)
# Trains the generator to fool the discriminator
combined = Model(z, validity)
combined.compile(loss='binary_crossentropy', optimizer=optimizer)
```
##### Question 5. Write a function that samples 25 images from a normal noise $\mathcal{N}(0,I_{d})$ with d configurable. It should be configurable wether we save or plot the images
```
def sample_images(generator,latent_dim=100,toplot=False,epoch=None):
r, c = 5, 5
noise = np.random.normal(0, 1, (r * c, latent_dim))
gen_imgs = generator.predict(noise)
# Rescale images 0 - 1
gen_imgs = 0.5 * gen_imgs + 0.5
fig, axs = plt.subplots(r, c,figsize=(10,10))
cnt = 0
for i in range(r):
for j in range(c):
axs[i,j].imshow(gen_imgs[cnt, :,:,0], cmap='gray')
axs[i,j].axis('off')
cnt += 1
if toplot:
plt.show()
else:
fig.savefig("./results/%d.png" % epoch)
plt.close()
```
##### Question 6. What is the definition of the binary cross entropy ? Train the model using batch_size of 32 and 10000 epochs.
What can you say about the results?
The binary cross entropy is defined as $L(y,p)=-(y\log(p)+(1-y)\log(1-p))$ where $p$ is the predicted probability and $y$ the true class
```
batch_size=32
epochs=10000
valid = np.ones((batch_size, 1))
fake = np.zeros((batch_size, 1))
dloss_onreal=[]
dloss_onfake=[]
total_dloss=[]
gloss=[]
for epoch in range(epochs):
# ---------------------
# Train Discriminator
# ---------------------
# Select a random batch of images
idx = np.random.randint(0, X_train.shape[0], batch_size)
imgs = X_train[idx]
noise = np.random.normal(0, 1, (batch_size, latent_dim)) #z
# Generate a batch of new images
gen_imgs = generator.predict(noise) #g_theta(z)
# Train the discriminator
d_loss_real = discriminator.train_on_batch(imgs, valid) #train on D(x)
d_loss_fake = discriminator.train_on_batch(gen_imgs, fake) #train on D(g_theta(z))
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
# ---------------------
# Train Generator
# ---------------------
noise = np.random.normal(0, 1, (batch_size, latent_dim))
# Train the generator (to have the discriminator label samples as valid)
g_loss = combined.train_on_batch(noise, valid)
dloss_onreal.append(d_loss_real)
dloss_onfake.append(d_loss_real)
total_dloss.append(d_loss)
gloss.append(g_loss)
if epoch % 200 ==0:
print('epoch number : ',str(epoch))
sample_images(generator,epoch=epoch)
```
We see clearly the mode collapse issue
##### 7. Sample 25 generated images and plot the loss curves
```
sample_images(generator,toplot=True)
plt.figure(figsize=(10,10))
plt.plot(np.array(total_dloss)[:,0])
plt.plot(gloss)
plt.legend(['Total D loss','G loss'])
plt.show()
```
| 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.
#@title MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
```
# Regression: predict fuel efficiency
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/keras/basic_regression"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/keras/basic_regression.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/keras/basic_regression.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
In a *regression* problem, we aim to predict the output of a continuous value, like a price or a probability. Contrast this with a *classification* problem, where we aim to predict a discrete label (for example, where a picture contains an apple or an orange).
This notebook uses the classic [Auto MPG](https://archive.ics.uci.edu/ml/datasets/auto+mpg) Dataset and builds a model to predict the fuel efficiency of late-1970s and early 1980s automobiles. To do this, we'll provide the model with a description of many models from that time period. This description includes attributes like: cylinders, displacement, horsepower, and weight.
This example uses the `tf.keras` API, see [this guide](https://www.tensorflow.org/guide/keras) for details.
```
# Use seaborn for pairplot
!pip install seaborn
from __future__ import absolute_import, division, print_function
import pathlib
import pandas as pd
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
print(tf.__version__)
```
## The Auto MPG dataset
The dataset is available from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/).
### Get the data
First download the dataset.
```
dataset_path = keras.utils.get_file("auto-mpg.data", "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data")
dataset_path
```
Import it using pandas
```
column_names = ['MPG','Cylinders','Displacement','Horsepower','Weight',
'Acceleration', 'Model Year', 'Origin']
raw_dataset = pd.read_csv(dataset_path, names=column_names,
na_values = "?", comment='\t',
sep=" ", skipinitialspace=True)
dataset = raw_dataset.copy()
dataset.tail()
```
### Clean the data
The dataset contains a few unknown values.
```
dataset.isna().sum()
```
To keep this initial tutorial simple drop those rows.
```
dataset = dataset.dropna()
```
The `"Origin"` column is really categorical, not numeric. So convert that to a one-hot:
```
origin = dataset.pop('Origin')
dataset['USA'] = (origin == 1)*1.0
dataset['Europe'] = (origin == 2)*1.0
dataset['Japan'] = (origin == 3)*1.0
dataset.tail()
```
### Split the data into train and test
Now split the data into a train and a test set.
We will use the test set in the final evaluation of out model.
```
train_dataset = dataset.sample(frac=0.8,random_state=0)
test_dataset = dataset.drop(train_dataset.index)
```
### Inspect the data
Have a quick look at the joint distribution of a few pairs of columns from the training set.
```
sns.pairplot(train_dataset[["MPG", "Cylinders", "Displacement", "Weight"]], diag_kind="kde")
```
Also look at the overall statistics:
```
train_stats = train_dataset.describe()
train_stats.pop("MPG")
train_stats = train_stats.transpose()
train_stats
```
### Split features from labels
Separate the target value, or "label", from the features. This label is the value that you will train the model to predict.
```
train_labels = train_dataset.pop('MPG')
test_labels = test_dataset.pop('MPG')
```
### Normalize the data
Look again at the `train_stats` block above and note how different the ranges of each feature are.
It is good practice to normalize features that use different scales and ranges. Although the model *might* converge without feature normalization, it makes training more difficult, and it makes the resulting model dependent on the choice of units used in the input.
Note: That we intentionally use the statistics from only the training set, these statistics will also be used for evaluation. This is so that the model doesn't have any information about the test set.
```
def norm(x):
return (x - train_stats['mean']) / train_stats['std']
normed_train_data = norm(train_dataset)
normed_test_data = norm(test_dataset)
```
This normalized data is what we will use to train the model.
Caution: The statistics used to normalize the inputs here are as important as the model weights.
## The model
### Build the model
Let's build our model. Here, we'll use a `Sequential` model with two densely connected hidden layers, and an output layer that returns a single, continuous value. The model building steps are wrapped in a function, `build_model`, since we'll create a second model, later on.
```
def build_model():
model = keras.Sequential([
layers.Dense(64, activation=tf.nn.relu, input_shape=[len(train_dataset.keys())]),
layers.Dense(64, activation=tf.nn.relu),
layers.Dense(1)
])
optimizer = tf.train.RMSPropOptimizer(0.001)
model.compile(loss='mse',
optimizer=optimizer,
metrics=['mae', 'mse'])
return model
model = build_model()
```
### Inspect the model
Use the `.summary` method to print a simple description of the model
```
model.summary()
```
Now try out the model. Take a batch of `10` exampes from the training data and call `model.predict` on it.
```
example_batch = normed_train_data[:10]
example_result = model.predict(example_batch)
example_result
```
It seems to be working, it produces a result of the expected shape and type.
### Train the model
The model is trained for 1000 epochs, and record the training and validation accuracy in the `history` object.
```
# Display training progress by printing a single dot for each completed epoch
class PrintDot(keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs):
if epoch % 100 == 0: print('')
print('.', end='')
EPOCHS = 1000
history = model.fit(
normed_train_data, train_labels,
epochs=EPOCHS, validation_split = 0.2, verbose=0,
callbacks=[PrintDot()])
```
Visualize the model's training progress using the stats stored in the `history` object.
```
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
hist.tail()
import matplotlib.pyplot as plt
def plot_history(history):
plt.figure()
plt.xlabel('Epoch')
plt.ylabel('Mean Abs Error [MPG]')
plt.plot(hist['epoch'], hist['mean_absolute_error'],
label='Train Error')
plt.plot(hist['epoch'], hist['val_mean_absolute_error'],
label = 'Val Error')
plt.legend()
plt.ylim([0,5])
plt.figure()
plt.xlabel('Epoch')
plt.ylabel('Mean Square Error [$MPG^2$]')
plt.plot(hist['epoch'], hist['mean_squared_error'],
label='Train Error')
plt.plot(hist['epoch'], hist['val_mean_squared_error'],
label = 'Val Error')
plt.legend()
plt.ylim([0,20])
plot_history(history)
```
This graph shows little improvement, or even degradation in the validation error after a few hundred epochs. Let's update the `model.fit` method to automatically stop training when the validation score doesn't improve. We'll use a *callback* that tests a training condition for every epoch. If a set amount of epochs elapses without showing improvement, then automatically stop the training.
You can learn more about this callback [here](https://www.tensorflow.org/versions/master/api_docs/python/tf/keras/callbacks/EarlyStopping).
```
model = build_model()
# The patience parameter is the amount of epochs to check for improvement
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=50)
history = model.fit(normed_train_data, train_labels, epochs=EPOCHS,
validation_split = 0.2, verbose=0, callbacks=[early_stop, PrintDot()])
plot_history(history)
```
The graph shows that on the validation set, the average error usually around +/- 2 MPG. Is this good? We'll leave that decision up to you.
Let's see how did the model performs on the **test** set, which we did not use when training the model:
```
loss, mae, mse = model.evaluate(normed_test_data, test_labels, verbose=0)
print("Testing set Mean Abs Error: {:5.2f} MPG".format(mae))
```
### Make predictions
Finally, predict MPG values using data in the testing set:
```
test_predictions = model.predict(normed_test_data).flatten()
plt.scatter(test_labels, test_predictions)
plt.xlabel('True Values [MPG]')
plt.ylabel('Predictions [MPG]')
plt.axis('equal')
plt.axis('square')
plt.xlim([0,plt.xlim()[1]])
plt.ylim([0,plt.ylim()[1]])
_ = plt.plot([-100, 100], [-100, 100])
error = test_predictions - test_labels
plt.hist(error, bins = 25)
plt.xlabel("Prediction Error [MPG]")
_ = plt.ylabel("Count")
```
## Conclusion
This notebook introduced a few techniques to handle a regression problem.
* Mean Squared Error (MSE) is a common loss function used for regression problems (different than classification problems).
* Similarly, evaluation metrics used for regression differ from classification. A common regression metric is Mean Absolute Error (MAE).
* When input data features have values with different ranges, each feature should be scaled independently.
* If there is not much training data, prefer a small network with few hidden layers to avoid overfitting.
* Early stopping is a useful technique to prevent overfitting.
| github_jupyter |
```
import sys
import os
import datetime
import pandas as pd
import seaborn as sns
from keras import backend as K
from PIL import Image
Image.MAX_IMAGE_PIXELS = 1000000000
from matplotlib import pyplot as plt
sys.path.insert(0, '../')
%load_ext autoreload
%autoreload 2
from src.models.params import get_params
from src.models.model_utils import evaluate_test_set, write_csv_files
from src.models.Unet import Unet
from src.visualization.make_image_files import visualize_test_data, visualize_landsat8_tile
from src.visualization.visualization_utils import get_predicted_thumbnails
from src.utils import get_model_name
%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0
```
# Define and run the training loops
```
activation_functions = ['swish', 'relu']
loss_functions = ['binary_crossentropy', 'jaccard_coef_loss']
optimizers = ['Adam', 'Nadam']
dropout_vals = [0, 0.5]
epochs = 200
num_gpus = 1
# Train the models
for activation_func in activation_functions:
for loss_function in loss_functions:
for optimizer in optimizers:
for dropout in dropout_vals:
params = get_params('U-net', 'Landsat8')
params.modelID = datetime.datetime.now().strftime("%y%m%d%H%M%S")
params.loss_func = loss_function
params.optimizer = optimizer
params.activation_func = activation_func
params.dropout = dropout
params.epochs = epochs
params.brightness_augmentation = False
params.batch_size = 12
print('###########################################')
print('# activation_func: ' + activation_func)
print('# loss_function: ' + loss_function)
print('# optimizer: ' + optimizer)
print('###########################################')
model = Unet()
model.train(num_gpus, params)
evaluate_test_set(model, num_gpus, params)
classes = [['thin', 'cloud']]
epochs = 50
num_gpus = 1
# Train the models
for cls in classes:
print('###########################################')
print('# class: ' + str(cls))
print('###########################################')
params = get_params('U-net', 'Landsat8')
params.batch_size = 12
params.modelID = datetime.datetime.now().strftime("%y%m%d%H%M%S")
params.loss_func = 'binary_crossentropy'
params.optimizer = 'Nadam'
params.activation_func = 'swish'
params.epochs = epochs
params.cls = cls
model = Unet()
model.train(num_gpus, params)
# Test different threshold values for the trained model (remember timeID is the same for all thresholds)
for threshold in thresholds:
params.threshold = threshold
avg_jaccard, product_names, product_jaccard = evaluate_test_set(model, num_gpus, params)
write_csv_files(avg_jaccard, product_jaccard, product_names, params)
```
# Investigate the trained models
```
params = get_params('U-net', 'Landsat8')
df = pd.read_csv(params.project_path + 'reports/Unet/param_optimization.csv' )
#df.sort_values('entire_testset', ascending=False).head(40)
#df.loc[df['modelID'] == 180201172308]
df.loc[df['cls'] == 'shadow']
```
# Plot predictions from the desired model
```
modelID = '180202154744'
num_gpus = 2
K.clear_session()
model = Unet()
params = get_params('U-net', 'Landsat8')
params.add_hparam('modelID', modelID)
params.activation_func = 'swish'
params.cls = ['shadow']
visualize_test_data(model, num_gpus, params)
# Overlay pictures
thresholded = True
transparency = 200
thumbnail_res = 512, 512 # Resolution to be showed
area = (1000, 1000, 7000, 7000) # Area to be cropped in (min_width, min_height, max_width, max_height)
params.threshold = 0.1
model_name = get_model_name(params)
# Plot predictions
files = sorted(os.listdir(params.project_path + 'data/output/')) # os.listdir loads in arbitrary order, hence use sorted()
files = [f for f in files if ('thresholded_Unet_Landsat8_' + modelID) in f] # Filter out one ID for each tile
for i, f in enumerate(files, start=1):
rgb, pred_unet, pred_true = get_predicted_thumbnails(f, thresholded, area, transparency, thumbnail_res, params)
# Plot
plt.figure(figsize=(35, 35))
plt.subplot(1, 3, 1)
plt.title('RGB for tile: ' + f[0:21])
plt.imshow(rgb)
plt.subplot(1, 3, 2)
plt.title('Unet for tile: ' + f[0:21])
plt.imshow(pred_unet)
plt.subplot(1, 3, 3)
plt.title('True for tile: ' + f[0:21])
plt.imshow(pred_true)
plt.show()
```
| github_jupyter |
<a id="title_ID"></a>
# JWST Pipeline Validation Notebook:
# < pipeline name >, < step name>
<span style="color:red"> **Instruments Affected**</span>: e.g., FGS, MIRI, NIRCam, NIRISS, NIRSpec
### Table of Contents
Follow this general outline. Additional sections may be added and others can be excluded, as needed. Sections in with a (\*) symbol are required.
<div style="text-align: left">
<br> [Introduction\*](#intro)
<br> [JWST CalWG Algorithm\*](#algorithm)
<br> [Defining Terms](#terms)
<br> [Test Description\*](#description)
<br> [Data Description\*](#data_descr)
<br> [Imports\*](#imports)
<br> [Loading the Data\*](#data_load)
<br> [Run the Pipeline](#pipeline)
<br> [Perform Tests or Visualization](#testing)
<br> [About This Notebook\*](#about)
<br>
</div>
<a id="intro"></a>
# Introduction
Give a short introduction explaining the purpose of this notebook and providing relevant links. Here is an example:
> This is the validation notebook for the source catalog step. This step creates a final catalog of source photometry and morphologies. Here we are testing the step for accuracy of the catalog. For more information on the pipeline step visit the links below.
> Step description: https://jwst-pipeline.readthedocs.io/en/latest/jwst/source_catalog/index.html
> Pipeline code: https://github.com/spacetelescope/jwst/tree/master/jwst/source_catalog
[Top of Page](#title_ID)
<a id="algorithm"></a>
# JWST CalWG Algorithm
Provide a short description of the implemented algorithm, and/or link to the Confluence page.
For example:
> https://outerspace.stsci.edu/display/JWSTCC/Vanilla+Point+Source+Catalog
[Top of Page](#title_ID)
<a id="terms"></a>
# Defining Terms
If necessary, provide terms or acronymns that may not be known a general audience (i.e., a new team member or an external user). For example:
> JWST: James Webb Space Telescope
> NIRSpec: Near-Infrared Spectrogragh
[Top of Page](#title_ID)
<a id="description"></a>
# Test Description
Provide a description of the test that is being performed.
For example:
>This test is performed by creating a set of simulated data with multiple point sources located at specified coordinates. The simulator puts in the expected distortion, so the initial output data comes out of the simulator in distorted coordinates. When this data is then run through calwebb_detector1, calwebb_image2 and calwebbb_image3, the combined, undistorted image should have the point sources registered at the expected locations. In flight, this test can be repeated with known stars that should be found at their expected coordinates.
[Top of Page](#title_ID)
<a id="data_descr"></a>
# Data Description
Provide a description of the test data that is being used.
For example:
>The set of data used in this particular test were created with the MIRI Data Simulator (MIRISim). The simulator created four imaging mode files, two exposures each at two different dither positions, using the specified filter.
[Top of Page](#title_ID)
<a id="tempdir"></a>
# Set up Temporary Directory
The following cell sets up a temporary directory (using python's `tempfile.TemporaryDirectory()`), and changes the script's active directory into that directory (using python's `os.chdir()`). This is so that, when the notebook is run through, it will download files to (and create output files in) the temporary directory rather than in the notebook's directory. This makes cleanup significantly easier (since all output files are deleted when the notebook is shut down), and also means that different notebooks in the same directory won't interfere with each other when run by the automated webpage generation process.
If you want the notebook to generate output in the notebook's directory, simply don't run this cell.
If you have a file (or files) that are kept in the notebook's directory, and that the notebook needs to use while running, you can copy that file into the directory (the code to do so is present below, but commented out).
[Top of Page](#title_ID)
```
#****
#
# Set this variable to False to not use the temporary directory
#
#****
use_tempdir = True
# Create a temporary directory to hold notebook output, and change the working directory to that directory.
from tempfile import TemporaryDirectory
import os
import shutil
if use_tempdir:
data_dir = TemporaryDirectory()
# If you have files that are in the notebook's directory, but that the notebook will need to use while
# running, copy them into the temporary directory here.
#
# files = ['name_of_file']
# for file_name in files:
# shutil.copy(file_name, os.path.join(data_dir.name, file_name))
# Save original directory
orig_dir = os.getcwd()
# Move to new directory
os.chdir(data_dir.name)
# For info, print out where the script is running
print("Running in {}".format(os.getcwd()))
```
## If Desired, set up CRDS to use a local cache
By default, the notebook template environment sets up its CRDS cache (the "CRDS_PATH" environment variable) in /grp/crds/cache. However, if the notebook is running on a local machine without a fast and reliable connection to central storage, it makes more sense to put the CRDS cache locally. Currently, the cell below offers several options, and will check the supplied boolean variables one at a time until one matches.
* if `use_local_crds_cache` is False, then the CRDS cache will be kept in /grp/crds/cache
* if `use_local_crds_cache` is True, the CRDS cache will be kept locally
* if `crds_cache_tempdir` is True, the CRDS cache will be kept in the temporary directory
* if `crds_cache_notebook_dir` is True, the CRDS cache will be kept in the same directory as the notebook.
* if `crds_cache_home` is True, the CRDS cache will be kept in $HOME/crds/cache
* if `crds_cache_custom_dir` is True, the CRDS cache will be kept in whatever is stored in the
`crds_cache_dir_name` variable.
If the above cell (creating a temporary directory) is not run, then setting `crds_cache_tempdir` to True will store the CRDS cache in the notebook's directory (the same as setting `crds_cache_notebook_dir` to True).
```
import os
# Choose CRDS cache location
use_local_crds_cache = False
crds_cache_tempdir = False
crds_cache_notebook_dir = False
crds_cache_home = False
crds_cache_custom_dir = False
crds_cache_dir_name = ""
if use_local_crds_cache:
if crds_cache_tempdir:
os.environ['CRDS_PATH'] = os.path.join(os.getcwd(), "crds")
elif crds_cache_notebook_dir:
try:
os.environ['CRDS_PATH'] = os.path.join(orig_dir, "crds")
except Exception as e:
os.environ['CRDS_PATH'] = os.path.join(os.getcwd(), "crds")
elif crds_cache_home:
os.environ['CRDS_PATH'] = os.path.join(os.environ['HOME'], 'crds', 'cache')
elif crds_cache_custom_dir:
os.environ['CRDS_PATH'] = crds_cache_dir_name
```
<a id="imports"></a>
# Imports
List the package imports and why they are relevant to this notebook.
* astropy.io for opening fits files
* inspect to get the docstring of our objects.
* IPython.display for printing markdown output
* jwst.datamodels for building model for JWST Pipeline
* jwst.module.PipelineStep is the pipeline step being tested
* matplotlib.pyplot.plt to generate plot
[Top of Page](#title_ID)
```
# import inspect
# from astropy.io import fits
# from IPython.display import Markdown
# from jwst.datamodels import RampModel
# from jwst.module import PipelineStep
# import matplotlib.pyplot as plt
```
<a id="data_load"></a>
# Loading the Data
### Data for internal use: Artifactory method
Artifactory should be used for data that is for internal use only.
1. Create a [Jira "Task" Issue in the JWST Simulations Jira project](https://jira.stsci.edu/issues/?jql=project%20%3D%20JWSTSIMS%20AND%20resolution%20%3D%20Unresolved%20ORDER%20BY%20priority%20DESC%2C%20updated%20DESC) requesting to have your data added to Artifactory. Assign the ticket to Misty Cracraft ([@cracraft](https://github.com/cracraft)) or Alicia Canipe ([@aliciacanipe](https://github.com/aliciacanipe)), and provide more information about the data: simulation information, data location, and pipeline step(s). Once your data has been added to Artifactory, Misty Cracraft ([@cracraft](https://github.com/cracraft)) or Alicia Canipe ([@aliciacanipe](https://github.com/aliciacanipe)) will resolve the issue and notify you that your data is ready to be used (the full path to the data will be provided by the person who notified you that your data was ingested successfully).
2. Make sure you have the proper OS environmental variable set to access STScI's instance of Artifactory. This can be done via command line or put into a setup file like a ```.bash_profile``` file.
```
export TEST_BIGDATA=https://bytesalad.stsci.edu/artifactory/
```
3. Make sure your environment has ```ci_watson``` installed.
```
pip install ci_watson
```
4. In your notebook, import the ```ci_watson``` package needed.
```python
from ci_watson.artifactory_helpers import get_bigdata
```
5. Read in each file stored in Artifactory (the full path should have been provided by the person who ingested the data).
```python
satfile = get_bigdata('jwst_validation_notebooks',
'validation_data',
'jump',
'jump_miri_test',
'miri_sat_55k.fits')
```
### Data for external use: Box method
Artifactory is only accessible to internal users on the STScI network. If you would like to contribute a test notebook that uses externally available data, this test data should be stored in a Box folder instead. The final workflow for using Box is still in discussion, but for now there is a function below that will allow you to download files from Box.
The function takes a list of tuples in the form (box_url, file_name) where box_url is the URL of a Box file to download, and file_name is the name that you want to use to refer to that file once it has been downloaded (a sample list is provided after the function definition). This is required because files downloaded from Box have their file extensions removed, and Box does not easily support meaningful file URLs or downloaded file names.
If you have set up individual Box files for download, their URL will probably be in the form `https://stsci.box.com/shared/static/URL` where `URL` is specific to each individual file. In this case, you can provide your box_url either as a full link or as just the part that comes after `/static/`, for example:
```python
file_urls = ['abcd.fits', 'efgh101.fits', 'ijk339c0fg.fits']
file_names = ['some_test_file.fits', 'some_other_test_file.fits', 'yet_another_file.fits']
box_download_list = [(url,name) for url,name in zip(file_urls,file_names)]
```
will work, but so too will
```python
main_box_url = 'https://stsci.box.com/shared/static/'
box_download_list = [('{}{}'.format(main_box_url, url),name) for url,name in zip(file_urls, file_names)]
```
If instead you have set up a shared box directory with the appropriate permissions, you will probably need to provide the full URL for each file (because the directory URL will not be in the form above), for example:
```python
from astropy.utils.data import download_file
main_box_url ="https://data.science.stsci.edu/redirect/JWST/TSO/pipeline_testing_miri_ima_tso/"
filename = 'pipetest_miri_imtso_FULL_10g10i_F770W.fits'
box_download_list = [(main_box_url+filename, filename)]
```
[Top of Page](#title_ID)
```
from astropy.utils.data import download_file
from pathlib import Path
from shutil import move
from os.path import splitext
def get_box_files(file_list):
for box_url,file_name in file_list:
if 'https' not in box_url:
box_url = 'https://stsci.box.com/shared/static/' + box_url
downloaded_file = download_file(box_url)
if Path(file_name).suffix == '':
ext = splitext(box_url)[1]
file_name += ext
move(downloaded_file, file_name)
box_download_list = [
# First item is Box URL. Second item is desired file name
# ("kzef4nvyzzpfy4x4o108x344qg5epaf0.fits", "test_for_thingy_asn.fits"),
# First item *can* be full URL path If second item doesn't have an
# extension, it will be given the
# same extension as the Box URL
# ("https://stsci.box.com/shared/static/kzef4nvyzzpfy4x4o108x344qg5epaf0.fits", "test_for_another_thingy_asn")
]
```
<a id="pipeline"></a>
# Run the Steps or Pipeline
Run the steps or the pipeline whose outputs will be validated for this test. For example:
```python
# import the pipeline you want to run (e.g., ramps-to-slopes)
from jwst.pipeline import calwebb_detector1
# initialize
m = calwebb_detector1.Detector1Pipeline()
# make changes to the parameters/reference files used
m.saturation.override_saturation = 'mysatfile.fits'
m.superbias.override_superbias = 'mysuperbias.fits'
m.refpix.odd_even_rows = False
# skip steps you don't want to run
m.group_scale.skip = True
m.ipc.skip = True
m.dark_current.skip = True
m.persistence.skip = True
# name your output file
m.output_file = 'myoutputfilename.fits'
# run the pipeline with these paramters
m.run('uncalfile.fits')
```
[Top of Page](#title_ID)
# Assertion Test Function
Using `assert()` statements to test code can be very important, but the problem with assertions is that a failed assertion will raise an exception and halt the notebook (and sometimes you want later tests to execute even if an earlier test failed, especially when the tests are independent of each other). In order to use assertions, but not halt the notebook on failure, this function wraps the assertion in a try/except block. As such, if the test fails, it will print out an error message but not stop later tests from running.
This function is designed to be used when you
* want to do an assertion test
* don't want a failed test to crash the rest of the notebook
* don't want to manually wrap the assertion in a try/except block
It's intended to be called as:
test_assertion(test_condition, success_message, failure_message)
where
* test_condition is something that evaluates to either True or False. For example, "np.max(detector_data)>0",
"np.all(test_flags)", "header['some_header_keyword'] is not 'FAILED'"
* success_message is an optional message to print out if the test succeeds. For example,
"Non-zero Data Test Passed"
* failue_message is an optional (but *strongly* recommended) message to print out if the test fails. For example,
"ERROR: Non-zero Data Test FAILED". If this is not provided, then the function will still print out a failure
message, but it probably won't be very useful.
```
def test_assertion(test_condition, success_message=None, failure_message=None):
try:
assert(test_condition)
if success_message is not None:
print(success_message)
except AssertionError as e:
if failure_message is not None:
print(failure_message)
else:
print("Assertion {} failed.".format(test_condition))
```
<a id="testing"></a>
# Perform Tests or Visualization
Perform the validation tests described previously. Generate plots, tables, diagnostics, etc.
[Top of Page](#title_ID)
<a id="about_ID"></a>
## About this Notebook
**Author:** Author Name, Job Title, Branch Name
<br>**Updated On:** MM/DD/YYYY
[Top of Page](#title_ID)
<img style="float: right;" src="./stsci_pri_combo_mark_horizonal_white_bkgd.png" alt="stsci_pri_combo_mark_horizonal_white_bkgd" width="200px"/>
| github_jupyter |
# About this kernel
+ eca_nfnet_l0
+ ArcFace
+ Mish() activation
+ Ranger (RAdam + Lookahead) optimizer
+ margin = 0.7
## Imports
```
import sys
sys.path.append('../input/shopee-competition-utils')
sys.path.insert(0,'../input/pytorch-image-models')
import numpy as np
import pandas as pd
import torch
from torch import nn
from torch.nn import Parameter
from torch.nn import functional as F
from torch.utils.data import Dataset, DataLoader
import albumentations
from albumentations.pytorch.transforms import ToTensorV2
from custom_scheduler import ShopeeScheduler
from custom_activation import replace_activations, Mish
from custom_optimizer import Ranger
from loss_module import ArcMarginProduct
import math
import cv2
import timm
import os
import random
import gc
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import GroupKFold
from sklearn.neighbors import NearestNeighbors
from tqdm.notebook import tqdm
```
## Config
```
class CFG:
DATA_DIR = '../input/shopee-product-matching/train_images'
TRAIN_CSV = '../input/shopee-product-matching/train.csv'
# data augmentation
IMG_SIZE = 512
MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]
SEED = 2021
# data split
N_SPLITS = 5
TEST_FOLD = 0
VALID_FOLD = 1
EPOCHS = 8
BATCH_SIZE = 8
NUM_WORKERS = 4
DEVICE = 'cuda:1'
CLASSES = 6609
SCALE = 30
MARGIN = 0.7
MODEL_NAME = 'eca_nfnet_l0'
MODEL_PATH = f'{MODEL_NAME}_arc_face_epoch_{EPOCHS}_bs_{BATCH_SIZE}_margin_{MARGIN}.pt'
FC_DIM = 512
SCHEDULER_PARAMS = {
"lr_start": 1e-5,
"lr_max": 1e-5 * 32,
"lr_min": 1e-6,
"lr_ramp_ep": 5,
"lr_sus_ep": 0,
"lr_decay": 0.8,
}
```
## Augmentations
```
def get_train_transforms():
return albumentations.Compose(
[
albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),
albumentations.HorizontalFlip(p=0.5),
albumentations.VerticalFlip(p=0.5),
albumentations.Rotate(limit=120, p=0.8),
albumentations.RandomBrightness(limit=(0.09, 0.6), p=0.5),
albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),
ToTensorV2(p=1.0),
]
)
def get_valid_transforms():
return albumentations.Compose(
[
albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),
albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),
ToTensorV2(p=1.0)
]
)
def get_test_transforms():
return albumentations.Compose(
[
albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),
albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),
ToTensorV2(p=1.0)
]
)
```
## Reproducibility
```
def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True # set True to be faster
seed_everything(CFG.SEED)
```
## Dataset
```
class ShopeeDataset(torch.utils.data.Dataset):
"""for training
"""
def __init__(self,df, transform = None):
self.df = df
self.root_dir = CFG.DATA_DIR
self.transform = transform
def __len__(self):
return len(self.df)
def __getitem__(self,idx):
row = self.df.iloc[idx]
img_path = os.path.join(self.root_dir,row.image)
image = cv2.imread(img_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
label = row.label_group
if self.transform:
augmented = self.transform(image=image)
image = augmented['image']
return {
'image' : image,
'label' : torch.tensor(label).long()
}
class ShopeeImageDataset(torch.utils.data.Dataset):
"""for validating and test
"""
def __init__(self,df, transform = None):
self.df = df
self.root_dir = CFG.DATA_DIR
self.transform = transform
def __len__(self):
return len(self.df)
def __getitem__(self,idx):
row = self.df.iloc[idx]
img_path = os.path.join(self.root_dir,row.image)
image = cv2.imread(img_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
label = row.label_group
if self.transform:
augmented = self.transform(image=image)
image = augmented['image']
return image,torch.tensor(1)
class ShopeeModel(nn.Module):
def __init__(
self,
n_classes = CFG.CLASSES,
model_name = CFG.MODEL_NAME,
fc_dim = CFG.FC_DIM,
margin = CFG.MARGIN,
scale = CFG.SCALE,
use_fc = True,
pretrained = True):
super(ShopeeModel,self).__init__()
print('Building Model Backbone for {} model'.format(model_name))
self.backbone = timm.create_model(model_name, pretrained=pretrained)
if 'efficientnet' in model_name:
final_in_features = self.backbone.classifier.in_features
self.backbone.classifier = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'resnet' in model_name:
final_in_features = self.backbone.fc.in_features
self.backbone.fc = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'resnext' in model_name:
final_in_features = self.backbone.fc.in_features
self.backbone.fc = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'nfnet' in model_name:
final_in_features = self.backbone.head.fc.in_features
self.backbone.head.fc = nn.Identity()
self.backbone.head.global_pool = nn.Identity()
self.pooling = nn.AdaptiveAvgPool2d(1)
self.use_fc = use_fc
if use_fc:
self.dropout = nn.Dropout(p=0.0)
self.fc = nn.Linear(final_in_features, fc_dim)
self.bn = nn.BatchNorm1d(fc_dim)
self._init_params()
final_in_features = fc_dim
self.final = ArcMarginProduct(final_in_features,
n_classes,
s=scale,
m=margin)
def _init_params(self):
nn.init.xavier_normal_(self.fc.weight)
nn.init.constant_(self.fc.bias, 0)
nn.init.constant_(self.bn.weight, 1)
nn.init.constant_(self.bn.bias, 0)
def forward(self, image, label):
feature = self.extract_feat(image)
logits = self.final(feature,label)
return logits
def extract_feat(self, x):
batch_size = x.shape[0]
x = self.backbone(x)
x = self.pooling(x).view(batch_size, -1)
if self.use_fc:
x = self.dropout(x)
x = self.fc(x)
x = self.bn(x)
return x
```
## ArcMarginProduct
```
class ArcMarginProduct(nn.Module):
r"""Implement of large margin arc distance: :
Args:
in_features: size of each input sample
out_features: size of each output sample
s: norm of input feature
m: margin
cos(theta + m)
"""
def __init__(self, in_features, out_features, s=30.0, m=0.50, easy_margin=False, ls_eps=0.0):
super(ArcMarginProduct, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.s = s
self.m = m
self.ls_eps = ls_eps # label smoothing
self.weight = Parameter(torch.FloatTensor(out_features, in_features))
nn.init.xavier_uniform_(self.weight)
self.easy_margin = easy_margin
self.cos_m = math.cos(m)
self.sin_m = math.sin(m)
self.th = math.cos(math.pi - m)
self.mm = math.sin(math.pi - m) * m
def forward(self, input, label):
# --------------------------- cos(theta) & phi(theta) ---------------------------
cosine = F.linear(F.normalize(input), F.normalize(self.weight))
sine = torch.sqrt(1.0 - torch.pow(cosine, 2))
phi = cosine * self.cos_m - sine * self.sin_m
if self.easy_margin:
phi = torch.where(cosine > 0, phi, cosine)
else:
phi = torch.where(cosine > self.th, phi, cosine - self.mm)
# --------------------------- convert label to one-hot ---------------------------
# one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda')
one_hot = torch.zeros(cosine.size(), device=CFG.DEVICE)
one_hot.scatter_(1, label.view(-1, 1).long(), 1)
if self.ls_eps > 0:
one_hot = (1 - self.ls_eps) * one_hot + self.ls_eps / self.out_features
# -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
output *= self.s
return output, nn.CrossEntropyLoss()(output,label)
```
## Engine
```
def train_fn(model, data_loader, optimizer, scheduler, i):
model.train()
fin_loss = 0.0
tk = tqdm(data_loader, desc = "Epoch" + " [TRAIN] " + str(i+1))
for t,data in enumerate(tk):
for k,v in data.items():
data[k] = v.to(CFG.DEVICE)
optimizer.zero_grad()
_, loss = model(**data)
loss.backward()
optimizer.step()
fin_loss += loss.item()
tk.set_postfix({'loss' : '%.6f' %float(fin_loss/(t+1)), 'LR' : optimizer.param_groups[0]['lr']})
scheduler.step()
return fin_loss / len(data_loader)
def eval_fn(model, data_loader, i):
model.eval()
fin_loss = 0.0
tk = tqdm(data_loader, desc = "Epoch" + " [VALID] " + str(i+1))
with torch.no_grad():
for t,data in enumerate(tk):
for k,v in data.items():
data[k] = v.to(CFG.DEVICE)
_, loss = model(**data)
fin_loss += loss.item()
tk.set_postfix({'loss' : '%.6f' %float(fin_loss/(t+1))})
return fin_loss / len(data_loader)
def read_dataset():
df = pd.read_csv(CFG.TRAIN_CSV)
df['matches'] = df.label_group.map(df.groupby('label_group').posting_id.agg('unique').to_dict())
df['matches'] = df['matches'].apply(lambda x: ' '.join(x))
gkf = GroupKFold(n_splits=CFG.N_SPLITS)
df['fold'] = -1
for i, (train_idx, valid_idx) in enumerate(gkf.split(X=df, groups=df['label_group'])):
df.loc[valid_idx, 'fold'] = i
labelencoder= LabelEncoder()
df['label_group'] = labelencoder.fit_transform(df['label_group'])
train_df = df[df['fold']!=CFG.TEST_FOLD].reset_index(drop=True)
train_df = train_df[train_df['fold']!=CFG.VALID_FOLD].reset_index(drop=True)
valid_df = df[df['fold']==CFG.VALID_FOLD].reset_index(drop=True)
test_df = df[df['fold']==CFG.TEST_FOLD].reset_index(drop=True)
train_df['label_group'] = labelencoder.fit_transform(train_df['label_group'])
return train_df, valid_df, test_df
def precision_score(y_true, y_pred):
y_true = y_true.apply(lambda x: set(x.split()))
y_pred = y_pred.apply(lambda x: set(x.split()))
intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])
len_y_pred = y_pred.apply(lambda x: len(x)).values
precision = intersection / len_y_pred
return precision
def recall_score(y_true, y_pred):
y_true = y_true.apply(lambda x: set(x.split()))
y_pred = y_pred.apply(lambda x: set(x.split()))
intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])
len_y_true = y_true.apply(lambda x: len(x)).values
recall = intersection / len_y_true
return recall
def f1_score(y_true, y_pred):
y_true = y_true.apply(lambda x: set(x.split()))
y_pred = y_pred.apply(lambda x: set(x.split()))
intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])
len_y_pred = y_pred.apply(lambda x: len(x)).values
len_y_true = y_true.apply(lambda x: len(x)).values
f1 = 2 * intersection / (len_y_pred + len_y_true)
return f1
def get_valid_embeddings(df, model):
model.eval()
image_dataset = ShopeeImageDataset(df,transform=get_valid_transforms())
image_loader = torch.utils.data.DataLoader(
image_dataset,
batch_size=CFG.BATCH_SIZE,
pin_memory=True,
num_workers = CFG.NUM_WORKERS,
drop_last=False
)
embeds = []
with torch.no_grad():
for img,label in tqdm(image_loader):
img = img.to(CFG.DEVICE)
label = label.to(CFG.DEVICE)
feat,_ = model(img,label)
image_embeddings = feat.detach().cpu().numpy()
embeds.append(image_embeddings)
del model
image_embeddings = np.concatenate(embeds)
print(f'Our image embeddings shape is {image_embeddings.shape}')
del embeds
gc.collect()
return image_embeddings
def get_valid_neighbors(df, embeddings, KNN = 50, threshold = 0.36):
model = NearestNeighbors(n_neighbors = KNN, metric = 'cosine')
model.fit(embeddings)
distances, indices = model.kneighbors(embeddings)
predictions = []
for k in range(embeddings.shape[0]):
idx = np.where(distances[k,] < threshold)[0]
ids = indices[k,idx]
posting_ids = ' '.join(df['posting_id'].iloc[ids].values)
predictions.append(posting_ids)
df['pred_matches'] = predictions
df['f1'] = f1_score(df['matches'], df['pred_matches'])
df['recall'] = recall_score(df['matches'], df['pred_matches'])
df['precision'] = precision_score(df['matches'], df['pred_matches'])
del model, distances, indices
gc.collect()
return df, predictions
```
# Training
```
def run_training():
train_df, valid_df, test_df = read_dataset()
train_dataset = ShopeeDataset(train_df, transform = get_train_transforms())
train_dataloader = torch.utils.data.DataLoader(
train_dataset,
batch_size = CFG.BATCH_SIZE,
pin_memory = True,
num_workers = CFG.NUM_WORKERS,
shuffle = True,
drop_last = True
)
print(train_df['label_group'].nunique())
model = ShopeeModel()
model = replace_activations(model, torch.nn.SiLU, Mish())
model.to(CFG.DEVICE)
optimizer = Ranger(model.parameters(), lr = CFG.SCHEDULER_PARAMS['lr_start'])
#optimizer = torch.optim.Adam(model.parameters(), lr = config.SCHEDULER_PARAMS['lr_start'])
scheduler = ShopeeScheduler(optimizer,**CFG.SCHEDULER_PARAMS)
best_valid_f1 = 0.
for i in range(CFG.EPOCHS):
avg_loss_train = train_fn(model, train_dataloader, optimizer, scheduler, i)
valid_embeddings = get_valid_embeddings(valid_df, model)
valid_df, valid_predictions = get_valid_neighbors(valid_df, valid_embeddings)
valid_f1 = valid_df.f1.mean()
valid_recall = valid_df.recall.mean()
valid_precision = valid_df.precision.mean()
print(f'Valid f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}')
if valid_f1 > best_valid_f1:
best_valid_f1 = valid_f1
print('Valid f1 score improved, model saved')
torch.save(model.state_dict(),CFG.MODEL_PATH)
run_training()
def get_test_embeddings(test_df):
model = ShopeeModel()
model.eval()
model = replace_activations(model, torch.nn.SiLU, Mish())
model.load_state_dict(torch.load(CFG.MODEL_PATH))
model = model.to(CFG.DEVICE)
image_dataset = ShopeeImageDataset(test_df,transform=get_test_transforms())
image_loader = torch.utils.data.DataLoader(
image_dataset,
batch_size=CFG.BATCH_SIZE,
pin_memory=True,
num_workers = CFG.NUM_WORKERS,
drop_last=False
)
embeds = []
with torch.no_grad():
for img,label in tqdm(image_loader):
img = img.cuda()
label = label.cuda()
feat,_ = model(img,label)
image_embeddings = feat.detach().cpu().numpy()
embeds.append(image_embeddings)
del model
image_embeddings = np.concatenate(embeds)
print(f'Our image embeddings shape is {image_embeddings.shape}')
del embeds
gc.collect()
return image_embeddings
```
## Best threshold Search
```
train_df, valid_df, test_df = read_dataset()
print("Searching best threshold...")
search_space = np.arange(10, 50, 1)
model = ShopeeModel()
model.eval()
model = replace_activations(model, torch.nn.SiLU, Mish())
model.load_state_dict(torch.load(CFG.MODEL_PATH))
model = model.to(CFG.DEVICE)
valid_embeddings = get_valid_embeddings(valid_df, model)
best_f1_valid = 0.
best_threshold = 0.
for i in search_space:
threshold = i / 100
valid_df, valid_predictions = get_valid_neighbors(valid_df, valid_embeddings, threshold=threshold)
valid_f1 = valid_df.f1.mean()
valid_recall = valid_df.recall.mean()
valid_precision = valid_df.precision.mean()
print(f"threshold = {threshold} -> f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}")
if (valid_f1 > best_f1_valid):
best_f1_valid = valid_f1
best_threshold = threshold
print("Best threshold =", best_threshold)
print("Best f1 score =", best_f1_valid)
BEST_THRESHOLD = best_threshold
print("Searching best knn...")
search_space = np.arange(10, 50, 2)
best_f1_valid = 0.
best_knn = 0
for knn in search_space:
valid_df, valid_predictions = get_valid_neighbors(valid_df, valid_embeddings, KNN=knn, threshold=BEST_THRESHOLD)
valid_f1 = valid_df.f1.mean()
valid_recall = valid_df.recall.mean()
valid_precision = valid_df.precision.mean()
print(f"knn = {knn} -> f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}")
if (valid_f1 > best_f1_valid):
best_f1_valid = valid_f1
best_knn = knn
print("Best knn =", best_knn)
print("Best f1 score =", best_f1_valid)
BEST_KNN = best_knn
test_embeddings = get_valid_embeddings(test_df,model)
test_df, test_predictions = get_valid_neighbors(test_df, test_embeddings, KNN = BEST_KNN, threshold = BEST_THRESHOLD)
test_f1 = test_df.f1.mean()
test_recall = test_df.recall.mean()
test_precision = test_df.precision.mean()
print(f'Test f1 score = {test_f1}, recall = {test_recall}, precision = {test_precision}')
```
| github_jupyter |
# Ejercicios - 16 septiembre
Curso Introducción a Python - Tecnun, Universidad de Navarra
## Creacción diccionario
1. Crear un diccionario donde las claves sean los días de la semana y los valores sean cuántos de esos dias hay en septiembre.
2. Del diccionario anterior, convertir todas las claves mayúsculas.
EXTRA: Utiliza una tupla para los días de la semana.
## Cambiar el orden de las palabras
Pide al usuario que introduzca una frase y que el algoritmo la muestre por pantalla pero con las palabras en orden inverso. Por ejemplo:
Me gusta analizar datos -> datos analizar gusta Me
## Piedra - Papel - Tijera
Crea un algoritmo que pida a dos usuarios si eligen piedra, papel o tijera y muestra por pantalla un mensaje para el ganador. En caso de empate, seguirán jugando hasta desempatar.
## Calculadora
Hacer una función para un programa al que le entregues dos números `x` y `y` un parámetro `t` tal que
- Si t = b. debe devolver $x - y$
- Si t = c, debe devolver $x + y$
- Si t = d, debe devolver $x/y$
- Si t = e, debe devolver $x^{y+1}$
EXTRA. Intenta utilizar un lista.
## Estaciones
Hacer un script para un programa al que le entregues un parámetro mes. Según el mes que introduzca el usuario, el programa debe devolver: PRIMAVERA, VERANO, OTOÑO o INVIERNO.
EXTRA. Intenta utilizar un diccionario.
## El ahorcado (EXTRA)
Crea el juego del ahorcado.
Primero se le pedirá al usuario que introduzca una palabra. Después, otro usuario irá introduciendo letras, una a una, de forma que cada vez que introduce una, la pantalla muestre signos de interrogación en las posiciones de las letras que no se han acertado todavía y las letras en las posiciones de las que se han acertado. Asímismo, se mostrarán las letras que se han empleado pero no son correctas. Sólo se permitirán 6 fallos.
En el caso de adivinar la palabra, se felicitará al usuario y, en el caso de no hacerlo, se mostrará "GAME OVER" por pantalla.
## Validación de contraseñas (EXTRA)
Crea una función que tome como argumento de entrada una propuesta de contraseña y compruebe si es segura o no. Una contraseña segura ha de cumplir las siguientes condiciones:
- Debe tener al menos 8 caracteres.
- Debe tener al menos una letra minúscula, una letra mayúscula, un número y un carácter no alfanumérico.
- No puede tener espacios en blanco.
Si la contraseña es segura, deberá mostrarse *True* por pantalla y, si no lo es, se mostrará *False*.
Puedes aprovechar para practicar las expresiones regulares.
| github_jupyter |
# Snippets
### Arrays
```
%%writefile test04.f90
program main
integer :: i, j, k, N=3
real, dimension(3,3,3) :: a
a = reshape([.50, .73, .22, .29, .65, .41, .69, .25, .76, .64, &
.60, .73, .93, .24, .63, .19, .73, .77, .93, .70, &
.29, .53, .34, .20, .91, .02, .47], &
shape(a),order=[3,2,1])
write(*,"(*(xg0.2))") (((a(k,j,:)), new_line('A'), &
j=1,N), new_line('A'), k=1,N)
write(*,"(*(g0.2x))") a
end
!gfortran test04.f90 -g -fcheck=all -fimplicit-none && ./a.out
```
### CSV
```
import numpy as np
x = np.array( [.50, .73, .22, .29, .65, .41, .69, .25, .76,
] ).reshape(3,3)
np.savetxt("data.csv", x, fmt='%8.4f', delimiter=",")
!cat data.csv
%%writefile test05.f90
program main
integer :: i, j, k, N=3
real, dimension(3,3,3) :: a
a = reshape([.50, .73, .22, .29, .65, .41, .69, .25, .76, .64, &
.60, .73, .93, .24, .63, .19, .73, .77, .93, .70, &
.29, .53, .34, .20, .91, .02, .47], &
shape(a),order=[3,2,1])
do k = 1, N
do j = 1, N
write(*,'(*(g0.2:","))') a(k,j,:)
end do
write(*,*)
end do
end
!gfortran test05.f90 -g -fcheck=all -fimplicit-none && ./a.out
import numpy as np
x=np.array([1+2j])
np.savetxt("data.csv", x, fmt='%.4f', delimiter=",")
!cat data.csv
```
### Using fortranmagic
```
%reload_ext fortranmagic
%fortran_config --defaults
%fortran_config --f90flags "-fimplicit-none"
%%fortran
subroutine main(x)
complex, intent(out) :: x
x = (16.0650005,2.26032639)
end
x = main()
print(type(x), x)
print(main.__doc__)
```
### Implicit save attribute
Source: http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html
y is initialized only once
```
%%fortran
subroutine main(x)
real, intent(out) :: x
x = test() !y is initialized only once
x = test() !y is no longer initialized
x = test() !y is no longer initialized
contains
real function test()
real :: y = 0.0 !y is initialized only once
y = y + 1
test = y
end function
end subroutine
main()
```
## 3D Array from Python to Fortran
- https://stackoverflow.com/questions/46318178/reading-arrays-from-npy-files-into-fortran-90
```
import numpy as np
A = np.random.rand(3, 3, 3)
A.T.tofile('data.bin')
np.set_printoptions(precision=2)
print(A)
%%writefile test06.f90
program main
integer :: j, k
integer, parameter :: N = 3
real(8), dimension(N, N, N) :: dat
open(0, file='data.bin', access='stream', form='unformatted')
read(0) dat
close(0)
do k = 1, N; do j = 1, N
write(*,'(*(f4.2:" "))') dat(k,j,:)
end do; write(*,*); end do
end
!gfortran test06.f90 -g -fcheck=all -fimplicit-none
!./a.out
```
| github_jupyter |
##### Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
```
#@title License header
# Copyright 2020 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.
```
# Image edge detection module
## Setup
```
#@title Imports
import os
import tempfile
from matplotlib import pyplot as plt
import numpy as np
import tensorflow as tf
from pyiree.tf import compiler as ireec
from pyiree.tf.support import tf_utils
from pyiree import rt as ireert
#@title Setup Artifacts Directory
# Used in the low-level compilation section.
ARITFACTS_DIR = os.path.join(tempfile.gettempdir(), "iree", "colab_artifacts")
os.makedirs(ARITFACTS_DIR, exist_ok=True)
#@title Define the EdgeDetectionModule
class EdgeDetectionModule(tf.Module):
@tf.function(input_signature=[tf.TensorSpec([1, 128, 128, 1], tf.float32)])
def edge_detect_sobel_operator(self, image):
# https://en.wikipedia.org/wiki/Sobel_operator
sobel_x = tf.constant([[-1.0, 0.0, 1.0],
[-2.0, 0.0, 2.0],
[-1.0, 0.0, 1.0]],
dtype=tf.float32, shape=[3, 3, 1, 1])
sobel_y = tf.constant([[ 1.0, 2.0, 1.0],
[ 0.0, 0.0, 0.0],
[-1.0, -2.0, -1.0]],
dtype=tf.float32, shape=[3, 3, 1, 1])
gx = tf.nn.conv2d(image, sobel_x, 1, "SAME")
gy = tf.nn.conv2d(image, sobel_y, 1, "SAME")
return tf.math.sqrt(gx * gx + gy * gy)
tf_module = EdgeDetectionModule()
#@title Load a test image of a [labrador](https://commons.wikimedia.org/wiki/File:YellowLabradorLooking_new.jpg) and run the module with TF
def load_image(path_to_image):
image = tf.io.read_file(path_to_image)
image = tf.image.decode_image(image, channels=1)
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.image.resize(image, (128, 128))
image = image[tf.newaxis, :]
return image
content_path = tf.keras.utils.get_file(
'YellowLabradorLooking_new.jpg',
'https://storage.googleapis.com/download.tensorflow.org/example_images/YellowLabradorLooking_new.jpg')
image = load_image(content_path).numpy()
def show_images(image, edges):
fig, axs = plt.subplots(1, 2)
axs[0].imshow(image.reshape(128, 128), cmap="gray")
axs[0].set_title("Input image")
axs[1].imshow(edges.reshape(128, 128), cmap="gray")
axs[1].set_title("Output image")
axs[0].axis("off")
axs[1].axis("off")
fig.tight_layout()
fig.show()
# Invoke the function with the image as an argument
tf_edges = tf_module.edge_detect_sobel_operator(image).numpy()
# Plot the input and output images
show_images(image, tf_edges)
```
## High Level Compilation With IREE
```
#@markdown ### Backend Configuration
backend_choice = "iree_vmla (CPU)" #@param [ "iree_vmla (CPU)", "iree_llvmjit (CPU)", "iree_vulkan (GPU/SwiftShader)" ]
backend_choice = backend_choice.split(" ")[0]
backend = tf_utils.BackendInfo(backend_choice)
#@title Compile and Run the EdgeDetectionModule with IREE.
module = backend.compile(EdgeDetectionModule)
# Compute the edges using the compiled module and display the result.
iree_edges = module.edge_detect_sobel_operator(image)
show_images(image, iree_edges)
```
## Low-Level Compilation
Overview:
1. Convert the `tf.Module` into an IREE compiler module
2. Save the MLIR assembly from the module into a file (can stop here to use it from another application)
3. Compile the `mhlo` MLIR into a VM module for IREE to execute
4. Run the VM module through IREE's runtime to test the edge detection function
```
#@title Construct a module containing the edge detection function
# Do *not* further compile to a bytecode module for a particular backend.
#
# By stopping at mhlo in text format, we can more easily take advantage of
# future compiler improvements within IREE and can use iree_bytecode_module to
# compile and bundle the module into a sample application. For a production
# application, we would probably want to freeze the version of IREE used and
# compile as completely as possible ahead of time, then use some other scheme
# to load the module into the application at runtime.
compiler_module = ireec.tf_module_to_compiler_module(EdgeDetectionModule())
print("Edge Detection MLIR:", compiler_module.to_asm())
edge_detection_mlir_path = os.path.join(ARITFACTS_DIR, "edge_detection.mlir")
with open(edge_detection_mlir_path, "wt") as output_file:
output_file.write(compiler_module.to_asm())
print(f"Wrote MLIR to path '{edge_detection_mlir_path}'")
#@markdown ### Backend Configuration
backend_choice = "iree_vmla (CPU)" #@param [ "iree_vmla (CPU)", "iree_llvmjit (CPU)", "iree_vulkan (GPU/SwiftShader)" ]
backend_choice = backend_choice.split(" ")[0]
backend = tf_utils.BackendInfo(backend_choice)
#@title Prepare to test the edge detection module
flatbuffer_blob = compiler_module.compile(
target_backends=backend.compiler_targets)
vm_module = ireert.VmModule.from_flatbuffer(flatbuffer_blob)
# Register the module with a runtime context.
config = ireert.Config(backend.driver)
ctx = ireert.SystemContext(config=config)
ctx.add_module(vm_module)
edge_detect_sobel_operator_f = ctx.modules.module["edge_detect_sobel_operator"]
low_level_iree_edges = edge_detect_sobel_operator_f(image)
show_images(image, low_level_iree_edges)
```
| github_jupyter |
```
import matplotlib.pyplot as plt
import numpy as np
def evaluate_h(w, X):
assert len(w.shape) == 1
assert len(X.shape) == 2
assert w.shape[0] == X.shape[0]
return np.sign(w @ X)
def run_perceptron(w_initial, X_training, y_training, iteration_callback=None):
w = w_initial.copy()
n = 0
while True:
y = evaluate_h(w, X_training)
if iteration_callback:
iteration_callback(n, w)
correct = y == y_training
if np.all(correct):
return w
else:
i = np.argmax(~correct) # indice of first misclassified point
w = w + y_training[i]*X_training[:, i]
n = n + 1
def plot_hypothesis(x_coordinates, w, *plot_args, **plot_kwargs):
m = -w[1]/w[2] if w[2] != 0 else 0
b = -w[0]/w[2] if w[2] != 0 else 0
y_coordinates = m*x_coordinates + b
plt.plot(x_coordinates, y_coordinates, *plot_args, **plot_kwargs)
w_actual = np.array([1, 1, 1])
w_initial = np.array([3, -50, 0])
num_dimensions = 2
num_training_samples = 5
training_data_range = 10
X_training = np.vstack([
np.ones(num_training_samples),
np.random.uniform(
-training_data_range,
training_data_range,
(num_dimensions, num_training_samples),
),
])
y_training = evaluate_h(w_actual, X_training)
x_coordinates = X_training[1, :]
y_coordinates = X_training[2, :]
colors = ['r' if y > 0 else 'b' for y in y_training]
plt.scatter(x_coordinates, y_coordinates, c=colors)
x_coordinates_hypothesis = np.array([-training_data_range, training_data_range])
# created dummy scattered plot with 5 points for verification
def plot_iteration(n, w):
if n % 5 == 0:
label = 'iteration {}'.format(n)
plot_hypothesis(x_coordinates_hypothesis, w, 'k:', label=label)
w_final = run_perceptron(w_initial, X_training, y_training, plot_iteration)
plt.legend()
plt.show()
# created dummy scattered plot with 5 points for verification
w_actual = np.array([1, 1, 1])
w_initial = np.array([3, -50, 0])
num_dimensions = 2
num_training_samples = 20
training_data_range = 10
X_training = np.vstack([
np.ones(num_training_samples),
np.random.uniform(
-training_data_range,
training_data_range,
(num_dimensions, num_training_samples),
),
])
y_training = evaluate_h(w_actual, X_training)
x_coordinates = X_training[1, :]
y_coordinates = X_training[2, :]
colors = ['r' if y > 0 else 'b' for y in y_training]
plt.scatter(x_coordinates, y_coordinates, c=colors)
x_coordinates_hypothesis = np.array([-training_data_range, training_data_range])
w_actual = np.array([1, 1, 1])
w_initial = np.array([3, -50, 0])
num_dimensions = 2
num_training_samples = 20
training_data_range = 10
X_training = np.vstack([
np.ones(num_training_samples),
np.random.uniform(
-training_data_range,
training_data_range,
(num_dimensions, num_training_samples),
),
])
y_training = evaluate_h(w_actual, X_training)
x_coordinates = X_training[1, :]
y_coordinates = X_training[2, :]
colors = ['r' if y > 0 else 'b' for y in y_training]
plt.scatter(x_coordinates, y_coordinates, c=colors)
x_coordinates_hypothesis = np.array([-training_data_range, training_data_range])
def plot_iteration(n, w):
if n % 5 == 0:
label = 'iteration {}'.format(n)
plot_hypothesis(x_coordinates_hypothesis, w, 'k:', label=label)
w_final = run_perceptron(w_initial, X_training, y_training, plot_iteration)
plot_hypothesis(x_coordinates_hypothesis, w_final, 'k', label='final')
plot_hypothesis(x_coordinates_hypothesis, w_actual, 'y', label='actual')
plt.legend()
plt.xlim(-training_data_range, training_data_range)
plt.ylim(-training_data_range, training_data_range)
plt.show()
# data size 20
w_actual = np.array([1, 1, 1])
w_initial = np.array([3, -50, 0])
num_dimensions = 2
num_training_samples = 100
training_data_range = 10
X_training = np.vstack([
np.ones(num_training_samples),
np.random.uniform(
-training_data_range,
training_data_range,
(num_dimensions, num_training_samples),
),
])
y_training = evaluate_h(w_actual, X_training)
x_coordinates = X_training[1, :]
y_coordinates = X_training[2, :]
colors = ['r' if y > 0 else 'b' for y in y_training]
plt.scatter(x_coordinates, y_coordinates, c=colors)
x_coordinates_hypothesis = np.array([-training_data_range, training_data_range])
def plot_iteration(n, w):
if n % 5 == 0:
label = 'iteration {}'.format(n)
plot_hypothesis(x_coordinates_hypothesis, w, 'k:', label=label)
w_final = run_perceptron(w_initial, X_training, y_training, plot_iteration)
plot_hypothesis(x_coordinates_hypothesis, w_final, 'k', label='final')
plot_hypothesis(x_coordinates_hypothesis, w_actual, 'y', label='actual')
plt.legend()
plt.xlim(-training_data_range, training_data_range)
plt.ylim(-training_data_range, training_data_range)
plt.show()
# generated for data set with size 100
w_actual = np.array([1, 1, 1])
w_initial = np.array([3, -50, 0])
num_dimensions = 2
num_training_samples = 1000
training_data_range = 10
X_training = np.vstack([
np.ones(num_training_samples),
np.random.uniform(
-training_data_range,
training_data_range,
(num_dimensions, num_training_samples),
),
])
y_training = evaluate_h(w_actual, X_training)
x_coordinates = X_training[1, :]
y_coordinates = X_training[2, :]
colors = ['r' if y > 0 else 'b' for y in y_training]
plt.scatter(x_coordinates, y_coordinates, c=colors)
x_coordinates_hypothesis = np.array([-training_data_range, training_data_range])
def plot_iteration(n, w):
if n % 5 == 0:
label = 'iteration {}'.format(n)
plot_hypothesis(x_coordinates_hypothesis, w, 'k:', label=label)
w_final = run_perceptron(w_initial, X_training, y_training, plot_iteration)
plot_hypothesis(x_coordinates_hypothesis, w_final, 'k', label='final')
plot_hypothesis(x_coordinates_hypothesis, w_actual, 'y', label='actual')
plt.legend()
plt.xlim(-training_data_range, training_data_range)
plt.ylim(-training_data_range, training_data_range)
plt.show()
#data set size d =1000
```
| github_jupyter |
```
%matplotlib notebook
import control as c
import ipywidgets as w
import numpy as np
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.gridspec as gridspec
display(HTML('<script> $(document).ready(function() { $("div.input").hide(); }); </script>'))
```
## Gain- and phase margin
In the following example, we will examine the definition and calculation of gain- and phase margins and their relation to the Bode stability criterion.
<br>We define the first occurrence of the phase curve passing $\pm180°$ as the phase crossover point, and the magnitude curve passing $0$ dB as the gain crossover point. The gain margin is the magnitude value at the phase crossover (pc) point with a negative sign, and the phase margin is the difference from $\pm180°$ at the gain crossover (gc). If calculated on an open-loop system, these values express the closeness of the negative feedback closed-loop system to instability.
$$\Phi_m=\angle G(j\omega_{gc})-(-180°)\qquad A_m = -|G(j\omega_{pc})|$$
Based on these values, the stability of a negative-feedback system can be determined: if the gain margin of the open-loop system is greater than $0$ dB, the system is stable (Bode stability criterion).
<br><b>Select a system type!</b>
```
# System type selector
typeSelect = w.ToggleButtons(
options=[('Second-order', 0), ('Third-order', 1), ('Fourth-order', 2)],
description='System type: ', layout=w.Layout(width='100%'))
display(typeSelect)
```
<b>Chose polynomial coefficients for the open-loop transfer function!</b>
```
def calculate_tf(b0, b1, a0, a1, a2, b2=0, b3=0, a3=0, a4=0):
W = c.tf([b3, b2, b1, b0], [a4, a3, a2, a1, a0]) # Transfer function
print('The open loop transfer function:')
print(W)
def draw_controllers(model):
global b0i, b1i, b2i, b3i, a0i, a1i, a2i, a3i, a4i
if model == 0: # 2nd order
b0i = w.FloatText(value=1.0, description='', disabled=False, step=0.1, layout=w.Layout(width='19%'))
b1i = w.FloatText(value=0.0, description='', disabled=False, step=0.1, layout=w.Layout(width='19%'))
a0i = w.FloatText(value=10.0, description='', disabled=False, step=0.1, layout=w.Layout(width='19%'))
a1i = w.FloatText(value=1.0, description='', disabled=False, step=0.1, layout=w.Layout(width='19%'))
a2i = w.BoundedFloatText(value=1.0, min=0.01, description='', disabled=False, step=0.1, layout=w.Layout(width='19%'))
input_data = w.interactive_output(calculate_tf, {'b0': b0i, 'b1': b1i,
'a0': a0i, 'a1': a1i, 'a2': a2i})
display(w.HBox([w.VBox([w.Label('$G_{ol}(s)=$')], layout=w.Layout(justify_content="center", align_items='flex-start')),
w.VBox([w.HBox([b1i, w.Label('$s+$'), b0i],
layout=w.Layout(justify_content='center')),
w.HBox([w.HTML(value='<hr style="border-top: 1px solid black">', layout=w.Layout(width='100%'))],
layout=w.Layout(justify_content='center')),
w.HBox([a2i, w.Label('$s^2+$'), a1i, w.Label('$s+$'), a0i],
layout=w.Layout(justify_content='center')) ],
layout=w.Layout(width='40%'))], layout=w.Layout(justify_content='center') ), input_data)
elif model == 1: # 3rd order
b0i = w.FloatText(value=1.0, description='', disabled=False, step=0.1, layout=w.Layout(width='15%'))
b1i = w.FloatText(value=0.0, description='', disabled=False, step=0.1, layout=w.Layout(width='15%'))
b2i = w.FloatText(value=0.0, description='', disabled=False, step=0.1, layout=w.Layout(width='15%'))
a0i = w.FloatText(value=10.0, description='', disabled=False, step=0.1, layout=w.Layout(width='15%'))
a1i = w.FloatText(value=1.0, description='', disabled=False, step=0.1, layout=w.Layout(width='15%'))
a2i = w.FloatText(value=0.0, description='', disabled=False, step=0.1, layout=w.Layout(width='15%'))
a3i = w.BoundedFloatText(value=1.0, min=0.01, description='', disabled=False, step=0.1, layout=w.Layout(width='15%'))
input_data = w.interactive_output(calculate_tf, {'b0': b0i, 'b1': b1i, 'b2': b2i,
'a0': a0i, 'a1': a1i, 'a2': a2i, 'a3': a3i})
display(w.HBox([w.VBox([w.Label('$G_{ol}(s)=$')], layout=w.Layout(justify_content="center", align_items='flex-start')),
w.VBox([w.HBox([b2i, w.Label('$s^2+$'), b1i, w.Label('$s+$'), b0i],
layout=w.Layout(justify_content='center')),
w.HBox([w.HTML(value='<hr style="border-top: 1px solid black">', layout=w.Layout(width='100%'))],
layout=w.Layout(justify_content='center')),
w.HBox([a3i, w.Label('$s^3+$'), a2i, w.Label('$s^2+$'), a1i, w.Label('$s+$'), a0i],
layout=w.Layout(justify_content='center')) ],
layout=w.Layout(width='50%'))], layout=w.Layout(justify_content='center') ), input_data)
else : # 4th order
b0i = w.FloatText(value=1.0, description='', disabled=False, step=0.1, layout=w.Layout(width='12%'))
b1i = w.FloatText(value=0.0, description='', disabled=False, step=0.1, layout=w.Layout(width='12%'))
b2i = w.FloatText(value=0.0, description='', disabled=False, step=0.1, layout=w.Layout(width='12%'))
b3i = w.FloatText(value=0.0, description='', disabled=False, step=0.1, layout=w.Layout(width='12%'))
a0i = w.FloatText(value=10.0, description='', disabled=False, step=0.1, layout=w.Layout(width='12%'))
a1i = w.FloatText(value=1.0, description='', disabled=False, step=0.1, layout=w.Layout(width='12%'))
a2i = w.FloatText(value=0.0, description='', disabled=False, step=0.1, layout=w.Layout(width='12%'))
a3i = w.FloatText(value=0.0, description='', disabled=False, step=0.1, layout=w.Layout(width='12%'))
a4i = w.BoundedFloatText(value=1, min=0.01, description='', disabled=False, step=0.1, layout=w.Layout(width='12%'))
input_data = w.interactive_output(calculate_tf, {'b0': b0i, 'b1': b1i, 'b2': b2i, 'b3': b3i,
'a0': a0i, 'a1': a1i, 'a2': a2i, 'a3': a3i, 'a4': a4i})
display(w.HBox([w.VBox([w.Label('$G_{ol}(s)=$')], layout=w.Layout(justify_content="center", align_items='flex-start')),
w.VBox([w.HBox([b3i, w.Label('$s^3+$'), b2i, w.Label('$s^2+$'), b1i, w.Label('$s+$'), b0i],
layout=w.Layout(justify_content='center')),
w.HBox([w.HTML(value='<hr style="border-top: 1px solid black">', layout=w.Layout(width='100%'))],
layout=w.Layout(justify_content='center')),
w.HBox([a4i, w.Label('$s^4+$'), a3i, w.Label('$s^3+$'), a2i, w.Label('$s^2+$'),
a1i, w.Label('$s+$'), a0i],
layout=w.Layout(justify_content='center')) ],
layout=w.Layout(width='60%'))], layout=w.Layout(justify_content='center') ), input_data)
w.interactive_output(draw_controllers, {'model': typeSelect})
```
<b>Read the gain and phase margin values from the Bode plot!</b>
```
fig1, ((f1_ax1), (f1_ax2)) = plt.subplots(2, 1)
fig1.set_size_inches((9.8, 5))
fig1.set_tight_layout(True)
f1_line1, = f1_ax1.plot([], [], lw=1, color='blue')
f1_line2, = f1_ax2.plot([], [], lw=1, color='blue')
f1_line3, = f1_ax1.plot([], [], lw=1, color='red')
f1_line4, = f1_ax1.plot([], [], lw=1, color='magenta')
f1_line5, = f1_ax2.plot([], [], lw=1, color='red')
f1_line6, = f1_ax2.plot([], [], lw=1, color='magenta')
f1_ax1.grid(which='both', axis='both', color='lightgray')
f1_ax2.grid(which='both', axis='both', color='lightgray')
f1_ax1.autoscale(enable=True, axis='x', tight=True)
f1_ax2.autoscale(enable=True, axis='x', tight=True)
f1_ax1.autoscale(enable=True, axis='y', tight=False)
f1_ax2.autoscale(enable=True, axis='y', tight=False)
f1_ax1.set_title('Bode magnitude plot', fontsize=11)
f1_ax1.set_xscale('log')
f1_ax1.set_xlabel(r'$\omega\/[\frac{rad}{s}]$', labelpad=0, fontsize=10)
f1_ax1.set_ylabel(r'$A\/$[dB]', labelpad=0, fontsize=10)
f1_ax1.tick_params(axis='both', which='both', pad=0, labelsize=8)
f1_ax2.set_title('Bode phase plot', fontsize=11)
f1_ax2.set_xscale('log')
f1_ax2.set_xlabel(r'$\omega\/[\frac{rad}{s}]$', labelpad=0, fontsize=10)
f1_ax2.set_ylabel(r'$\phi\/$[°]', labelpad=0, fontsize=10)
f1_ax2.tick_params(axis='both', which='both', pad=0, labelsize=8)
f1_ax1.axhline(0, color='limegreen', ls='--')
f1_ax2.axhline(-180, color='limegreen', ls='--')
f1_ax2.axhline(180, color='limegreen', ls='--')
f1_ax1.legend([f1_line3, f1_line4], ['Gain Margin', 'Phase Margin'], loc='upper right')
f1_ax2.legend([f1_line5, f1_line6], ['Gain Margin', 'Phase Margin'], loc='upper right')
def calculate_margin(b0, b1, a0, a1, a2, b2=0, b3=0, a3=0, a4=0):
W = c.tf([b3, b2, b1, b0], [a4, a3, a2, a1, a0]) # Transfer function
_, _, ob = c.bode_plot(W, Plot=False) # Small resolution plot to determine bounds
mag, phase, omega = c.bode_plot(W, omega=np.logspace(np.log10(ob[0]), np.log10(ob[-1]), 100), Plot=False) # Bode-plot
gm, pm, wg, wp = c.margin(W) # Gain and phase margin
global f1_line1, f1_line2, f1_line3, f1_line4, f1_line5, f1_line6
f1_ax1.lines.remove(f1_line1)
f1_ax2.lines.remove(f1_line2)
try:
f1_ax1.lines.remove(f1_line3)
f1_ax1.lines.remove(f1_line4)
f1_ax2.lines.remove(f1_line5)
f1_ax2.lines.remove(f1_line6)
except:
pass
f1_line1, = f1_ax1.plot(omega, 20*np.log10(mag), lw=1, color='blue')
f1_line2, = f1_ax2.plot(omega, phase*180/np.pi, lw=1, color='blue')
if wg > 0:
f1_line3 = f1_ax1.axvline(wg, lw=1, color='red')
f1_line5 = f1_ax2.axvline(wg, lw=1, color='red')
else:
f1_line3, = f1_ax1.plot([], [], lw=1, color='red')
f1_line5, = f1_ax2.plot([], [], lw=1, color='red')
if wp > 0:
f1_line4 = f1_ax1.axvline(wp, lw=1, color='magenta')
f1_line6 = f1_ax2.axvline(wp, lw=1, color='magenta')
else:
f1_line4, = f1_ax1.plot([], [], lw=1, color='magenta')
f1_line6, = f1_ax2.plot([], [], lw=1, color='magenta')
f1_ax1.relim()
f1_ax2.relim()
f1_ax1.autoscale_view()
f1_ax2.autoscale_view()
def link_controllers(model):
global b0i, b1i, b2i, b3i, a0i, a1i, a2i, a3i, a4i
if model == 0: # 2nd order
w.interactive_output(calculate_margin, {'b0': b0i, 'b1': b1i,
'a0': a0i, 'a1': a1i, 'a2': a2i})
elif model == 1: # 3rd order
w.interactive_output(calculate_margin, {'b0': b0i, 'b1': b1i, 'b2': b2i,
'a0': a0i, 'a1': a1i, 'a2': a2i, 'a3': a3i})
else : # 4th order
w.interactive_output(calculate_margin, {'b0': b0i, 'b1': b1i, 'b2': b2i, 'b3': b3i,
'a0': a0i, 'a1': a1i, 'a2': a2i, 'a3': a3i, 'a4': a4i})
w.interactive_output(link_controllers, {'model': typeSelect})
```
<b>Is the closed-loop stable or unstable?</b>
```
out = w.Output()
def print_margin(b0, b1, a0, a1, a2, b2=0, b3=0, a3=0, a4=0):
global out
W = c.tf([b3, b2, b1, b0], [a4, a3, a2, a1, a0]) # Transfer function
gm, pm, wg, wp = c.margin(W) # Gain and phase margin
out.clear_output()
with out:
print('Gain margin: {:.2f} dB'.format(20*np.log10(gm)))
print('Phase margin: {:.2f}°'.format(pm))
if (20*np.log10(gm) > 0):
print('\n(stable)')
else:
print('\n(unstable)')
def link_controllers2(model):
global b0i, b1i, b2i, b3i, a0i, a1i, a2i, a3i, a4i
if model == 0: # 2nd order
w.interactive_output(print_margin, {'b0': b0i, 'b1': b1i,
'a0': a0i, 'a1': a1i, 'a2': a2i})
elif model == 1: # 3rd order
w.interactive_output(print_margin, {'b0': b0i, 'b1': b1i, 'b2': b2i,
'a0': a0i, 'a1': a1i, 'a2': a2i, 'a3': a3i})
else : # 4th order
w.interactive_output(print_margin, {'b0': b0i, 'b1': b1i, 'b2': b2i, 'b3': b3i,
'a0': a0i, 'a1': a1i, 'a2': a2i, 'a3': a3i, 'a4': a4i})
w.interactive_output(link_controllers2, {'model': typeSelect})
display(out)
```
| github_jupyter |
```
import numpy
from numpy import arange
from matplotlib import pyplot
import pandas as pd
from pandas import set_option
from pandas.plotting import scatter_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import Lasso
from sklearn.linear_model import ElasticNet
from sklearn.tree import DecisionTreeRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import LabelEncoder
#Load Dataset
names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']
dataset = pd.read_csv('datasets/housing.csv', delim_whitespace=True, names = names)
#Descriptive Statistics
dataset.shape
dataset.dtypes
dataset.head(20)
set_option('precision', 1)
print(dataset.describe())
set_option('precision', 2)
print(dataset.corr(method='pearson'))
#Unimodel Data Visualizations
dataset.hist(sharex = False, sharey=False, xlabelsize=1, ylabelsize=1)
pyplot.show()
prices = dataset['MEDV']
dataset = dataset.drop(['CRIM','ZN','INDUS','NOX','AGE','DIS','RAD'], axis = 1)
features = dataset.drop('MEDV', axis = 1)
dataset.head()
#density
dataset.plot(kind='density', subplots=True, layout=(4,4), sharex=False, legend=False, fontsize=1)
pyplot.show()
#boxplot
dataset.plot(kind='box', subplots=True, layout=(4,4), sharex=False, legend=False, fontsize=8)
pyplot.show()
#Multimodel Data Visualizations
#Scatter Plot
scatter_matrix(dataset)
pyplot.show()
#correlation matrix
fig = pyplot.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(dataset.corr(), vmin = -1, vmax = 1, interpolation='none')
fig.colorbar(cax)
ticks = numpy.arange(0,14,1)
ax.set_xticks(ticks)
ax.set_xticks(ticks)
ax.set_yticklabels(names)
ax.set_yticklabels(names)
pyplot.show()
# Split-out validation dataset
array = dataset.values
X = array[:,0:12]
Y = array[:,12]
validation_size = 0.20
seed = 7
lab_enc = LabelEncoder()
Y = lab_enc.fit_transform(Y)
X_train, X_validation, Y_train, Y_validation = train_test_split(X, Y, test_size=validation_size, random_state=seed)
# Split-out validation dataset
array = dataset.values
X = array[:,0:6]
Y = array[:,6]
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation = train_test_split(X, Y, test_size=validation_size, random_state=seed)
num_folds = 10
seed = 7
scoring = 'neg_mean_squared_error'
#Spot Check
models = []
models.append(('LR', LogisticRegression()))
models.append(('LASSO', Lasso()))
models.append(('EN', ElasticNet()))
models.append(('KNN', KNeighborsRegressor()))
models.append(('CART', DecisionTreeRegressor()))
models.append(('SVR', SVR()))
# evaluate each model in turn
results = []
names = []
for name, model in models:
kfold = KFold(n_splits=num_folds, random_state=seed)
cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
print(msg)
#Compare Algorithms
fig = pyplot.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
pyplot.boxplot(results)
ax.set_xticklabels(names)
pyplot.show()
#Standardization
pipeline = []
pipeline.append(('ScaledLR', Pipeline([('Scaler', StandardScaler()), ('LR', LinearRegression())])))
pipeline.append(('ScaledLasso', Pipeline([('Scaler', StandardScaler()), ('LASSO', Lasso())])))
pipeline.append(('ScaledEN', Pipeline([('Scaler', StandardScaler()), ('EN', ElasticNet())])))
pipeline.append(('ScaledKNN', Pipeline([('Scaler', StandardScaler()), ('KNN', KNeighborsRegressor())])))
pipeline.append(('ScaledCART', Pipeline([('Scaler', StandardScaler()), ('CART', DecisionTreeRegressor())])))
pipeline.append(('ScaledSVR', Pipeline([('Scaler', StandardScaler()), ('SVR', SVR())])))
results = []
names = []
for name, model in models:
kfold = KFold(n_splits=num_folds, random_state=seed)
cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
print(msg)
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
import syft as sy
import numpy as np
import torch as th
from syft import VirtualMachine
from pathlib import Path
from torchvision import datasets, transforms
from syft.core.plan.plan_builder import PLAN_BUILDER_VM, make_plan, build_plan_inputs, ROOT_CLIENT
from syft.lib.python.collections.ordered_dict import OrderedDict
from syft.lib.python.list import List
from matplotlib import pyplot as plt
from syft import logger
from syft import SyModule, SySequential
logger.remove()
```
# Dataset
```
from syft.util import get_root_data_path
cifar10_path = get_root_data_path()
cifar10_path.mkdir(exist_ok=True, parents=True)
norm = (0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261)
cifar_train = datasets.CIFAR10(cifar10_path, train=True, download=True,
transform=transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(*norm)
]))
cifar_test = datasets.CIFAR10((cifar10_path), train=False,
transform=transforms.Compose([transforms.ToTensor(),
transforms.Normalize(*norm)]))
train_loader = th.utils.data.DataLoader(cifar_train, batch_size=64, shuffle=True, pin_memory=True)
test_loader = th.utils.data.DataLoader(cifar_test, batch_size=1024, shuffle=True, pin_memory=True)
```
# Define Plan
```
# !pip install timm
import timm
pretrained_model = timm.create_model('resnet18', pretrained=True)
# model = timm.create_model('resnet18d', pretrained=True)
class BasicBlock(SyModule):
def __init__(self, f_in, f_out, stride1=1, downsample=False, **kwargs):
super().__init__(**kwargs)
self.conv1 = th.nn.Conv2d(f_in, f_out, kernel_size=(3, 3), stride=stride1, padding=(1, 1), bias=False)
self.bn1 = th.nn.BatchNorm2d(f_out)
self.act1 = th.nn.ReLU()
self.conv2 = th.nn.Conv2d(f_out, f_out, kernel_size=(3, 3), padding=(1, 1), bias=False)
self.bn2 = th.nn.BatchNorm2d(f_out)
self.act2 = th.nn.ReLU()
if downsample ==False:
self.downsample = None
else:
self.downsample = SySequential(
th.nn.Conv2d(f_in, f_out, kernel_size=(1, 1), stride=2, bias=False),
th.nn.BatchNorm2d(f_out),
input_size=self.input_size
)
def forward(self, x):
residual = x
x = self.conv1(x)
x = self.bn1(x)
x = self.act1(x)
x = self.conv2(x)
x = self.bn2(x)
if self.downsample is not None:
residual = self.downsample(x=residual)[0]
x += residual
x = self.act2(x)
return x
class ResNet18(SyModule):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# stem
self.conv1 = th.nn.Conv2d(3, 64, kernel_size=(7,7), stride=(2,2), padding=(3,3), bias=False)
self.bn1 = th.nn.BatchNorm2d(64)
self.act1 = th.nn.ReLU()
self.maxpool = th.nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# blocks
filters = [(64, 64), (64, 128), (128, 256), (256, 512)]
input1_sizes = [(2, 64, 7, 7), (2, 64, 7, 7), (2, 128, 4, 4), (2, 256, 2, 2)]
input2_sizes = [(2, 64, 7, 7), (2, 128, 7, 7), (2, 256, 4, 4), (2, 512, 2, 2)]
for i in range(1,5):
downsample_first = i != 1
f_in, f_out = filters[i-1]
f_in2 = f_out
stride1 = 1 if i == 1 else 2
input1_size = input1_sizes[i-1]
input2_size = input2_sizes[i-1]
layer = SySequential(
BasicBlock(f_in=f_in, f_out=f_out, downsample=downsample_first, stride1=stride1,
input_size=input1_size),
BasicBlock(f_in=f_in2, f_out=f_out,
input_size=input2_size)
)
setattr(self, f"layer{i}", layer)
# head
self.global_pool = th.nn.AdaptiveAvgPool2d(1)
self.fc = th.nn.Linear(in_features=512, out_features=10, bias=True)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.act1(x)
x = self.maxpool(x)
# self.layern are user defined layers and therefore need the self.layern(x=x)[0] stuff
x = self.layer1(x=x)[0]
x = self.layer2(x=x)[0]
x = self.layer3(x=x)[0]
x = self.layer4(x=x)[0]
x = self.global_pool(x).flatten(1)
x = self.fc(x)
return x
model = ResNet18(input_size=(2,3,32,32))
state_dict = dict(filter(lambda x: "fc." not in x[0], pretrained_model.state_dict().items()))
model.load_state_dict(state_dict, strict=False)
```
## Plan
```
remote_torch = ROOT_CLIENT.torch
dummy_dl = sy.lib.python.List([next(iter(train_loader))])
@make_plan
def train(dl = dummy_dl, model=model):
optimizer = remote_torch.optim.AdamW(model.parameters())
for xy in dl:
optimizer.zero_grad()
x, y = xy[0], xy[1]
out = model(x=x)[0]
loss = remote_torch.nn.functional.cross_entropy(out, y)
loss.backward()
optimizer.step()
return [model]
def test(test_loader, model):
correct = []
model.eval()
for data, target in test_loader:
output = model(x=data)[0]
_, pred = th.max(output, 1)
correct.append(th.sum(np.squeeze(pred.eq(target.data))))
acc = sum(correct) / len(test_loader.dataset)
return acc
alice_client = VirtualMachine(name="alice").get_client()
train_ptr = train.send(alice_client)
```
The expected accuracy for this pretrained model:
| iter | Test acc |
|---------------|----------|
| 10 | 10% |
| 100 | 25% |
| 200 | 43% |
| 300 | 54% |
| 782 (1 epoch) | 70% |
Currently, this is very slow because the model needs to be serialized & deserialized every time we run it.
```
for i, (x, y) in enumerate(train_loader):
print(f"iter {i}")
dl = [[x,y]]
res_ptr = train_ptr(dl=dl, model=model)
model, = res_ptr.get()
if i%10 == 0 and i!=0:
print(f"Iter: {i} Test accuracy: {test(test_loader, model):.2F}", flush=True)
if i>50:
break
```
# Appendix
```
# layer1 = SySequential(
# BasicBlock(f_in=64, f_out=64, stride1=1, input_size=(2, 64, 7, 7)),
# BasicBlock(f_in=64, f_out=64, input_size=(2, 64, 7, 7))
# )
# layer2 = SySequential(
# BasicBlock(f_in=64, f_out=128, stride1=2, downsample=True, input_size=(1, 64, 7, 7)),
# BasicBlock(f_in=128, f_out=128, input_size=(1, 128, 7, 7))
# )
# layer3 = SySequential(
# BasicBlock(f_in=128, f_out=256, stride1=2, downsample=True, input_size=(1, 128, 4, 4)),
# BasicBlock(f_in=256, f_out=256, input_size=(1, 256, 4, 4))
# )
# layer4 = SySequential(
# BasicBlock(f_in=256, f_out=512, stride1=2, downsample=True, input_size=(2, 256, 2, 2)),
# BasicBlock(f_in=512, f_out=512, input_size=(2, 512, 2, 2))
# )
```
| github_jupyter |
# Pawnee Fire analysis
The Pawnee Fire was a large wildfire that burned in Lake County, California. The fire started on June 23, 2018 and burned a total of 15,185 acres (61 km2) before it was fully contained on July 8, 2018.

## Remote Sensing using Sentinel-2 layer
```
from arcgis import GIS
gis = GIS(profile='plenary_deldev_profile')
```
For this analysis, we will be using Sentinel-2 imagery from the Living Atlas.
Sentinel-2 is an Earth observation mission developed by ESA as part of the Copernicus Programme to perform terrestrial observations in support of services such as forest monitoring, land cover changes detection, and natural disaster management.
```
sentinel_item = gis.content.search('Sentinel-2 Views', outside_org=True)[0]
sentinel_item
```
### Select before and after rasters
```
import arcgis
sentinel = sentinel_item.layers[0]
aoi = {'spatialReference': {'latestWkid': 3857, 'wkid': 102100},
'xmax': -13643017.100720055,
'xmin': -13652113.10708598,
'ymax': 4739654.477447927,
'ymin': 4731284.622850712}
arcgis.env.analysis_extent = aoi
sentinel.extent = aoi
import pandas as pd
from datetime import datetime
selected = sentinel.filter_by(where="acquisitiondate BETWEEN timestamp '2018-06-15 00:00:00' AND timestamp '2018-06-24 19:59:59'",
geometry=arcgis.geometry.filters.intersects(aoi))
df = selected.query(out_fields="AcquisitionDate, Tile_ID, CloudCover", order_by_fields="AcquisitionDate").df
df['acquisitiondate'] = pd.to_datetime(df['acquisitiondate'], unit='ms')
df.tail(40)
prefire = sentinel.filter_by('OBJECTID=2750251') # 2017-07-01
midfire = sentinel.filter_by('OBJECTID=2800097') # 2017-07-24
```
## Visual Assessment
```
from arcgis.raster.functions import *
truecolor = apply(midfire, 'Natural Color with DRA')
truecolor
```
### Visualize Burn Scars
Extract the [12, 11, 4] bands to improve visibility of fire and burn scars. This band combination pushes further into the SWIR range of the electromagnetic spectrum, where there is less susceptibility to smoke and haze generated by a burning fire.
```
extract_band(midfire, [12,11,4])
```
For comparison, the same area before the fire started shows no burn scar.
```
extract_band(prefire, [12,11,4])
```
## Quantitative Assessment
The **Normalized Burn Ratio (NBR)** can be used to delineate the burnt areas and identify the severity of the fire.
The formula for the NBR is very similar to that of NDVI except that it uses near-infrared band 9 and the short-wave infrared band 13:
\begin{align}
{\mathbf{NBR}} = \frac{\mathbf{B9} - \mathbf{B13}}{\mathbf{B9} + \mathbf{B13} + \mathbf{WS}} \\
\end{align}
The NBR equation was designed to be calcualted from reflectance, but it can be calculated from radiance and digital_number_(dn) with changes to the burn severity table below. The WS parameter is used for water suppression, and is typically 2000.
For a given area, NBR is calculated from an image just prior to the burn and a second NBR is calculated for an image immediately following the burn. Burn extent and severity is judged by taking the difference between these two index layers:
\begin{align}
{\Delta \mathbf{NBR}} = \mathbf{NBR_{prefire}} - \mathbf{NBR_{postfire}} \\
\end{align}
The meaning of the ∆NBR values can vary by scene, and interpretation in specific instances should always be based on some field assessment. However, the following table from the USGS FireMon program can be useful as a first approximation for interpreting the NBR difference:
| \begin{align}{\Delta \mathbf{NBR}} \end{align} | Burn Severity |
| ------------- |:-------------:|
| 0.1 to 0.27 | Low severity burn |
| 0.27 to 0.44 | Medium severity burn |
| 0.44 to 0.66 | Moderate severity burn |
| > 0.66 | High severity burn |
[Source: http://wiki.landscapetoolbox.org/doku.php/remote_sensing_methods:normalized_burn_ratio]
### Use Band Arithmetic and Map Algebra
```
nbr_prefire = band_arithmetic(prefire, "(b9 - b13) / (b9 + b13 + 2000)")
nbr_postfire = band_arithmetic(midfire, "(b9 - b13) / (b9 + b13 + 2000)")
nbr_diff = nbr_prefire - nbr_postfire
burnt_areas = colormap(remap(nbr_diff,
input_ranges=[0.1, 0.27, # low severity
0.27, 0.44, # medium severity
0.44, 0.66, # moderate severity
0.66, 1.00], # high severity burn
output_values=[1, 2, 3, 4],
no_data_ranges=[-1, 0.1], astype='u8'),
colormap=[[4, 0xFF, 0xC3, 0], [3, 0xFA, 0x8E, 0], [2, 0xF2, 0x55, 0],
[1, 0xE6, 0, 0]])
burnt_areas.draw_graph()
```
<img src="./img/pawnee-fire-graph.jpg" />
### Area calculation
```
pixx = (aoi['xmax'] - aoi['xmin']) / 1200.0
pixy = (aoi['ymax'] - aoi['ymin']) / 450.0
res = burnt_areas.compute_histograms(aoi, pixel_size={'x':pixx, 'y':pixy})
numpix = 0
histogram = res['histograms'][0]['counts'][1:]
for i in histogram:
numpix += i
```
### Report burnt area
```
from IPython.display import HTML
sqmarea = numpix * pixx * pixy # in sq. m
acres = 0.00024711 * sqmarea # in acres
HTML('<h3>Fire has consumed <font color="red">{:,} acres</font> till {}</h3>.' \
.format(int(acres), df.iloc[-1]['acquisitiondate'].date()))
import matplotlib.pyplot as plt
%matplotlib inline
plt.title('Distribution by severity', y=-0.1)
plt.pie(histogram, labels=['Low Severity', 'Medium Severity',
'Moderate Severity', 'High Severity'])
plt.axis('equal')
```
### Visualize burnt areas
```
firemap = gis.map()
firemap.extent = aoi
firemap
```
<img src="./img/pawnee-fire-inmem-raster.jpg" width=100% />
```
firemap.add_layer([truecolor, burnt_areas])
```
## Raster to Feature layer conversion
Use Raster Analytics and Geoanalytics to convert the burnt area raster to a feature layer. The `to_features()` method converts the raster to a feature layer and `create_buffers()` fills holes in the features and dissolves them to output one feature that covers the extent of the Thomas Fire.
#### Access Portal
```
#gis = GIS("https://datasciencedev.esri.com/portal", "rjackson", "admin123", verify_cert=False)
portal = GIS("https://python.playground.esri.com/portal", "arcgis_python", "amazing_arcgis_123")
fire = portal.content.search('PawneeFireArea', 'Feature Layer')[0]
fire
```
### Convert and Buffer Data
```
from arcgis.geoanalytics.use_proximity import create_buffers
fire_item = burnt_areas.to_features(output_name='Pawnee_Fire_boundary_output_tst')
fire_layer = fire_item.layers[0]
fire = create_buffers(fire_layer, 100, 'Meters', dissolve_option='All',
multipart=True, output_name='PawneeFireAreaTst')
```
## Visualize feature layer
```
vectormap = gis.map()
vectormap.basemap = 'dark-gray'
vectormap.extent = aoi
vectormap.add_layer(fire)
vectormap
```
<img src="./img/pawnee-fire-vectormap.jpg"/>
## Impact Assessment
### Assess human impact
```
from arcgis.geoenrichment import enrich
from arcgis.geometry import filters
from arcgis.features import GeoAccessor, GeoSeriesAccessor
import pandas as pd
sdf = pd.DataFrame.spatial.from_layer(fire.layers[0])
gis = GIS(profile='deldev')
fire_geometry = sdf.iloc[0].SHAPE
sa_filter = filters.intersects(geometry=fire_geometry,
sr=fire_geometry['spatialReference'])
def age_pyramid(df):
import warnings
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
warnings.simplefilter(action='ignore', category=FutureWarning)
pd.options.mode.chained_assignment = None
plt.style.use('ggplot')
df = df[[x for x in impacted_people.columns if 'MALE' in x or 'FEM' in x]]
sf = pd.DataFrame(df.sum())
age = sf.index.str.extract('(\d+)').astype('int64')
f = sf[sf.index.str.startswith('FEM')]
m = sf[sf.index.str.startswith('MALE')]
sf = sf.reset_index(drop = True)
f = f.reset_index(drop = True)
m = m.reset_index(drop = True)
sf['age'] = age
f["age"] = age
m["age"] = age
f = f.sort_values(by='age', ascending=False).set_index('age')
m = m.sort_values(by='age', ascending=False).set_index('age')
popdf = pd.concat([f, m], axis=1)
popdf.columns = ['F', 'M']
popdf['agelabel'] = popdf.index.map(str) + ' - ' + (popdf.index+4).map(str)
popdf.M = -popdf.M
sns.barplot(x="F", y="agelabel", color="#CC6699", label="Female", data=popdf, edgecolor='none')
sns.barplot(x="M", y="agelabel", color="#008AB8", label="Male", data=popdf, edgecolor='none')
plt.ylabel('Age group')
plt.xlabel('Number of people');
return plt;
```
### Age Pyramid of affected population
```
from arcgis.geoenrichment import enrich
impacted_people = enrich(sdf, 'Age')
age_pyramid(impacted_people)
```

| github_jupyter |
<a href="https://githubtocolab.com/giswqs/geemap/blob/master/examples/notebooks/50_cartoee_projections.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a>
Uncomment the following line to install [geemap](https://geemap.org) and [cartopy](https://scitools.org.uk/cartopy/docs/latest/installing.html#installing) if needed. Keep in mind that cartopy can be challenging to install. If you are unable to install cartopy on your computer, you can try Google Colab with this the [notebook example](https://colab.research.google.com/github/giswqs/geemap/blob/master/examples/notebooks/cartoee_colab.ipynb).
See below the commands to install cartopy and geemap using conda/mamba:
```
conda create -n carto python=3.8
conda activate carto
conda install mamba -c conda-forge
mamba install cartopy scipy -c conda-forge
mamba install geemap -c conda-forge
jupyter notebook
```
```
# !pip install cartopy scipy
# !pip install geemap
```
# Working with projections in cartoee
`cartoee` is a lightweight module to aid in creatig publication quality maps from Earth Engine processing results without having to download data. The `cartoee` package does this by requesting png images from EE results (which are usually good enough for visualization) and `cartopy` is used to create the plots. Utility functions are available to create plot aethetics such as gridlines or color bars. **The notebook and the geemap cartoee module ([cartoee.py](https://geemap.org/cartoee)) were contributed by [Kel Markert](https://github.com/KMarkert). A huge thank you to him.**
```
import ee
import geemap
from geemap import cartoee
import cartopy.crs as ccrs
%pylab inline
geemap.ee_initialize()
```
## Plotting an image on a map
Here we are going to show another example of creating a map with EE results. We will use global sea surface temperature data for Jan-Mar 2018.
```
# get an earth engine image of ocean data for Jan-Mar 2018
ocean = (
ee.ImageCollection('NASA/OCEANDATA/MODIS-Terra/L3SMI')
.filter(ee.Filter.date('2018-01-01', '2018-03-01'))
.median()
.select(["sst"], ["SST"])
)
# set parameters for plotting
# will plot the Sea Surface Temp with specific range and colormap
visualization = {'bands':"SST", 'min':-2, 'max':30}
# specify region to focus on
bbox = [-180, -88, 180, 88]
fig = plt.figure(figsize=(15,10))
# plot the result with cartoee using a PlateCarre projection (default)
ax = cartoee.get_map(ocean, cmap='plasma', vis_params=visualization, region=bbox)
cb = cartoee.add_colorbar(ax, vis_params=visualization, loc='right', cmap='plasma')
ax.set_title(label = 'Sea Surface Temperature', fontsize = 15)
ax.coastlines()
plt.show()
```
### Mapping with different projections
You can specify what ever projection is available within `cartopy` to display the results from Earth Engine. Here are a couple examples of global and regions maps using the sea surface temperature example. Please refer to the [`cartopy` projection documentation](https://scitools.org.uk/cartopy/docs/latest/crs/projections.html) for more examples with different projections.
```
fig = plt.figure(figsize=(15,10))
# create a new Mollweide projection centered on the Pacific
projection = ccrs.Mollweide(central_longitude=-180)
# plot the result with cartoee using the Mollweide projection
ax = cartoee.get_map(ocean, vis_params=visualization, region=bbox,
cmap='plasma', proj=projection)
cb = cartoee.add_colorbar(ax,vis_params=visualization, loc='bottom', cmap='plasma',
orientation='horizontal')
ax.set_title("Mollweide projection")
ax.coastlines()
plt.show()
fig = plt.figure(figsize=(15,10))
# create a new Goode homolosine projection centered on the Pacific
projection = ccrs.Robinson(central_longitude=-180)
# plot the result with cartoee using the Goode homolosine projection
ax = cartoee.get_map(ocean, vis_params=visualization, region=bbox,
cmap='plasma', proj=projection)
cb = cartoee.add_colorbar(ax, vis_params=visualization, loc='bottom', cmap='plasma',
orientation='horizontal')
ax.set_title("Robinson projection")
ax.coastlines()
plt.show()
fig = plt.figure(figsize=(15,10))
# create a new Goode homolosine projection centered on the Pacific
projection = ccrs.InterruptedGoodeHomolosine(central_longitude=-180)
# plot the result with cartoee using the Goode homolosine projection
ax = cartoee.get_map(ocean, vis_params=visualization, region=bbox,
cmap='plasma', proj=projection)
cb = cartoee.add_colorbar(ax, vis_params=visualization, loc='bottom', cmap='plasma',
orientation='horizontal')
ax.set_title("Goode homolosine projection")
ax.coastlines()
plt.show()
fig = plt.figure(figsize=(15,10))
# create a new orographic projection focused on the Pacific
projection = ccrs.EqualEarth(central_longitude=-180)
# plot the result with cartoee using the orographic projection
ax = cartoee.get_map(ocean, vis_params=visualization, region=bbox,
cmap='plasma', proj=projection)
cb = cartoee.add_colorbar(ax, vis_params=visualization, loc='right', cmap='plasma',
orientation='vertical')
ax.set_title("Equal Earth projection")
ax.coastlines()
plt.show()
fig = plt.figure(figsize=(15,10))
# create a new orographic projection focused on the Pacific
projection = ccrs.Orthographic(-130,-10)
# plot the result with cartoee using the orographic projection
ax = cartoee.get_map(ocean, vis_params=visualization, region=bbox,
cmap='plasma', proj=projection)
cb = cartoee.add_colorbar(ax, vis_params=visualization, loc='right', cmap='plasma',
orientation='vertical')
ax.set_title("Orographic projection")
ax.coastlines()
plt.show()
```
### Warping artifacts
Often times global projections are not needed so we use specific projection for the map that provides the best view for the geographic region of interest. When we use these, sometimes image warping effects occur. This is because `cartoee` only requests data for region of interest and when mapping with `cartopy` the pixels get warped to fit the view extent as best as possible. Consider the following example where we want to map SST over the south pole:
```
fig = plt.figure(figsize=(15, 10))
# Create a new region to focus on
spole = [-180, -88, 180,0]
projection = ccrs.SouthPolarStereo()
# plot the result with cartoee focusing on the south pole
ax = cartoee.get_map(ocean, cmap='plasma', vis_params=visualization, region=spole, proj=projection)
cb = cartoee.add_colorbar(ax, vis_params=visualization, loc='right', cmap='plasma')
ax.coastlines()
ax.set_title('The South Pole')
plt.show()
```
As you can see from the result there are warping effects on the plotted image. There is really no way of getting aound this (other than requesting a larger extent of data which may not alway be the case).
So, what we can do is set the extent of the map to a more realistic view after plotting the image as in the following example:
```
fig = plt.figure(figsize=(15,10))
# plot the result with cartoee focusing on the south pole
ax = cartoee.get_map(ocean, cmap='plasma', vis_params=visualization, region=spole, proj=projection)
cb = cartoee.add_colorbar(ax, vis_params=visualization, loc='right', cmap='plasma')
ax.coastlines()
ax.set_title('The South Pole')
# get bounding box coordinates of a zoom area
zoom = spole
zoom[-1] = -20
# convert bbox coordinate from [W,S,E,N] to [W,E,S,N] as matplotlib expects
zoom_extent = cartoee.bbox_to_extent(zoom)
# set the extent of the map to the zoom area
ax.set_extent(zoom_extent,ccrs.PlateCarree())
plt.show()
```
| github_jupyter |
# 3. Naive Bayes: Un Ejemplo
Haremos un ejemplo para ilustrar el clasificador Naive Bayes.
En este ejemplo, clasificaremos textos según hablen de China ('zh') o Japón ('ja').
```
import numpy as np
```
## Datos de Entrenamiento
Supongamos que tenemos los siguientes datos de entrenamiento:
```
training = [
('chinese beijing chinese', 'zh'),
('chinese chinese shangai', 'zh'),
('chinese macao', 'zh'),
('tokyo japan chinese', 'ja'),
]
X_train = [doc for doc, _ in training]
y_train = [cls for _, cls in training]
X_train
classes = ['zh', 'ja']
features = ['chinese', 'beijing', 'shangai', 'macao', 'tokyo', 'japan']
```
## Clasificador Naive Bayes
### Distribución a Priori ("prior")
Calculemos la distribución a priori (probabilidad de cada clase) usando máxima verosimilitud:
$$P(Y = y) = \frac{Count(Y = y)}{\sum_{y'} Count(Y = y')}$$
```
from collections import Counter
class_count = Counter(y_train)
class_count
prior_prob = {}
for c in classes:
prior_prob[c] = class_count[c] / len(y_train)
print(f'P({c}) = {prior_prob[c]:0.2f}')
```
### Distribuciones Condicionales
Calculemos las distribuciones condicionales, esto es, la probabilidad de cada feature para cada clase.
Usaremos máxima verosimilitud y suavizado "add-one":
$$P(X_i = x|Y = y) = \frac{Count(X_i = x, Y = y) + 1}{\sum_{x'} Count(X_i = x', Y = y)+ |V|}$$
Primero calculamos los conteos:
```
feature_count = {}
for doc, cls in training:
tokens = doc.split() # lista de palabras
for feature in tokens:
if (feature, cls) not in feature_count:
feature_count[feature, cls] = 0
feature_count[feature, cls] = feature_count[feature, cls] + 1
```
O más cortito con `defaultdict`:
```
from collections import defaultdict
feature_count = defaultdict(int)
for doc, cls in training:
tokens = doc.split() # lista de palabras
for feature in tokens:
feature_count[feature, cls] += 1
dict(feature_count)
```
Ahora calculamos las distribuciones:
```
V = len(features)
cond_prob = {}
for c in classes:
cond_prob[c] = {}
count_sum = sum(feature_count[f, c] for f in features)
denom = count_sum + V
for f in features:
num = feature_count[f, c] + 1
cond_prob[c][f] = num / denom
print(f'P({f}|{c}) = {num} / {denom} ~ {cond_prob[c][f]:0.2f}')
```
### Predicción
Dado un documento, calculemos su clasificación. Para ello, calcularemos la probabilidad de cada clase, o mejor dicho algo propocional a esos valores (nos ahorramos el denominador $P(X=x)$).
$$P(Y=y|X=x) \propto P(Y=y) \prod_{i} P(X_i = x_i|Y=y)$$
```
doc = 'chinese chinese chinese tokyo japan'.split()
zh_prob = prior_prob['zh']
for w in doc:
zh_prob = zh_prob * cond_prob['zh'][w]
print(f'P(zh|doc) = {zh_prob:0.4f}')
ja_prob = prior_prob['ja']
for w in doc:
ja_prob = ja_prob * cond_prob['ja'][w]
print(f'P(ja|doc) = {ja_prob:0.4f}')
```
**¿Cuál es la clasificación?**
Valores probabilísticos:
```
zh_prob / (zh_prob + ja_prob), ja_prob / (zh_prob + ja_prob)
```
## Naive Bayes con Scikit-learn
Veamos cómo podemos clasificar documentos en **scikit-learn** usando Naive Bayes.
### Bolsas de Palabras (Bag of Words)
Representaremos a los documentos de manera vectorial usando bolsas de palabras:
```
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer()
```
Entrenamos (sin etiquetas) para que el vectorizador asigne una columna a cada feature posible:
```
vect.fit(X_train)
vect.get_feature_names()
```
Veamos cómo se vectorizan los datos de entrenamiento:
```
X2 = vect.transform(X_train)
X2
X2.todense()
```
Internamente, el vectorizador guarda el mapeo de features a columnas:
```
vect.vocabulary_
```
Ahora vectorizamos un nuevo documento:
```
doc = 'chinese chinese chinese tokyo japan'
X_test = vect.transform([doc])
X_test.todense()
```
### Multinomial Naive Bayes
Instanciamos y entrenamos Naive Bayes:
```
from sklearn.naive_bayes import MultinomialNB
mnb = MultinomialNB()
mnb.fit(X2, y_train)
```
Ahora predecimos:
```
mnb.predict(X_test)
```
También podemos obtener las probabilidades:
```
mnb.predict_proba(X_test)
```
### Parámetros Internos
Veamos cómo es internamente el modelo Naive Bayes en scikit-learn.
```
mnb.classes_
mnb.class_count_
mnb.feature_count_
np.exp(mnb.class_log_prior_)
np.exp(mnb.feature_log_prob_)
```
## Referencias
- [Naive Bayes classifier (Wikipedia)](https://en.wikipedia.org/wiki/Naive_Bayes_classifier)
Python:
- [defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict)
Scikit-learn:
- [Working With Text Data](https://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html)
- [CountVectorizer](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html)
- [Naive Bayes](https://scikit-learn.org/stable/modules/naive_bayes.html#naive-bayes)
| github_jupyter |
# Oil and Gas Visualization/Dashboard
### Import required libraries
```
import numpy as np
import pandas as pd
import plotly.plotly as py
import plotly.offline as pyo
import cufflinks as cf
```
### Import New York State dataset
```
df = pd.read_csv('data/wellspublic.csv', low_memory=False)
df.shape
df.columns
```
### Make scattermapbox map
```
types = dict(
BR = 'Brine',
Confidential = 'Confidential',
DH = 'Dry Hole',
DS = 'Disposal',
DW = 'Dry Wildcat',
GD = 'Gas Development',
GE = 'Gas Extension',
GW = 'Gas Wildcat',
IG = 'Gas Injection Well',
IW = 'Enhanced Oil Recovery - Injection',
LP = 'Liquefied Petroleum Gas Storage',
MB = 'Monitoring Brine',
MM = 'Monitoring Miscellaneous',
MS = 'Monitoring Storage',
NL = 'Not Listed',
OB = 'Observation Well',
OD = 'Oil Development',
OE = 'Oil Extension',
OW = 'Oil Wildcat',
SG = 'Stratigraphic',
ST = 'Storage',
TH = 'Geothermal',
UN = 'Unknown',
)
traces = []
for well, df in df.groupby('Well_Type'):
trace = dict(
type = 'scattermapbox',
lon = df['Surface_Longitude'],
lat = df['Surface_latitude'],
text = df['Well_Name'],
name = types[well],
marker = dict(
size = 4,
opacity = 0.6,
)
)
traces.append(trace)
# trace = dict(
# type = 'scattermapbox',
# lon = df['Surface_Longitude'],
# lat = df['Surface_latitude'],
# name = df['Well_Name'],
# )
# traces = [trace]
mapbox_access_token = 'pk.eyJ1IjoiamFja2x1byIsImEiOiJjaXhzYTB0bHcwOHNoMnFtOWZ3YWdreDB3In0.pjROwb9_CEuyKPE-x0lRUw'
layout = dict(
title = "New York Oil and Gas map",
# GENERAL LAYOUT
width = 1280,
height = 720,
autosize = True,
font = dict(
family = "Overpass",
size = 12,
color = '#CCCCCC',
),
margin = dict(
t = 80,
l = 40,
b = 40,
r = 120,
pad = 0,
),
# OPTIONAL
hovermode = "closest",
# COLOR THEME
plot_bgcolor = "#191A1A",
paper_bgcolor = "#020202",
# LEGEND
legend = dict(
x = 1.02,
y = 1,
font = dict(size = 10),
),
# MAPBOX
mapbox = dict(
accesstoken = mapbox_access_token,
style = "dark",
center = dict(
lon = -76.40,
lat = 42.70,
),
zoom = 5.5,
),
)
figure = dict(data=traces, layout=layout)
py.plot(figure, filename='Oil map')
```
| github_jupyter |
# [Applied Statistics](https://lamastex.github.io/scalable-data-science/as/2019/)
## 1MS926, Spring 2019, Uppsala University
©2019 Raazesh Sainudiin. [Attribution 4.0 International (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/)
# Assignment 3 for Course 1MS926
Fill in your Personal Number, make sure you pass the `# ... Test` cells and
submit by email from your official `uu.se` student email account to `raazesh.sainudiin` `@` `math.uu.se` with *Subject line* **1MS926 Assignment 3**.
You can submit multiple times before the deadline and your highest score will be used.
```
# Enter your 12 digit personal number here and evaluate this cell
MyPersonalNumber = 'YYYYMMDDXXXX'
#tests
assert(isinstance(MyPersonalNumber, basestring))
assert(MyPersonalNumber.isdigit())
assert(len(MyPersonalNumber)==12)
```
---
## Assignment 3, PROBLEM 1
Maximum Points = 1
Using the steps in the Sample Exam Problem 1 with Solution in notebook `09.ipynb`, derive the maximum likelihood estimate for $n$ IID samples from a random variable with the following probability density function:
$$
f(x; \lambda) = \frac{1}{24} \lambda^5 x^4 \exp(-\lambda x), \qquad \text{ where, } \lambda>0, x > 0
$$
You can solve the MLe by hand (using pencil paper or using key-strokes). Present your solution as the return value of a function called `def MLeForAssignment3Problem1(x)`, where `x` is a list of $n$ input data points.
```
# do not change the name of the function, just replace XXX with the appropriate expressions for the MLe
def MLeForAssignment3Problem1(x):
'''write comment of what this function does'''
XXX
XXX
return XXX
```
---
## Assignment 3, PROBLEM 2
Maximum Points = 2
Joshua Fenemore collected data in 2007 on waiting times at the Orbiter bus-stop close to University of Canterbury, Christchurch, New Zealand.
The sampled waiting times at the bus-stop, i.e., the inter-arrival time between consecutive buses, were recored in units of nearest minute and are given in the list `sampleWaitingTimes` below.
Your **task** is to assume that the inter-arrival time between Orbiter buses is independent and identically distributed according to $Exponential(\lambda)$ random variable and write a generic function:
- called `mleOfExponetialLambdaRVFromIIDSamples(samples)`,
- where `samples` is a `list` of data points assumed to be drawn from IID $Exponential(\lambda)$ random variable,
- such that, the function returns the maximum likelihood estimate or MLe $\widehat{\lambda}_n$ of the unknown rate parameter $\lambda$
- finally get the MLe for Joshua's data by calling your function on his samples as follows:
- `mleOfRateParameterForOrbiterWaitingTimes = mleOfExponetialLambdaRVFromIIDSamples(sampleWaitingTimes)`
(NOTE: The MLe for this model was already derived "above", i.e., in `09.ipynb`, so you can directly use this expression to complete your task).
```
# do not change the sampled data-points in sampleWaitingTimes
sampleWaitingTimes=[8,3,7,18,18,3,7,9,9,25,0,0,25,6,10,0,10,8,16,9,1,5,16,6,4,1,3,21,0,28,3,8,6,6,11,\
8,10,15,0,8,7,11,10,9,12,13,8,10,11,8,7,11,5,9,11,14,13,5,8,9,12,10,13,6,11,13,0,\
0,11,1,9,5,14,16,2,10,21,1,14,2,10,24,6,1,14,14,0,14,4,11,15,0,10,2,13,2,22,10,5,\
6,13,1,13,10,11,4,7,9,12,8,16,15,14,5,10,12,9,8,0,5,13,13,6,8,4,13,15,7,11,6,23,1]
# do not change the next line, but just replace XXX - 1 POINT
# in the body of the function to complete your task
def mleOfExponetialLambdaRVFromIIDSamples(samples):
'''XXX'''
XXX
XXX
return XXX
# You should not change anything in the line below - 1 POINT
mleOfRateParameterForOrbiterWaitingTimes = mleOfExponetialLambdaRVFromIIDSamples(sampleWaitingTimes)
```
---
## Assignment 3, PROBLEM 3
Maximum Points = 2
Use Bounded 1D Optimisation to find the maximum likelihood estimate for the IID $Bernoulli(\theta)$ experiment using data in the array `dataSamples` below.
HINT: First, Study the Solution to the **Sample Exam Problem 2**.
```
import numpy as np
from scipy import optimize
# do not change next line - dataSamplesCoinToss is the sampled data-points
dataSamplesCoinToss= np.array([0,0,1,1,1,1,1,0,0,1,1,0,0,1,1,0,0])
# finding MLE for IID Bernoulli(theta) RV
# do not Chnage the name of the next function - just replace XXX
def negLogLklOBernoulliIIDSamples(paramLam):
'''XXX'''
XXX
XXX
return XXX
theta_initial=XXX
# do NOT change the next two lines
boundedBernoulliResult = optimize.minimize_scalar(negLogLklOBernoulliIIDSamples, theta_initial, \
bounds=(0.001, 0.099), method='bounded')
boundedBernoulliResult
```
---
## Assignment 3, PROBLEM 4
Maximum Points = 2
Use the **Multi-dimensional Constrained Optimisation** example above (in `09.ipynb`) to numerically find the MLe for the mean and variance parameter based on `normallySimulatedDataSamples`, an array obtained by a specific simulation of $30$ IID samples from the $Normal(10,2)$ random variable.
Recall that $Normal(\mu, \sigma^2)$ RV has the probability density function given by:
$$
f(x ;\mu, \sigma) = \displaystyle\frac{1}{\sigma\sqrt{2\pi}}\exp\left(\frac{-1}{2\sigma^2}(x-\mu)^2\right)
$$
The two parameters, $\mu \in \mathbb{R} := (-\infty,\infty)$ and $\sigma \in (0,\infty)$, are sometimes referred to as the location and scale parameters.
You know that the log likelihood function for $n$ IID samples from a Normal RV with parameters $\mu$ and $\sigma$ simply follows from $\sum_{i=1}^n \log(f(x_i; \mu,\sigma))$, based on the IID assumption.
NOTE: When setting bounding boxes for $\mu$ and $\sigma$ try to start with some guesses like $[-20,20]$ and $[0.1,5.0]$ and make it larger if the solution is at the boundary. Making the left bounding-point for $\sigma$ too close to $0.0$ will cause division by zero Warnings. Other numerical instabilities can happen in such iterative numerical solutions to the MLe. You need to be patient and learn by trial-and-error. You will see the mathematical theory in more details in a future course in scientific computing/optimisation. So don't worry too much now except learning to use it for our problems.
```
import numpy as np
from scipy import optimize
# do NOT change the next three lines
np.random.seed(123456) # set seed
# simulate 30 IID samples drawn from Normal(10,2)RV
normallySimulatedDataSamples = np.random.normal(10,2,30)
# define the negative log likelihoo function you want to minimise by editing XXX
def negLogLklOfIIDNormalSamples(parameters):
'''return the -log(likelihood) of normallySimulatedDataSamples with mean and var parameters'''
mu_param=parameters[0]
sigma_param=parameters[1]
XXX
XXX # add more or less lines as you need
return XXX
# you should only change XXX below and not anything else
parameter_bounding_box=((XXX, XXX), (XXX, XXX)) # specify the constraints for each parameter - some guess work...
initial_arguments = np.array([XXX, XXX]) # point in 2D to initialise the minimize algorithm
result_Ass3Prob4 = optimize.minimize(XXX, initial_arguments, bounds=parameter_bounding_box, XXX)
# call the minimize method above finally! you need to play a bit to get initial conditions and bounding box ok
result_Ass3Prob4
```
---
## Assignment 3, PROBLEM 5
Maximum Points = 3
Obtain the 95% CI based on the asymptotic normality of the MLE for the mean paramater $\lambda$ based on $n$ IID $Poisson(\lambda^*)$ trials.
Recall that a random variable $X \sim Poisson(\lambda)$ if its probability mass function is:
$$
f(x; \lambda) = \exp{(-\lambda)} \frac{\lambda^x}{x!}, \quad \lambda > 0, \quad x \in \{0,1,2,\ldots\}
$$
The MLe $\widehat{\lambda}_n = \overline{x}_n$, the sample mean.
Work out your answer and express it in the next cell by replacing `XXX`s.
```
# Only replace the XXX below, do not change the function naemes or parameters
samplePoissonCounts = np.array([0,5,11,5,6,8,9,0,1,14,2,4,4,11,2,12,10,5,6,1,7,9,8,0,5,7,11,6,0,1])
def Assignment3Problem5(poissonSamples):
'''return the 95% confidence interval as a 2-tuple for the unknown rate parameter lambda*
from n IID Exponential(lambda*) trials in the input numpy array called exponentialSamples'''
XXX
XXX
XXX
lower95CI=XXX
upper95CI=XXX
return (lower95CI,upper95CI)
# do NOT change anything below
lowerCISampleExamProblem5,upperCISampleExamProblem5 = Assignment3Problem5(samplePoissonCounts)
print "The 95% CI for lambda based on IID Poisson(lambda) data in samplePoissonCounts = "
print (lowerCISampleExamProblem5,upperCISampleExamProblem5)
```
---
## Assignment 3, PROBLEM 6
Maximum Points = 3
For the Orbiter waiting time problem, assuming IID trials as follows:
$$\displaystyle{X_1,X_2,\ldots,X_{n} \overset{IID}{\sim} Exponential(\lambda^*)}$$
Your task is to perform a Wald Test of size $\alpha=0.05$ to try to reject the null hypothesis that the waiting time at the Orbiter bus-stop, i.e., the inter-arrival time between buses, is exactly $10$ minutes:
$$\displaystyle{H_0: \lambda^*=\lambda_0 \quad \text{ versus } \quad H_1: \lambda^* \neq \lambda_0, \qquad \text{ with }\lambda_0=0.1}$$
Show you work by replacing `XXX`s with the right expressions in the next cell.
```
sampleWaitingTimes = np.array([8,3,7,18,18,3,7,9,9,25,0,0,25,6,10,0,10,8,16,9,1,5,16,6,4,1,3,21,0,28,3,8,6,6,11,\
8,10,15,0,8,7,11,10,9,12,13,8,10,11,8,7,11,5,9,11,14,13,5,8,9,12,10,13,6,11,13,0,\
0,11,1,9,5,14,16,2,10,21,1,14,2,10,24,6,1,14,14,0,14,4,11,15,0,10,2,13,2,22,10,5,\
6,13,1,13,10,11,4,7,9,12,8,16,15,14,5,10,12,9,8,0,5,13,13,6,8,4,13,15,7,11,6,23,1])
#test H0: lambda=0.1
## STEP 1: get the MLE thetaHat
lambdaHat=XXX # you need to use sampleWaitingTimes here!
print "mle lambdaHat = ",lambdaHat
## STEP 2: get the NullLambda or lambda0
NullLambda=XXX
print "Null value of lambda under H0 = ", NullLambda
## STEP 3: get estimated standard error
seLambda=XXX # see Sample Exam Problem 5 in 10.ipynb
print "estimated standard error",seLambda
# STEP 4: get Wald Statistic
W=XXX
print "Wald staatistic = ",W
# STEP 5: conduct the size alpha=0.05 Wald test
# do NOT change anything below
rejectNullAssignment3Problem6 = abs(W) > 2.0 # alpha=0.05, so z_{alpha/2} =1.96 approx=2.0
if (rejectNullAssignment3Problem6):
print "we reject the null hypothesis that lambda0=0.1"
else:
print "we fail to reject the null hypothesis that lambda0=0.1"
```
---
## Assignment 3, PROBLEM 7
Maximum Points = 2
Repeat the **three steps to perform a bootstrap** above as done in **Median of inter-EQ Time** example (notebook `11.ipynb`) to find the plug-in estimate and 95% CI for the *99-th Percentile of the inter-EQ time in minutes*.
You just need to evaluate the next `REQUIRED-CELL` and replace `XXX` with the right expressions in the following cell.
HINT: Median is the $50$-th Percentile.
```
# REQUIRED-CELL
# DO NOT MODIFY this cell
# Evaluate this cell before trying this PROBLEM so that the required functions and variables are loaded
import numpy as np
## Be Patient! - This will take more time, about a minute or so
###############################################################################################
def getLonLatMagDepTimes(NZEQCsvFileName):
'''returns longitude, latitude, magnitude, depth and the origin time as unix time
for each observed earthquake in the csv filr named NZEQCsvFileName'''
from datetime import datetime
import time
from dateutil.parser import parse
import numpy as np
with open(NZEQCsvFileName) as f:
reader = f.read()
dataList = reader.split('\n')
myDataAccumulatorList =[]
for data in dataList[1:-1]:
dataRow = data.split(',')
myTimeString = dataRow[2] # origintime
# let's also grab longitude, latitude, magnitude, depth
myDataString = [dataRow[4],dataRow[5],dataRow[6],dataRow[7]]
try:
myTypedTime = time.mktime(parse(myTimeString).timetuple())
myFloatData = [float(x) for x in myDataString]
myFloatData.append(myTypedTime) # append the processed timestamp
myDataAccumulatorList.append(myFloatData)
except TypeError, e: # error handling for type incompatibilities
print 'Error: Error is ', e
#return np.array(myDataAccumulatorList)
return myDataAccumulatorList
myProcessedList = getLonLatMagDepTimes('data/earthquakes.csv')
def interQuakeTimes(quakeTimes):
'''Return a list inter-earthquake times in seconds from earthquake origin times
Date and time elements are expected to be in the 5th column of the array
Return a list of inter-quake times in seconds. NEEDS sorted quakeTimes Data'''
import numpy as np
retList = []
if len(quakeTimes) > 1:
retList = [quakeTimes[i]-quakeTimes[i-1] for i in range(1,len(quakeTimes))]
#return np.array(retList)
return retList
def makeBootstrappedConfidenceIntervalOfStatisticT(dataset, statT, alpha, B=100):
'''make a bootstrapped 1-alpha confidence interval for ANY given statistic statT
from the dataset with B Bootstrap replications for 0 < alpha < 1, and
return lower CI, upper CI, bootstrapped_samples '''
n = len(dataset) # sample size of the original dataset
bootstrappedStatisticTs=[] # list to store the statistic T from each bootstrapped data
for b in range(B):
#sample indices at random between 0 and len(iQMinutes)-1 to make the bootstrapped dataset
randIndices=[randint(0,n-1) for i in range(n)]
bootstrappedDataset = dataset[randIndices] # resample with replacement from original dataset
bootstrappedStatisticT = statT(bootstrappedDataset)
bootstrappedStatisticTs.append(bootstrappedStatisticT)
# noe get the [2.5%, 97.5%] percentile-based CI
alpaAsPercentage=alpha*100.0
lowerBootstrap1MinusAlphaCIForStatisticT = np.percentile(bootstrappedStatisticTs,alpaAsPercentage/2)
upperBootstrap1MinusAlphaCIForStatisticT = np.percentile(bootstrappedStatisticTs,100-alpaAsPercentage/2)
#print "The inner (1 - "+str(alpha)+" ) percentile based Confidence Interval for the statistic T = "
#print "[ "+str(lowerBootstrap1MinusAlphaCIForStatisticT)+" , " +str(upperBootstrap1MinusAlphaCIForStatisticT)+" ]"
return (lowerBootstrap1MinusAlphaCIForStatisticT,upperBootstrap1MinusAlphaCIForStatisticT,\
np.array(bootstrappedStatisticTs))
interQuakesSecs = interQuakeTimes(sorted([x[4] for x in myProcessedList]))
iQMinutes = np.array(interQuakesSecs)/60.0
###############################################################################################
statT99thPercentile = lambda dataset : XXX #statistic of interest
alpha=XXX
B=1000 # number of bootstrap samples, reduce this to 100 while debuging and back to 1000 when done
# plug-in point estimate of the 99th-Percentile of inter-EQ Times
plugInEstimateOf99thPercentile = XXX
# get the bootstrapped samples and build 1-alpha confidence interval
# do NOT change anything below
lowerCIT99P,upperCIT99P,bootValuesT99P = \
makeBootstrappedConfidenceIntervalOfStatisticT(iQMinutes, statT99thPercentile, alpha, B)
print "The Plug-in Point Estimate of the 99th-Percentile of inter-EQ Times = ", plugInEstimateOf99thPercentile
print "1-alpha Bootstrapped CI for the 99th-Percentile of inter-EQ Times = ",(lowerCIT99P,upperCIT99P)
print " for alpha = ",alpha.n(digits=2)," and bootstrap replicates = ",B
```
---
## Assignment 3, PROBLEM 8
Maximum Points = 2
For the fitted regression model in the next cell get the residuals and plot them against the covariate [see **Residual analysis** section in latest `12.ipynb` for the basic ideas conveyed in the last lecture].
How do the residuals compare to a Normal random variable centred at $0$ with a constant variance (summarise in a sentence or two by double-clicking this cell and writing in between the two lines `---` below)?
---
---
```
logLightIntens_logSurfTemp=[(4.37,5.23),(4.56,5.74),
(4.26,4.93),(4.56,5.74),(4.30,5.19),(4.46,5.46),(3.84,4.65),(4.57,5.27),(4.26,5.57),(4.37,5.12),(3.49,5.73),
(4.43,5.45),(4.48,5.42),(4.01,4.05),(4.29,4.26),(4.42,4.58),(4.23,3.94),(4.42,4.18),(4.23,4.18),(3.49,5.89),
(4.29,4.38),(4.29,4.22),(4.42,4.42),(4.49,4.85),(4.38,5.02),(4.42,4.66),(4.29,4.66),(4.38,4.90),(4.22,4.39),
(3.48,6.05),(4.38,4.42),(4.56,5.10),(4.45,5.22),(3.49,6.29),(4.23,4.34),(4.62,5.62),(4.53,5.10),(4.45,5.22),
(4.53,5.18),(4.43,5.57),(4.38,4.62),(4.45,5.06),(4.50,5.34),(4.45,5.34),(4.55,5.54),(4.45,4.98),(4.42,4.50)]
CleanedlogLightIntens_logSurfTemp=\
np.array([yx for yx in logLightIntens_logSurfTemp if yx[1]<5.9 and yx[0]>4]) # data range constraint
x=CleanedlogLightIntens_logSurfTemp[:,1]
y=CleanedlogLightIntens_logSurfTemp[:,0]
from scipy.linalg import lstsq
import matplotlib.pyplot as plt
import numpy as np
M1 = x[:, np.newaxis]^[0, 1]
b, res, rnk, s = lstsq(M1, y)
plt.plot(x, y, 'o', label='data')
xx = np.linspace(3.9, 5.8, 101)
yy = b[0] + b[1]*xx
plt.plot(xx, yy, label='least squares fit')
plt.xlabel('log light intensity (X)')
plt.ylabel('log surface temperature (Y)')
plt.legend(framealpha=1, shadow=True)
plt.grid(alpha=0.25)
plt.text(4, 4.7, r'$\widehat{r}(x) = \widehat{\beta}_0 + \widehat{\beta}_1 x, \quad \
\widehat{\beta}_0 = $ %(b0)0.3f , $\widehat{\beta}_1 = $ %(b1)0.3f' % {'b0': b[0], 'b1': b[1]} )
plt.show()
# Obtain the residuals and plot them (summarise in the markdown cell above)
XXX
XXX
XXX
```
| github_jupyter |
## Face and Facial Keypoint detection
After you've trained a neural network to detect facial keypoints, you can then apply this network to *any* image that includes faces. The neural network expects a Tensor of a certain size as input and, so, to detect any face, you'll first have to do some pre-processing.
1. Detect all the faces in an image using a face detector (we'll be using a Haar Cascade detector in this notebook).
2. Pre-process those face images so that they are grayscale, and transformed to a Tensor of the input size that your net expects. This step will be similar to the `data_transform` you created and applied in Notebook 2, whose job was tp rescale, normalize, and turn any iimage into a Tensor to be accepted as input to your CNN.
3. Use your trained model to detect facial keypoints on the image.
---
In the next python cell we load in required libraries for this section of the project.
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
```
#### Select an image
Select an image to perform facial keypoint detection on; you can select any image of faces in the `images/` directory.
```
import cv2
# load in color image for face detection
image = cv2.imread('images/obamas.jpg')
# switch red and blue color channels
# --> by default OpenCV assumes BLUE comes first, not RED as in many images
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# plot the image
fig = plt.figure(figsize=(9,9))
plt.imshow(image)
```
## Detect all faces in an image
Next, you'll use one of OpenCV's pre-trained Haar Cascade classifiers, all of which can be found in the `detector_architectures/` directory, to find any faces in your selected image.
In the code below, we loop over each face in the original image and draw a red square on each face (in a copy of the original image, so as not to modify the original). You can even [add eye detections](https://docs.opencv.org/3.4.1/d7/d8b/tutorial_py_face_detection.html) as an *optional* exercise in using Haar detectors.
An example of face detection on a variety of images is shown below.
<img src='images/haar_cascade_ex.png' width=80% height=80%/>
```
# load in a haar cascade classifier for detecting frontal faces
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# run the detector
# the output here is an array of detections; the corners of each detection box
# if necessary, modify these parameters until you successfully identify every face in a given image
faces = face_cascade.detectMultiScale(image, 1.2, 2)
# make a copy of the original image to plot detections on
image_with_detections = image.copy()
# loop over the detected faces, mark the image where each face is found
for (x,y,w,h) in faces:
# draw a rectangle around each detected face
# you may also need to change the width of the rectangle drawn depending on image resolution
cv2.rectangle(image_with_detections,(x,y),(x+w,y+h),(255,0,0),3)
fig = plt.figure(figsize=(9,9))
plt.imshow(image_with_detections)
```
## Loading in a trained model
Once you have an image to work with (and, again, you can select any image of faces in the `images/` directory), the next step is to pre-process that image and feed it into your CNN facial keypoint detector.
First, load your best model by its filename.
```
import torch
from models import Net
net = Net()
## TODO: load the best saved model parameters (by your path name)
## You'll need to un-comment the line below and add the correct name for *your* saved model
net.load_state_dict(torch.load('saved_models/keypoints_model_1.pt'))
## print out your net and prepare it for testing (uncomment the line below)
net.eval()
```
## Keypoint detection
Now, we'll loop over each detected face in an image (again!) only this time, you'll transform those faces in Tensors that your CNN can accept as input images.
### TODO: Transform each detected face into an input Tensor
You'll need to perform the following steps for each detected face:
1. Convert the face from RGB to grayscale
2. Normalize the grayscale image so that its color range falls in [0,1] instead of [0,255]
3. Rescale the detected face to be the expected square size for your CNN (224x224, suggested)
4. Reshape the numpy image into a torch image.
**Hint**: The sizes of faces detected by a Haar detector and the faces your network has been trained on are of different sizes. If you find that your model is generating keypoints that are too small for a given face, try adding some padding to the detected `roi` before giving it as input to your model.
You may find it useful to consult to transformation code in `data_load.py` to help you perform these processing steps.
### TODO: Detect and display the predicted keypoints
After each face has been appropriately converted into an input Tensor for your network to see as input, you can apply your `net` to each face. The ouput should be the predicted the facial keypoints. These keypoints will need to be "un-normalized" for display, and you may find it helpful to write a helper function like `show_keypoints`. You should end up with an image like the following with facial keypoints that closely match the facial features on each individual face:
<img src='images/michelle_detected.png' width=30% height=30%/>
```
# NOTE: This function is same as the one provided by Udacity as template code in the previous notebook.
# Only the marker size has been changed after reading above example.
def show_all_keypoints(image, predicted_key_pts):
"""Show image with predicted keypoints"""
# image is grayscale
plt.figure()
plt.imshow(image, cmap='gray')
plt.scatter(predicted_key_pts[:, 0], predicted_key_pts[:, 1], s=5, marker='.', c='m')
image_copy = np.copy(image)
# loop over the detected faces from your haar cascade
for (x,y,w,h) in faces:
# Select the region of interest that is the face in the image
roi = image_copy[y-50:y+h+50, x-40:x+w+40] # the numeric values are needed for scaling the output keypoints correctly.
width_roi = roi.shape[1] # needed later for scaling keypoints
height_roi = roi.shape[0] # needed later for scaling keypoints
roi_copy = np.copy(roi) # will be used as background to display final keypints.
## TODO: Convert the face region from RGB to grayscale
roi = cv2.cvtColor(roi, cv2.COLOR_RGB2GRAY)
## TODO: Normalize the grayscale image so that its color range falls in [0,1] instead of [0,255]
roi = roi/255.0
## TODO: Rescale the detected face to be the expected square size for your CNN (224x224, suggested)
roi = cv2.resize(roi, (96, 96)) # resize the image to get a square 96*96 image.
roi = np.reshape(roi,(96, 96, 1)) # reshape after rescaling to add the third color dimension.
## TODO: Reshape the numpy image shape (H x W x C) into a torch image shape (C x H x W)
roi = roi.transpose(2, 0, 1)
## TODO: Make facial keypoint predictions using your loaded, trained network
roi = torch.from_numpy(roi).type(torch.FloatTensor) # convert images to FloatTensors (common source of error)
# Runtime error : expected stride to be a single integer value or a list of 1 values to match the convolution dimensions,
# but got stride=[1, 1]. This error will occur if the following line is omitted. Hence we need to apply unsqueeze operation.
roi = roi.unsqueeze(0)
# Pass the transformed input images to the network for detecting keypoints.
keypoints = net(roi)
keypoints = keypoints.view(68, 2)
# Undo the transformations performed on the facial keypoints
keypoints = keypoints.data.numpy()
keypoints = keypoints*50.0 + 100
## TODO: Display each detected face and the corresponding keypoints
keypoints = keypoints * (width_roi / 96, height_roi / 90) # scale the keypoints to match the size of the output display.
plt.figure()
# Using helper function for display as defined previously.
show_all_keypoints(roi_copy, keypoints)
plt.show()
```
| github_jupyter |
```
# hide
%load_ext autoreload
%autoreload 2
%load_ext nb_black
%load_ext lab_black
# default_exp model
```
# Model
> Generating predictions for Numerai on preprocessed data.
## Overview
Currently supported frameworks and formats:
1. `.joblib` (Common format to save Python objects. These models should have a `.predict` method. Especially convenient for [sklearn models](https://scikit-learn.org/stable/supervised_learning.html).)
2. `.pickle`/`.pkl` (Arbitrary Python objects. All pickled models should have a `.predict` method.)
3. `.cbm` (Easy format to load [CatBoost](https://catboost.ai/en/docs/) models.)
4. `.lgb` (Format to load [LightGBM](https://lightgbm.readthedocs.io/en/latest/) models.)
5. `.h5` ([tf.keras](https://keras.io/) models)
6. Baseline models for which loading from files is not relevant (i.e. `ConstantModel` and `RandomModel`.)
It is recommended to use models within a `ModelPipeline`, but they can also be used on its own.
The last section of this notebook explains two different ways you can implement your own models:
1. From `BaseModel` (custom prediction logic).
2. From `DirectoryModel` (make predictions for all models in directory with given file suffix.
Prediction logic will already be implemented. Only write model loading logic).
```
# hide
from nbdev.showdoc import *
#export
import os
import gc
import uuid
import wandb
import joblib
import pickle
import numpy as np
import pandas as pd
import lightgbm as lgb
import tensorflow as tf
from pathlib import Path
from typing import Union
from tqdm.auto import tqdm
from functools import partial
from catboost import CatBoost
from numerbay import NumerBay
from typeguard import typechecked
from abc import ABC, abstractmethod
from rich import print as rich_print
from sklearn.dummy import DummyRegressor
from numerblox.download import NumeraiClassicDownloader
from numerblox.numerframe import NumerFrame, create_numerframe
from numerblox.preprocessing import display_processor_info
```
## 0. Base
### 0.1. BaseModel
The `BaseModel` is an abstract base class that handles directory logic and naming conventions. All models should inherit from `BaseModel` and be sure to implement the `.predict` method.
In general, models are loaded in from disk. However, if no model files are involved in your model you should pass an empty string (`""`) as the `model_directory` argument.
Note that a new prediction column will have the column name `prediction_{MODEL_NAME}`.
```
#export
class BaseModel(ABC):
"""
Setup for model prediction on a Dataset.
:param model_directory: Main directory from which to read in models. \n
:param model_name: Name that will be used to create column names and for display purposes.
"""
def __init__(self, model_directory: str,
model_name: str = None,
):
self.model_directory = Path(model_directory)
self.model_name = model_name if model_name else uuid.uuid4().hex
self.prediction_col_name = f"prediction_{self.model_name}"
self.description = f"{self.__class__.__name__}: '{self.model_name}' prediction"
@abstractmethod
def predict(self, dataf: Union[pd.DataFrame, NumerFrame]) -> NumerFrame:
""" Return NumerFrame with column added for prediction. """
...
return NumerFrame(dataf)
def get_prediction_col_names(self, pred_shape: tuple) -> list:
""" Create multiple columns if predictions are multi-target. """
prediction_cols = self.prediction_col_name
if len(pred_shape) > 1:
if pred_shape[1] > 1:
prediction_cols = [f"{self.prediction_col_name}_{i}" for i in range(pred_shape[1])]
return prediction_cols
def __call__(self, dataf: Union[pd.DataFrame, NumerFrame]) -> NumerFrame:
return self.predict(dataf=dataf)
```
### 0.2. DirectoryModel
A `DirectoryModel` assumes that you have a directory of models and you want to load + predict for all models with a certain `file_suffix` (for example, `.joblib`, `.cbm` or `.lgb`). This base class handles prediction logic for this situation.
If you are thinking of implementing your own model and your use case involves reading multiple models from a directory, then you should inherit from `DirectoryModel` and be sure to implement `.load_models`. You then don't have to implement any prediction logic in the `.predict` method.
When inheriting from `DirectoryModel` the only mandatory method implementation is for `.load_models`. It should instantiate all models and return them as a `list`.
```
#export
class DirectoryModel(BaseModel):
"""
Base class implementation where predictions are averaged out from a directory of models. Walks through every file with given file_suffix in a directory.
:param model_directory: Main directory from which to read in models. \n
:param file_suffix: File format to load (For example, .joblib, .pkl, .cbm or .lgb) \n
:param model_name: Name that will be used to create column names and for display purposes. \n
:param feature_cols: optional list of features to use for prediction. Selects all feature columns (i.e. column names with prefix 'feature') by default. \n
:param combine_preds: Whether to average predictions along column axis. Only relevant for multi target models. \n
Convenient when you want to predict the main target by averaging a multi-target model.
"""
def __init__(self, model_directory: str, file_suffix: str,
model_name: str = None,
feature_cols: list = None,
combine_preds = True,
):
super().__init__(model_directory=model_directory,
model_name=model_name,
)
self.file_suffix = file_suffix
self.model_paths = list(self.model_directory.glob(f'*.{self.file_suffix}'))
if self.file_suffix:
assert self.model_paths, f"No {self.file_suffix} files found in {self.model_directory}."
self.total_models = len(self.model_paths)
self.feature_cols = feature_cols
self.combine_preds = combine_preds
@display_processor_info
def predict(self, dataf: NumerFrame, *args, **kwargs) -> NumerFrame:
"""
Use all recognized models to make predictions and average them out.
:param dataf: A Preprocessed DataFrame where all its features can be passed to the model predict method.
*args, **kwargs will be parsed into the model.predict method.
:return: A new dataset with prediction column added.
"""
dataf.loc[:, self.prediction_col_name] = np.zeros(len(dataf))
models = self.load_models()
feature_cols = self.feature_cols if self.feature_cols else dataf.feature_cols
for model in tqdm(models, desc=self.description, position=1):
predictions = model.predict(dataf[feature_cols], *args, **kwargs)
# Check for if model output is a Pandas DataFrame
predictions = predictions.values if isinstance(predictions, pd.DataFrame) else predictions
predictions = predictions.mean(axis=1) if self.combine_preds and len(predictions.shape) > 1 else predictions
prediction_cols = self.get_prediction_col_names(predictions.shape)
dataf.loc[:, prediction_cols] = dataf.loc[:, prediction_cols] + (predictions / self.total_models)
del models; gc.collect()
return NumerFrame(dataf)
@abstractmethod
def load_models(self) -> list:
""" Instantiate all models detected in self.model_paths. """
...
```
## 1. Single model formats
Implementations for common Numerai model prediction situations.
### 1.1. SingleModel
In many cases you just want to load a single model file and create predictions for that model. `SingleModel` supports this.
This class supports multiple model formats for easy use. All models should have a `.predict` method.
Currently, `.joblib`, `.cbm`, `.pkl`, `.pickle` and `.h5` (keras) format are supported.
**Things to keep in mind**
- This model will use all available features in the `NumerFrame` and use them for prediction by default. Define `feature_cols` in `SingleModel` or implement a `FeatureSelectionPreProcessor` as part of your `ModelPipeline` if you are using a subset of features.
- If you have XGBoost models we recommend saving them as `.joblib`.
- The added prediction column will have the column name `prediction_{MODEL_NAME}` if 1 target is predicted.
For multiple targets the new column names will be `prediction_{MODEL_NAME}_{i}` for each target number i (starting with 0).
- We welcome the Numerai community to extend `SingleModel` for more file formats. See the Contributing section in `README.md` for more information on contributing.
```
#export
@typechecked
class SingleModel(BaseModel):
"""
Load single model from file and perform prediction logic.
:param model_file_path: Full path to model file. \n
:param model_name: Name that will be used to create column names and for display purposes. \n
:param combine_preds: Whether to average predictions along column axis. Only relevant for multi target models.
Convenient when you want to predict the main target by averaging a multi-target model. \n
:param autoencoder_mlp: Whether your model is an autoencoder + MLP model.
Will take the 3rd of tuple output in this case. Only relevant for NN models.
More info on autoencoders:
https://forum.numer.ai/t/autoencoder-and-multitask-mlp-on-new-dataset-from-kaggle-jane-street/4338 \n
:param feature_cols: optional list of features to use for prediction. Selects all feature columns (i.e. column names with prefix 'feature') by default.
"""
def __init__(self, model_file_path: str, model_name: str = None,
combine_preds = False, autoencoder_mlp = False,
feature_cols: list = None
):
self.model_file_path = Path(model_file_path)
assert self.model_file_path.exists(), f"File path '{self.model_file_path}' does not exist."
assert self.model_file_path.is_file(), f"File path must point to file. Not valid for '{self.model_file_path}'."
super().__init__(model_directory=str(self.model_file_path.parent),
model_name=model_name,
)
self.model_suffix = self.model_file_path.suffix
self.suffix_to_model_mapping = {".joblib": joblib.load,
".cbm": CatBoost().load_model,
".pkl": pickle.load,
".pickle": pickle.load,
".h5": partial(tf.keras.models.load_model, compile=False)
}
self.__check_valid_suffix()
self.combine_preds = combine_preds
self.autoencoder_mlp = autoencoder_mlp
self.feature_cols = feature_cols
def predict(self, dataf: NumerFrame, *args, **kwargs) -> NumerFrame:
model = self._load_model(*args, **kwargs)
feature_cols = self.feature_cols if self.feature_cols else dataf.feature_cols
predictions = model.predict(dataf[feature_cols])
# Check for if model output is a Pandas DataFrame
predictions = predictions.values if isinstance(predictions, pd.DataFrame) else predictions
predictions = predictions[2] if self.autoencoder_mlp else predictions
predictions = predictions.mean(axis=1) if self.combine_preds else predictions
prediction_cols = self.get_prediction_col_names(predictions.shape)
dataf.loc[:, prediction_cols] = predictions
del model; gc.collect()
return NumerFrame(dataf)
def _load_model(self, *args, **kwargs):
""" Load arbitrary model from path using suffix to model mapping. """
return self.suffix_to_model_mapping[self.model_suffix](str(self.model_file_path), *args, **kwargs)
def __check_valid_suffix(self):
""" Detailed message if model is not supported in this class. """
try:
self.suffix_to_model_mapping[self.model_suffix]
except KeyError:
raise NotImplementedError(
f"Format '{self.model_suffix}' is not available. Available versions are {list(self.suffix_to_model_mapping.keys())}"
)
dataf = create_numerframe("test_assets/mini_numerai_version_2_data.parquet")
test_paths = ["test_assets/joblib_v2_example_model.joblib"]
for path in test_paths:
model = SingleModel(path, model_name="test")
print(model.predict(dataf).get_prediction_data.head(2))
model = SingleModel(test_paths[0], model_name="test")
model.suffix_to_model_mapping
```
### 1.2. WandbKerasModel
This model is for a specific case. Namely, if you are logging Keras model using [Weights & Biases](https://wandb.ai/site) and want to download the best model for a specific run. `WandbKerasModel` wraps `SingleModel` and only adds additional logic for downloading models from Weights & Biases.
To authenticate your W&B account you are given several options:
1. Run `wandb login` in terminal and follow instructions ([docs](https://docs.wandb.ai/ref/cli/wandb-login)).
2. Configure [global environment variable](https://docs.wandb.ai/guides/track/advanced/environment-variables) `"WANDB_API_KEY"`.
3. Run `wandb.init(project=PROJECT_NAME, entity=ENTITY_NAME)` and
pass API key from [https://wandb.ai/authorize](https://wandb.ai/authorize).
```
#export
@typechecked
class WandbKerasModel(SingleModel):
"""
Download best .h5 model from Weights & Biases (W&B) run in local directory and make predictions.
More info on W&B: https://wandb.ai/site
:param run_path: W&B path structured as entity/project/run_id.
Can be copied from the Overview tab of a W&B run.
For more info: https://docs.wandb.ai/ref/app/pages/run-page#overview-tab \n
:param file_name: Name of .h5 file as saved in W&B run.
'model-best.h5' by default.
File name can be found under files tab of W&B run. \n
:param combine_preds: Whether to average predictions along column axis. Convenient when you want to predict the main target by averaging a multi-target model. \n
:param autoencoder_mlp: Whether your model is an autoencoder + MLP model.
Will take the 3rd of tuple output in this case. Only relevant for NN models. \n
More info on autoencoders:
https://forum.numer.ai/t/autoencoder-and-multitask-mlp-on-new-dataset-from-kaggle-jane-street/4338 \n
:param replace: Replace any model files saved under the same file name with downloaded W&B run model. WARNING: Setting to True may overwrite models in your local environment. \n
:param feature_cols: optional list of features to use for prediction. Selects all feature columns (i.e. column names with prefix 'feature') by default.
"""
def __init__(self,
run_path: str,
file_name: str = "model-best.h5",
combine_preds = False,
autoencoder_mlp = False,
replace = False,
feature_cols: list = None
):
self.run_path = run_path
self.file_name = file_name
self.replace = replace
self._download_model()
super().__init__(model_file_path=f"{self.run_path.split('/')[-1]}_{self.file_name}",
model_name=self.run_path,
combine_preds=combine_preds,
autoencoder_mlp=autoencoder_mlp,
feature_cols=feature_cols
)
def _download_model(self):
"""
Use W&B API to download .h5 model file.
More info on API: https://docs.wandb.ai/guides/track/public-api-guide
"""
if Path(self.file_name).is_file() and not self.replace:
rich_print(f":warning: [red] Model file '{self.file_name}' already exists in local environment.\
Skipping download of W&B run model. If this is not the model you want to use for prediction\
consider moving it or set 'replace=True' at initialization to overwrite. [/red] :warning:")
else:
rich_print(f":page_facing_up: [green] Downloading '{self.file_name}' from '{self.run_path}' in W&B Cloud. [/green] :page_facing_up:")
run = wandb.Api().run(self.run_path)
run.file(name=self.file_name).download(replace=self.replace)
os.rename(self.file_name, f"{self.run_path.split('/')[-1]}_{self.file_name}")
# hide
# run_path = "user123/project/abcd1234"
# model = WandbKerasModel(run_path=run_path)
```
### 1.3. CSVSub
This model is a wrapper for if you want to add predictions from external CSVs in a directory.
```
#export
@typechecked
class ExternalCSVs(BaseModel):
"""
Load external submissions and add to NumerFrame. \n
All csv files in this directory will be added to NumerFrame.
Make sure all external predictions are prepared and ready for submission. i.e. IDs lining up and one column named 'prediction'. \n
:param data_directory: Directory path for retrieving external submission.
"""
def __init__(self, data_directory: str = "external_submissions"):
super().__init__(model_directory=data_directory)
self.data_directory = Path(data_directory)
self.paths = list(self.data_directory.glob("*.csv"))
if not self.paths:
rich_print(f":warning: WARNING: No csvs found in directory '{self.data_directory}'. :warning:")
def predict(self, dataf: NumerFrame) -> NumerFrame:
""" Return NumerFrame with added external predictions. """
for path in tqdm(self.paths, desc="External submissions"):
dataf.loc[:, f"prediction_{path.name}"] = self._get_preds(path)
return NumerFrame(dataf)
def _get_preds(self, path: Path) -> pd.Series:
pred_col = pd.read_csv(path, index_col=0, header=0)['prediction']
if not pred_col.between(0, 1).all():
raise ValueError(f"Prediction values must be between 0 and 1. Does not hold for '{path.name}'.")
return pred_col
```
For testing, the `external_submissions` directory contains `test_predictions.csv` with values from feature `target_thomas_20`.
```
dataf = create_numerframe("test_assets/mini_numerai_version_2_data.parquet")
external = ExternalCSVs(data_directory="test_assets/external_submissions")
new_dataf = external.predict(dataf)
new_dataf.get_prediction_data.head(2)
# hide
assert new_dataf['prediction_test_predictions.csv'].astype(np.float32).equals(new_dataf['target_thomas_20'])
```
If no submissions are found in the given `data_directory` you should recieve a warning.
```
ExternalCSVs(data_directory="Some_nonexisting_directory_12354321");
```
### 1.4. NumerBay
This model is a wrapper for if you want to add predictions from NumerBay purchases.
Currently only Numerai Classic submissions are supported. Numerai Signals will be supported in a future version.
```
#export
@typechecked
class NumerBayCSVs(BaseModel):
"""
Load NumerBay submissions and add to NumerFrame. \n
Make sure to provide correct NumerBay credentials and that your purchases have been confirmed and artifacts are available for download. \n
:param data_directory: Directory path for caching submission. Files not already present in the directory will be downloaded from NumerBay.
:param numerbay_product_full_names: List of product full names (in the format of [category]-[product name]) to download from NumerBay. E.g. ['numerai-predictions-numerbay']
:param numerbay_username: NumerBay username
:param numerbay_password: NumerBay password
:param numerbay_key_path: NumerBay encryption key json file path (exported from the profile page)
"""
def __init__(self,
data_directory: str = "numerbay_submissions",
numerbay_product_full_names: list = None,
numerbay_username: str = None,
numerbay_password: str = None,
numerbay_key_path: str = None,
ticker_col: str = 'bloomberg_ticker'):
super().__init__(model_directory=data_directory)
self.data_directory = Path(data_directory)
self.numerbay_product_full_names = numerbay_product_full_names
self.numerbay_key_path = numerbay_key_path
self._api = None
self._get_api_func = lambda: NumerBay(username=numerbay_username, password=numerbay_password)
self.ticker_col = ticker_col
self.classic_number = 8
self.signals_number = 11
def predict(self, dataf: NumerFrame) -> NumerFrame:
""" Return NumerFrame with added NumerBay predictions. """
for numerbay_product_full_name in tqdm(self.numerbay_product_full_names, desc="NumerBay submissions"):
pred_name = f"prediction_{numerbay_product_full_name}"
if dataf.meta.era_col == "era":
dataf.loc[:, pred_name] = \
self._get_preds(numerbay_product_full_name, tournament=self.classic_number)
else:
dataf.loc[:, pred_name] = \
dataf.merge(self._get_preds(numerbay_product_full_name, tournament=self.signals_number),
on=[self.ticker_col, dataf.meta.era_col], how='left')['signal']
return NumerFrame(dataf)
@property
def api(self):
if self._api is None:
self._api = self._get_api_func()
return self._api
def _get_preds(self, numerbay_product_full_name: str, tournament: int) -> pd.Series:
if tournament == self.signals_number: # Temporarily disable Signals
raise NotImplementedError("NumerBay Signals predictions not yet supported.")
# Scan for already downloaded files, allows arbitrary ext just in case (e.g. csv.zip)
file_paths = list(self.data_directory.glob(f"{numerbay_product_full_name}.*"))
if len(file_paths) > 0:
file_path = file_paths[0]
else:
file_path = Path.joinpath(self.data_directory, f"{numerbay_product_full_name}.csv")
# Download file if needed
if not file_path.is_file():
# Download to a tmp file
tmp_path = Path.joinpath(self.data_directory, f".{numerbay_product_full_name}.tmp")
self.api.download_artifact(
dest_path=str(tmp_path),
product_full_name=numerbay_product_full_name,
key_path=self.numerbay_key_path
)
# Rename file after successful download (and decryption)
os.rename(tmp_path, file_path)
# Read downloaded file
if file_path.is_file():
if tournament == self.classic_number:
pred_col = pd.read_csv(file_path, index_col=0, header=0)['prediction']
elif tournament == self.signals_number:
pass
else:
raise ValueError(f"Invalid tournament '{tournament}'.")
else:
raise FileNotFoundError(f"No file found in directory '{self.data_directory}' for NumerBay product "
f"'{numerbay_product_full_name}'.")
# validity check
if not pred_col.between(0, 1).all():
raise ValueError(f"Prediction values must be between 0 and 1. Does not hold for '{path.name}'.")
return pred_col
```
Example usage
```
# nb_model = NumerBayCSVs(data_directory='/app/notebooks/tmp',
# numerbay_product_full_names=['numerai-predictions-someproduct'],
# numerbay_username="myusername",
# numerbay_password="mypassword",
# numerbay_key_path="/app/notebooks/tmp/numerbay.json")
# preds = nb_model.predict(dataf)
```
## 2. Loading all models in directory
### 2.1. Joblib directory
Many models, like `scikit-learn`, can conveniently be saved as `.joblib` files. This class automatically loads all `.joblib` files in a given folder and generates (averaged out) predictions.
```
#export
@typechecked
class JoblibModel(DirectoryModel):
"""
Load and predict for arbitrary models in directory saved as .joblib.
All loaded models should have a .predict method and accept the features present in the data.
:param model_directory: Main directory from which to read in models. \n
:param model_name: Name that will be used to create column names and for display purposes. \n
:param feature_cols: optional list of features to use for prediction. Selects all feature columns (i.e. column names with prefix 'feature') by default.
"""
def __init__(self,
model_directory: str,
model_name: str = None,
feature_cols: list = None
):
file_suffix = 'joblib'
super().__init__(model_directory=model_directory,
file_suffix=file_suffix,
model_name=model_name,
feature_cols=feature_cols
)
def load_models(self) -> list:
return [joblib.load(path) for path in self.model_paths]
dataf = create_numerframe("test_assets/mini_numerai_version_2_data.parquet", metadata={"version": 2})
model = JoblibModel("test_assets", model_name="Joblib_LGB")
predictions = model.predict(dataf).get_prediction_data
assert predictions['prediction_Joblib_LGB'].between(0, 1).all()
predictions.head(2)
```
### 2.2. Catboost directory (.cbm)
This model setup loads all `CatBoost` (`.cbm`) models present in a given directory and makes (averaged out) predictions.
```
#export
@typechecked
class CatBoostModel(DirectoryModel):
"""
Load and predict with all .cbm models (CatBoostRegressor) in directory.
:param model_directory: Main directory from which to read in models. \n
:param model_name: Name that will be used to define column names and for display purposes. \n
:param feature_cols: optional list of features to use for prediction. Selects all feature columns (i.e. column names with prefix 'feature') by default.
"""
def __init__(self,
model_directory: str,
model_name: str = None,
feature_cols: list = None
):
file_suffix = 'cbm'
super().__init__(model_directory=model_directory,
file_suffix=file_suffix,
model_name=model_name,
feature_cols=feature_cols
)
def load_models(self) -> list:
return [CatBoost().load_model(path) for path in self.model_paths]
# Example on NumerFrame
from numerblox.preprocessing import GroupStatsPreProcessor
dataf = create_numerframe("test_assets/mini_numerai_version_1_data.csv", {"version": 1})
processed_dataf = GroupStatsPreProcessor()(dataf)
model = CatBoostModel("test_assets", model_name="CB")
predictions = model.predict(processed_dataf).get_prediction_data
assert predictions['prediction_CB'].between(0, 1).all()
predictions.head(2)
```
### 2.3. LightGBM directory (.lgb)
This model setup loads all `LightGBM` (`.lgb`) models present in a given directory and makes (averaged out) predictions.
```
#export
@typechecked
class LGBMModel(DirectoryModel):
"""
Load and predict with all .lgb models (LightGBM) in directory.
:param model_directory: Main directory from which to read in models. \n
:param model_name: Name that will be used to define column names and for display purposes. \n
:param feature_cols: optional list of features to use for prediction. Selects all feature columns (i.e. column names with prefix 'feature') by default.
"""
def __init__(self,
model_directory: str,
model_name: str = None,
feature_cols: list = None
):
file_suffix = 'lgb'
super().__init__(model_directory=model_directory,
file_suffix=file_suffix,
model_name=model_name,
feature_cols=feature_cols
)
def load_models(self) -> list:
return [lgb.Booster(model_file=str(path)) for path in self.model_paths]
dataf = create_numerframe("test_assets/mini_numerai_version_2_data.parquet")
model = LGBMModel("test_assets", model_name="LGB")
predictions = model.predict(dataf).get_prediction_data
assert predictions['prediction_LGB'].between(0, 1).all()
predictions.head(2)
```
## 3. Baseline models
Setting a baseline is always an important step for data science problems. This section introduces models that should only be used a baselines.
### 3.1. ConstantModel
This model simply outputs a constant of your choice. Convenient for setting classification baselines.
```
#export
class ConstantModel(BaseModel):
"""
WARNING: Only use this Model for testing purposes. \n
Create constant prediction.
:param constant: Value for constant prediction. \n
:param model_name: Name that will be used to create column names and for display purposes.
"""
def __init__(self, constant: float = 0.5, model_name: str = None):
self.constant = constant
model_name = model_name if model_name else f"constant_{self.constant}"
super().__init__(model_directory="",
model_name=model_name
)
self.clf = DummyRegressor(strategy='constant', constant=constant).fit([0.], [0.])
def predict(self, dataf: NumerFrame) -> NumerFrame:
dataf.loc[:, self.prediction_col_name] = self.clf.predict(dataf.get_feature_data)
return NumerFrame(dataf)
constant = 0.85
dataf = create_numerframe("test_assets/mini_numerai_version_1_data.csv")
constant_model = ConstantModel(constant=constant)
predictions = constant_model.predict(dataf).get_prediction_data
assert (predictions.to_numpy() == constant).all()
predictions.head(2)
```
### 3.2. RandomModel
This model returns uniformly distributed predictions in range $[0...1)$. Solid naive baseline for regression models.
```
#export
class RandomModel(BaseModel):
"""
WARNING: Only use this Model for testing purposes. \n
Create uniformly distributed predictions.
:param model_name: Name that will be used to create column names and for display purposes.
"""
def __init__(self, model_name: str = None):
model_name = model_name if model_name else "random"
super().__init__(model_directory="",
model_name=model_name
)
def predict(self, dataf: Union[pd.DataFrame, NumerFrame]) -> NumerFrame:
dataf.loc[:, self.prediction_col_name] = np.random.uniform(size=len(dataf))
return NumerFrame(dataf)
dataf = create_numerframe("test_assets/mini_numerai_version_1_data.csv")
random_model = RandomModel()
predictions = random_model.predict(dataf).get_prediction_data
assert predictions['prediction_random'].between(0, 1).all()
predictions.head(2)
```
### 3.3. Example (validation) predictions
This Model performs downloading and adding of example predictions for Numerai Classic. Convenient when you are constructing a `ModelPipeline` and want to include example predictions.
```
#export
@typechecked
class ExamplePredictionsModel(BaseModel):
"""
Load example predictions and add to NumerFrame. \n
:param file_name: File to download from NumerAPI.
'example_validation_predictions.parquet' by default. \n
:param data_directory: Directory path to download example predictions to or directory where example data already exists. \n
:param round_num: Optional round number. Downloads most recent round by default.
"""
def __init__(self, file_name: str = "example_validation_predictions.parquet",
data_directory: str = "example_predictions_model",
round_num: int = None):
super().__init__(model_directory="",
model_name="example",
)
self.file_name = file_name
self.data_directory = data_directory
self.round_num = round_num
@display_processor_info
def predict(self, dataf: NumerFrame) -> NumerFrame:
""" Return NumerFrame with added example predictions. """
self._download_example_preds()
example_preds = self._load_example_preds()
dataf.loc[:, self.prediction_col_name] = dataf.merge(example_preds, on='id', how='left')['prediction']
self.downloader.remove_base_directory()
return NumerFrame(dataf)
def _download_example_preds(self):
self.downloader = NumeraiClassicDownloader(directory_path=self.data_directory)
self.dest_path = f"{str(self.downloader.dir)}/{self.file_name}"
self.downloader.download_single_dataset(filename=self.file_name,
dest_path=self.dest_path,
round_num=self.round_num)
def _load_example_preds(self, *args, **kwargs):
return pd.read_parquet(self.dest_path, *args, **kwargs)
# hide_output
# slow
# Download validation data
downloader = NumeraiClassicDownloader("example_predictions_model")
val_file = "numerai_validation_data.parquet"
val_save_path = f"{str(downloader.dir)}/{val_file}"
downloader.download_single_dataset(filename=val_file,
dest_path=val_save_path)
# Load validation data and add example predictions
dataf = create_numerframe(val_save_path)
example_model = ExamplePredictionsModel()
predictions = example_model.predict(dataf).get_prediction_data
assert predictions['prediction_example'].between(0, 1).all()
predictions.head(2)
```
## 4. Custom Model
There are two different ways to implement new models. Both have their own conveniences and use cases.
**4.1.** Inherit from `BaseModel` (custom prediction logic).
**4.2.** Inherit from `DirectoryModel` (make predictions for all models in directory with given file suffix. Prediction logic will already be implemented. Only implement model loading logic).
**4.1. (From BaseModel)** works well when you have no or only a single file that you use for generating predictions.
Examples:
1. Loading a model is not relevant or your model is already loaded in memory.
2. You would like predictions for one model loaded from disk.
3. The object you are loading already aggregates multiple models and transformation steps (such as [scikit-learn FeatureUnion](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.html)).
**4.2. (From DirectoryModel)** is convenient when you have a lot of similar models in a directory and want to generate predictions for all of them.
Examples:
1. You have multiple similar models saved through a cross validation process.
2. You have a bagging strategy where a lot of models trained on slightly different data or with different initializations should are averaged.
### 4.1. From BaseModel
Arbitrary models can be instantiated and used for prediction generation by inheriting from `BaseModel`. Arbitrary logic (model loading, prediction, etc.) can be defined in `.predict` as long as the method takes a `NumerFrame` as input and outputs a `NumerFrame`.
The model should be able to typecheck by adding the `@typeguard.typechecked` decorator at the top of the class.
For clear console output we recommend adding the `@display_processor_info` decorator to the `.predict` method.
If your model does not involve reading files from disk specify `model_directory=""`.
```
#export
@typechecked
class AwesomeModel(BaseModel):
"""
TEMPLATE - Predict with arbitrary prediction logic and model formats.
:param model_directory: Main directory from which to read in models. \n
:param model_name: Name that will be used to define column names and for display purposes. \n
:param feature_cols: optional list of features to use for prediction. Selects all feature columns (i.e. column names with prefix 'feature') by default.
"""
def __init__(self, model_directory: str, model_name: str = None,
feature_cols: list = None):
super().__init__(model_directory=model_directory,
model_name=model_name,
)
self.feature_cols = feature_cols
@display_processor_info
def predict(self, dataf: NumerFrame) -> NumerFrame:
""" Return NumerFrame with column(s) added for prediction(s). """
# Get all features
feature_cols = self.feature_cols if self.feature_cols else dataf.feature_cols
feature_df = dataf[feature_cols]
# Predict and add to new column
...
# Parse all contents of NumerFrame to the next pipeline step
return NumerFrame(dataf)
```
### 4.2. From DirectoryModel
You may want to implement a setup similar to `JoblibModel` and `CatBoostModel`. Namely, load in all models of a certain type from a directory, predict for all and take the average. If this is your use case, inherit from `DirectoryModel` and be sure to implement the `.load_models` method.
For a `DirectoryModel` you should specify a `file_suffix` (like `.joblib` or `.cbm`) which will be used to store all available models in `self.model_paths`.
The `.predict` method will in this case already be implemented, but can be overridden if the prediction logic is more complex. For example, if you want to apply weighted averaging or a geometric mean for models within a given directory.
Like with inheriting from `BaseModel`, This Model should also be able to typecheck by adding the `@typeguard.typechecked` decorator at the top of the class.
```
#export
@typechecked
class AwesomeDirectoryModel(DirectoryModel):
"""
TEMPLATE - Load in all models of arbitrary file format and predict for all.
:param model_directory: Main directory from which to read in models. \n
:param model_name: Name that will be used to define column names and for display purposes. \n
:param feature_cols: optional list of features to use for prediction. Selects all feature columns (i.e. column names with prefix 'feature') by default.
"""
def __init__(self,
model_directory: str,
model_name: str = None,
feature_cols: list = None
):
file_suffix = '.anything'
super().__init__(model_directory=model_directory,
file_suffix=file_suffix,
model_name=model_name,
feature_cols=feature_cols
)
def load_models(self) -> list:
""" Instantiate all models and return as a list. (abstract method) """
...
```
----------------------------------------------
```
# hide
# Run this cell to sync all changes with library
from nbdev.export import notebook2script
notebook2script()
```
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License");
```
#@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.
```
# Get Started with TensorFlow
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/alpha/tutorials/quickstart/advanced"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/tutorials/quickstart/advanced.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/quickstart/advanced.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
This is a [Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb) notebook file. Python programs are run directly in the browser—a great way to learn and use TensorFlow. To run the Colab notebook:
1. Connect to a Python runtime: At the top-right of the menu bar, select *CONNECT*.
2. Run all the notebook code cells: Select *Runtime* > *Run all*.
For more examples and guides, see the [TensorFlow tutorials](https://www.tensorflow.org/alpha/tutorials/).
To get started, import the TensorFlow library into your program:
```
from __future__ import absolute_import, division, print_function
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow_datasets as tfds
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
```
Load and prepare the [MNIST dataset](http://yann.lecun.com/exdb/mnist/). Convert the samples from integers to floating-point numbers:
```
dataset, info = tfds.load('mnist', with_info=True, as_supervised=True)
mnist_train, mnist_test = dataset['train'], dataset['test']
def convert_types(image, label):
image = tf.cast(image, tf.float32)
image /= 255
return image, label
mnist_train = mnist_train.map(convert_types).shuffle(10000).batch(32)
mnist_test = mnist_test.map(convert_types).batch(32)
```
Build the `tf.keras` model using the Keras [model subclassing API](https://www.tensorflow.org/guide/keras#model_subclassing):
```
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.conv1(x)
x = self.flatten(x)
x = self.d1(x)
return self.d2(x)
model = MyModel()
```
Choose an optimizer and loss function for training:
```
loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam()
```
Select metrics to measure the loss and the accuracy of the model. These metrics accumulate the values over epochs and then print the overall result.
```
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
```
Train the model using `tf.GradientTape`:
```
@tf.function
def train_step(image, label):
with tf.GradientTape() as tape:
predictions = model(image)
loss = loss_object(label, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss(loss)
train_accuracy(label, predictions)
```
Now test the model:
```
@tf.function
def test_step(image, label):
predictions = model(image)
t_loss = loss_object(label, predictions)
test_loss(t_loss)
test_accuracy(label, predictions)
EPOCHS = 5
for epoch in range(EPOCHS):
for image, label in mnist_train:
train_step(image, label)
for test_image, test_label in mnist_test:
test_step(test_image, test_label)
template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
print (template.format(epoch+1,
train_loss.result(),
train_accuracy.result()*100,
test_loss.result(),
test_accuracy.result()*100))
```
The image classifier is now trained to ~98% accuracy on this dataset. To learn more, read the [TensorFlow tutorials](https://www.tensorflow.org/alpha/tutorials/).
| github_jupyter |
```
from __future__ import division, print_function, unicode_literals
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from utils.metrics import threshold_at_completeness_of, threshold_at_purity_of
from utils.bootstrap import (
kde_purity,
kde_completeness,
get_stellar_fraction,
confidence_band,
get_log_density
)
plt.rc('legend', fontsize=10)
df = pd.read_csv("sdss_test.csv")
mag_r = df["dered_r"].values
morph_true, morph_pred = np.loadtxt('sdss_tpc.2.mlz', unpack=True, usecols=(0, 2))
morph_true = 1.0 - morph_true # make galaxy=0 and star=1
morph_pred = 1.0 - morph_pred # make galaxy=0 and star=1
phot_true, phot_pred = np.loadtxt('sdss_tpc.3.mlz', unpack=True, usecols=(0, 2))
phot_true = 1.0 - phot_true # make galaxy=0 and star=1
phot_pred = 1.0 - phot_pred # make galaxy=0 and star=1
cnn_true = np.load("sdss_test_labels.npy")
cnn_pred = np.load("sdss_convnet_pred.npy")
cnn_pred = 1.0 - cnn_pred # make galaxy=0 and star=1
cnn_true = (1.0 - cnn_true) / 2 # make galaxy=0 and star=1
assert cnn_true.min() == 0
assert cnn_true.max() == 1
assert phot_true.sum() == cnn_true.sum()
assert morph_true.sum() == cnn_true.sum()
mask = ((mag_r > -90) & (mag_r < 90))
mag_r, cnn_true, cnn_pred, phot_pred, morph_pred = map(
lambda x: x[mask],
[mag_r, cnn_true, cnn_pred, phot_pred, morph_pred]
)
bins = np.arange(13.5, 23.5, 0.1)
stars_frac_med, stars_frac_lower, stars_frac_upper = confidence_band(
get_stellar_fraction, 1 - cnn_true, 1 - cnn_true, mag_r, bins=bins, n_boots=100)
cnn_cut = threshold_at_completeness_of(cnn_true, cnn_pred, 0.96)
cnn_g_med, cnn_g_lower, cnn_g_upper = confidence_band(
kde_purity, cnn_true, cnn_pred, mag_r, bins=bins, p_cut=cnn_cut, n_boots=1000)
phot_p_cut = threshold_at_completeness_of(phot_true, phot_pred, 0.96)
phot_g_med, phot_g_lower, phot_g_upper = confidence_band(
kde_purity, phot_true, phot_pred, mag_r, bins=bins, p_cut=phot_p_cut, n_boots=1000)
morph_p_cut = threshold_at_completeness_of(morph_true, morph_pred, 0.96)
morph_g_med, morph_g_lower, morph_g_upper = confidence_band(
kde_purity, morph_true, morph_pred, mag_r, bins=bins, p_cut=morph_p_cut, n_boots=1000)
cnn_p_cut = threshold_at_purity_of(1 - cnn_true, 1 - cnn_pred, 0.97)
cnn_s_med, cnn_s_lower, cnn_s_upper = confidence_band(
kde_completeness, 1 - cnn_true, 1 - cnn_pred, mag_r, bins=bins, p_cut=cnn_p_cut, n_boots=10000)
phot_p_cut = threshold_at_purity_of(1 - phot_true, 1 - phot_pred, 0.97)
phot_s_med, phot_s_lower, phot_s_upper = confidence_band(
kde_completeness, 1 - phot_true, 1 - phot_pred, mag_r, bins=bins, p_cut=phot_p_cut, n_boots=10000)
morph_p_cut = threshold_at_purity_of(1 - morph_true, 1 - morph_pred, 0.97)
morph_s_med, morph_s_lower, morph_s_upper = confidence_band(
kde_completeness, 1 - morph_true, 1 - morph_pred, mag_r, bins=bins, p_cut=morph_p_cut, n_boots=10000)
alpha = 0.2
p = sns.color_palette()
sns.set_style("ticks")
fig = plt.figure(figsize=(6, 8))
ax0 = plt.subplot2grid((6, 8), (0, 0), colspan=8)
ax1 = plt.subplot2grid((6, 8), (1, 0), colspan=8)
ax2 = plt.subplot2grid((6, 8), (2, 0), colspan=8, rowspan=2)
ax3 = plt.subplot2grid((6, 8), (4, 0), colspan=8, rowspan=2)
plt.setp(ax0.get_xticklabels(), visible=False)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.setp(ax2.get_xticklabels(), visible=False)
ax0.hist(mag_r, bins=bins, histtype='bar', color=p[1], alpha=alpha)
log_dens_mag_r = get_log_density(mag_r, bins=bins)
ax0.plot(bins, len(mag_r) * np.exp(log_dens_mag_r) / np.exp(log_dens_mag_r).sum(), color=p[1])
ax0.set_xlim(13.5, 22.5)
ax0.set_yticks([0, 200, 400, 600])
ax0.set_ylabel('$N$')
ax1.plot(bins, stars_frac_med, color=p[3])
ax1.set_xlim(13.5, 22.5)
ax1.set_ylim(0, 0.75)
ax1.set_yticks([0, 0.2, 0.4, 0.6])
ax1.set_ylabel('stellar fraction')
ax1.legend(loc='upper right')
ax2.plot(bins, cnn_g_med, label='ConvNet', ls='-', color=p[2])
ax2.fill_between(bins, cnn_g_lower, cnn_g_upper, color=p[2], alpha=alpha)
ax2.plot(bins, morph_g_med, label='$\mathregular{TPC_{morph}}$', ls='--', color=p[0])
ax2.fill_between(bins, morph_g_lower, morph_g_upper, color=p[0], alpha=alpha)
ax2.plot(bins, phot_g_med, label='$\mathregular{TPC_{phot}}$', ls='--', color=p[4])
ax2.fill_between(bins, phot_g_lower, phot_g_upper, color=p[4], alpha=alpha)
ax2.legend(loc='lower center')
ax2.set_xlim(13.5, 22.5)
ax2.set_ylim(0.81, 1.04)
ax2.set_yticks([0.85, 0.9, 0.95, 1.0])
ax2.set_ylabel(r'$p_g\left(c_g=0.96\right)$', fontsize=12)
ax3.plot(bins, cnn_s_med, label='ConvNet', ls='-', color=p[2])
ax3.fill_between(bins, cnn_s_lower, cnn_s_upper, color=p[2], alpha=alpha)
ax3.plot(bins, phot_s_med, label='TPC', ls='--', color=p[4])
ax3.fill_between(bins, phot_s_lower, phot_s_upper, color=p[4], alpha=alpha)
ax3.plot(bins, morph_s_med, label='TPC', ls='--', color=p[0])
ax3.fill_between(bins, morph_s_lower, morph_s_upper, color=p[0], alpha=alpha)
ax3.set_ylabel(r'$c_s\left(p_s=0.97\right)$', fontsize=12)
ax3.set_xlim(13.5, 22.5)
ax3.set_ylim(0.49, 1.05)
#ax3.set_yticks([0.96, 1.0])
ax3.set_xlabel(r'$r$ (mag)')
plt.subplots_adjust(hspace=0)
plt.savefig('figures/sdss_mag.pdf', bbox_inches='tight')
plt.show()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/TheGupta2012/qctrl-qhack-Hostages-of-the-Entangled-Dungeons/blob/master/Robust_control_x_gate.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
**Creating Robust Control for Single qubit gates**
Here we introduce the essential concepts behind robust control. We create a model of noise on a quantum computer and simulate its performance. Then we show how to create controls that are robust to this noise process. We demonstrate the control's robustness with a simulation.
## Imports and initialization
```
import matplotlib.pyplot as plt
import numpy as np
import qctrlvisualizer as qv
from attr import asdict
from qctrl import Qctrl
# Starting a session with the API
qctrl = Qctrl(email = 'harshit.co19@nsut.ac.in', password = 'HARSHITcontrol')
# Define standard matrices
identity = np.array([[1.0, 0.0], [0.0, 1.0]], dtype=np.complex)
sigma_x = np.array([[0.0, 1.0], [1.0, 0.0]], dtype=np.complex)
sigma_y = np.array([[0.0, -1j], [1j, 0.0]], dtype=np.complex)
sigma_z = np.array([[1.0, 0.0], [0.0, -1.0]], dtype=np.complex)
sigma_m = np.array([[0.0, 1.0], [0.0, 0.0]], dtype=np.complex)
sigmas = [sigma_x, sigma_y, sigma_z]
sigma_names = ["X", "Y", "Z"]
not_gate = np.array([[0.0, -1.0], [1.0, 0.0]])
# Plotting and formatting methods
plt.style.use(qv.get_qctrl_style())
def plot_simulation_trajectories(figure, times, coherent_samples, noisy_trajectories):
ideal_bloch_sphere_coords = np.array(
[
[
np.real(
np.dot(
sample.state_vector.conj(),
np.matmul(sigma, sample.state_vector),
)
)
for sigma in sigmas
]
for sample in coherent_samples
]
)
noisy_bloch_sphere_coords = np.array(
[
[
[
np.real(
np.dot(
sample.state_vector.conj(),
np.matmul(sigma, sample.state_vector),
)
)
for sigma in sigmas
]
for sample in trajectory.samples
]
for trajectory in noisy_trajectories
]
)
figure.set_figheight(6.0)
figure.set_figwidth(7.0)
axes = figure.subplots(nrows=3, ncols=1, sharex=True, sharey=False, squeeze=False)[
:, 0
]
for a in range(3):
axes[a].set_ylabel(sigma_names[a])
axes[a].set_ylim([-1.1, 1.1])
for t in range(noisy_bloch_sphere_coords.shape[0]):
axes[a].plot(
times * 1e6,
noisy_bloch_sphere_coords[t, :, a],
"--",
color="#680CE9",
alpha=0.25,
)
axes[a].plot(times * 1e6, ideal_bloch_sphere_coords[:, a], "-", color="#680CE9")
axes[2].set_xlabel("Time ($\mu$s)")
axes[0].set_title("Bloch sphere coordinates")
def plot_simulation_noise_directions(figure, times, coherent_samples):
figure.set_figheight(6.0)
figure.set_figwidth(7.0)
noise_operator_directions = np.array(
[
[
0.5
* np.real(
np.trace(
np.matmul(
sigma,
np.matmul(
sample.evolution_operator.conj().T,
np.matmul(sigma_z, sample.evolution_operator),
),
)
)
)
for sigma in sigmas
]
for sample in coherent_samples
]
)
axes = figure.subplots(nrows=3, ncols=1, sharex=True, sharey=False, squeeze=False)[
:, 0
]
for a in range(3):
axes[a].set_ylabel(sigma_names[a])
axes[a].set_ylim([-1.1, 1.1])
axes[a].plot(
robust_point_times * 1e6,
noise_operator_directions[:, a],
"-",
color="#680CE9",
)
axes[a].fill_between(
robust_point_times * 1e6,
0,
noise_operator_directions[:, a],
color="#680CE9",
alpha=0.25,
)
axes[2].set_xlabel("Time ($\mu$s)")
axes[0].set_title("Bloch sphere directions")
def plot_noise_spectral_density(figure, nsd_samples):
frequencies = np.array([sample["frequency"] for sample in nsd_samples])
powers = np.array([sample["power"] for sample in nsd_samples])
axes = figure.subplots(nrows=1, ncols=1, sharex=True, sharey=False, squeeze=False)[
0, 0
]
axes.plot(frequencies / 1e6, powers * 1e6)
axes.fill_between(frequencies / 1e6, 0, powers * 1e6, alpha=0.25)
axes.set_xlabel("Frequency (MHz)")
axes.set_ylabel("Power density (1/MHz)")
axes.set_title("Dephasing noise spectral density")
def pm_format(average, std):
return "{:.4f}".format(average) + "+/-" + "{:.4f}".format(std)
# The main signal which is sent to the qubit in the cloud
def bandwidth_limited_pwc_signal(
name, duration, segment_count, max_rabi_rate, cutoff_frequency
):
# create a raw pwc_signal where the amplitude of each segment is an optimization variables
raw_signal = qctrl.operations.pwc_signal(
values=qctrl.operations.bounded_optimization_variable(
count=segment_count, lower_bound=-max_rabi_rate, upper_bound=max_rabi_rate
),
duration=duration,
)
# pass the signal through a bandwidth limited filter
filtered_signal = qctrl.operations.convolve_pwc(
raw_signal, qctrl.operations.sinc_integral_function(cutoff_frequency)
)
# resample the smooth filtered signal as a pwc_signal
final_signal = qctrl.operations.discretize_stf(
stf=filtered_signal,
duration=robust_duration,
segments_count=segment_count,
name=name,
)
return final_signal
```
## Single qubit with dephasing noise
To better understand how noise affects a quantum computer we are going to create a simulation.
To start we write down a Hamiltonian, which will mathematically describe this physical system:
\begin{align*}
H_{\rm total}(t) = & H_{\rm control}(t) + H_{\rm noise}(t).
\end{align*}
### Control: Standard microwave pulse that creates a NOT Gate
The control part of the Hamiltonian is:
\begin{align}
H_{\rm control}(t) = \Omega_{\rm I}(t) \sigma_{x}/2 + \Omega_{\rm Q}(t) \sigma_{y}/2.
\end{align}
Where $\Omega_I(t)$ and $\Omega_Q(t)$ are the time-dependent Rabi rate created by the IQ modulated microwave pulse applied to control the qubits state, which couples to the qubit state through the $\sigma_k$ operators.
We are trying to apply a NOT gate to the qubit. The simplest way to do this is to apply a Q modulated microwave pulse at the maximum Rabi rate $\Omega_{\rm Q}(t) = \Omega_{\rm max}$ for a duration of $\pi/\Omega_{\rm max}$, while the I modulated microwave pulse is set to zero $\Omega_{\rm I}(t) = 0$. We will call this the standard NOT gate.
```
omega_max = 2 * np.pi * 1e6 # Hz
standard_duration = np.pi / omega_max # s
standard_pulse_segments = [
qctrl.types.ComplexSegmentInput(duration=standard_duration, value=omega_max),
]
plot_segments = {
"$\Omega_Q$": [
{"duration": segment.duration, "value": segment.value}
for segment in standard_pulse_segments
]
}
qv.plot_controls(plt.figure(), plot_segments)
plt.show()
```
### Noise: Magnetic field with a 1/f spectrum
The noise part of the Hamiltonian is:
\begin{align}
H_{\rm noise}(t) = \eta(t) \sigma_z / 2.
\end{align}
We treat the noisy magnetic field environment as a classical noise process $\eta(t)$ coupled to the quantum system with a noise operator $\sigma_z$. This approximate model is often reasonable for real quantum computing hardware when the decoherence time (T2) is the limiting factor, being much shorter than the relaxation time (T1) of the qubits.
The noise process $\eta(t)$ is sampled from a noise spectral density that follows a power law:
\begin{align}
S_{\eta}(\omega) = \frac{\omega_{\rm cutoff}^{a-1}}{\omega^a + \omega_{\rm cutoff}^a},
\end{align}
Where $\omega_{\rm cutoff}$ is the cutoff frequency and $a$ is the order of the power law. It is common for magnetic field environments to follow 1/f power law ($a=1$) where low frequency noise dominates.
Different physical processes will couple to the quantum computer through different noise operators. The key to getting a good simulation is to identify the noises that most significantly affect our qubits.
```
def power_spectrum(frequencies, frequency_cutoff, power):
return frequency_cutoff ** (power - 1) / (
frequencies ** power + frequency_cutoff ** power
)
frequencies = np.linspace(0, 2.0e4, 1000)
power_densities = 4e10 * power_spectrum(frequencies, 1.0e2, 1.0)
nsd_sampled_points = [
{"frequency": f, "power": p, "power_uncertainty": 0.0, "weight": 0.0}
for f, p in zip(frequencies, power_densities)
]
plot_noise_spectral_density(plt.figure(), nsd_sampled_points)
```
## Simulation of standard NOT Gate
Now that we have a Hamiltonian we can create a simulation. The control we have is a `shift` with $\sigma_x$ as the `operator` and $\Omega(t)$ is the `pulse`. The noise we have is an `additive noise` with $\sigma_z$ as the `operator` and $S_\eta(\omega)$ is the `linear_piecewise_noise_spectral_density`.
```
standard_control = qctrl.types.colored_noise_simulation.Shift(
control=standard_pulse_segments, operator=sigma_y / 2
)
noise_drift = qctrl.types.colored_noise_simulation.Drift(
operator=sigma_z / 2.0,
noise=qctrl.types.colored_noise_simulation.Noise(
power_densities=power_densities,
frequency_step=frequencies[1],
time_domain_sample_count=1000,
),
)
target = qctrl.types.TargetInput(operator=not_gate)
```
Now we can create a simulation of the qubit in a noisy environment.
*See also:* The [simulation user guide](https://docs.q-ctrl.com/boulder-opal/user-guides/simulation) explains how to create multiple types of simulations.
```
standard_point_times = np.linspace(0, standard_duration, 100)
standard_noisy_simulation_result = qctrl.functions.calculate_colored_noise_simulation(
duration=standard_duration,
sample_times=standard_point_times,
shifts=[standard_control],
drifts=[noise_drift],
trajectory_count=5,
initial_state_vector=np.array([1.0, 0.0]),
target=target,
)
```
For comparison we can also create a simulation of a system with no noise
```
standard_ideal_simulation_result = qctrl.functions.calculate_coherent_simulation(
duration=standard_duration,
sample_times=standard_point_times,
shifts=[standard_control],
initial_state_vector=np.array([1.0, 0.0]),
target=target,
)
```
### Noisy trajectories of the qubit state
We can display the noisy trajectories of the qubit using the coordinates of the [Bloch sphere](https://en.wikipedia.org/wiki/Bloch_sphere) as a representation of the state. We can see that the noisy trajectories, shown with dotted lines, take us away from the ideal simulation path, shown with the solid line. Most importantly, the final state of noisy trajectories diverges from the ideal final state. This indicates that the noise will introduce errors into our calculation and affect the outcomes of an algorithm that we want to run.
```
plot_simulation_trajectories(
plt.figure(),
standard_point_times,
standard_ideal_simulation_result.samples,
standard_noisy_simulation_result.trajectories,
)
plt.show()
```
### Average gate infidelity of standard NOT gate
The results above are specific to a particular initial state. We can quantify the *average* performance of the gate under noise by looking at the average gate infidelity, defined as:
\begin{align}
\mathcal{I}_{\rm gate} = 1 - \mathbb{E}[ \rm{Tr}[ U_{\rm target}^\dagger(T) U_{\rm total}(T) ] ],
\end{align}
where $U_{k}(T)$ is the solution to $\dot{U}_{k}(t) = -i H_{k} U_{k}(t)$, $U_{\rm target}$ is the target unitary, in this case a NOT gate, and $\mathbb{E}[ \cdot ]$ is the classical stochastic average. An estimate of this number is automatically calculated when you provide a target to a stochastic simulation in BOULDER OPAL.
```
standard_final_sample = standard_noisy_simulation_result.average_samples[-1]
print("Average gate infidelity:")
print(
pm_format(
standard_final_sample.average_infidelity,
standard_final_sample.average_infidelity_uncertainty,
)
)
print(standard_noisy_simulation_result.average_samples[-1])
```
## Robust control design
The filter function framework can be used to design robust controls. We treat the design problem as a multi-objective optimization problem. First we assume the control field is parametrized by a set of variables $\Omega_{\rm candidate}(\underline{v},t)$.
The first target of our optimization is to ensure that our optimized pulse performs the correct operation. To do this we need to minimize the infidelity of the control:
\begin{align}
\mathcal{I}_{\rm control} = \rm{Tr}[U_{\rm control}^\dagger(T) U_{\rm target}(T)],
\end{align}
This quantifies how close the control is to the target operation if there is no noise.
The second target of our optimization is to ensure that our optimized pulse is robust to the noise. It is common for physically relevant noise processes to be dominated by low frequency noise, in this case it simplifies the numerical calculation to minimize just the zero frequency part of the filter function. We call this the infidelity of the noise:
\begin{align}
\mathcal{I}_{\rm noise} = w^2 \left|\left| \int dt H_{\rm noise}^{\rm (control)}(t) \right|\right|_2^2,
\end{align}
where $w$ is a relative weight of the filter cost compared to the operation, a good value for additive noises is $w=1/T$.
The multi-objective optimization problem can be represented as minimizing the cost
\begin{align}
\mathcal{I}_{\rm robust}(\underline{v}) = \mathcal{I}_{\rm control}(\underline{v}) + \mathcal{I}_{\rm noise}(\underline{v}).
\end{align}
If we can find a control where $\mathcal{I}_{\rm robust}(\underline{v})$ is very close to zero, we can be sure that it will both complete the correct operation and be robust to low frequency noise.
### Optimizing a robust NOT gate
We can create a robust NOT gate using the BOULDER OPAL optimizer. The [optimization feature](https://docs.q-ctrl.com/boulder-opal/user-guides/optimization) allows the user to define an optimization with arbitrary pulse constraints.
We are going to construct two control pulses $\Omega_I(\underline{v},t)$ and $\Omega_Q(\underline{v},t)$ which have a maximum Rabi rate $\Omega_{\rm max}$ and a bandwidth limit defined by a cutoff frequency $\Omega_{\rm cutoff}$.
The optimizer requires that you define the quantum system as a `graph` that represents how a set of `optimization_variables` an `infidelity` you want to minimize. A series of convenience methods makes
creating this `graph` straightforward once you have mathematically written down the total Hamiltonian ($H_{\rm total}$). Below we show how to create a `graph` for optimizing a qubit with dephasing noise. On each line, we write down what the current variable represents in the mathematical equation of the total Hamiltonian.
We restate the entire Hamiltonian below so we can easily refer to it:
\begin{align}
H_{\rm total}(t) = & H_{\rm control}(t) + H_{\rm noise}(t), \\
H_{\rm control}(t) = & \Omega_{\rm I}(t) \sigma_{x}/2 + \Omega_{\rm Q}(t) \sigma_{y}/2, \\
H_{\rm noise}(t) = & \eta(t) \sigma_z / 2.
\end{align}
```
robust_duration = 3.0 * standard_duration
omega_cutoff = 1e7
segment_count = 100
with qctrl.create_graph() as graph:
# Omega_I(v,t)
pulse_i = bandwidth_limited_pwc_signal(
name="I",
duration=robust_duration,
segment_count=segment_count,
max_rabi_rate=omega_max,
cutoff_frequency=omega_cutoff,
)
# Omega_Q(v,t)
pulse_q = bandwidth_limited_pwc_signal(
name="Q",
duration=robust_duration,
segment_count=segment_count,
max_rabi_rate=omega_max,
cutoff_frequency=omega_cutoff,
)
# Omega_I(t) sigma_x/2
robust_control_i = qctrl.operations.pwc_operator(
signal=pulse_i, operator=sigma_x / 2.0
)
# Omega_Q(t) sigma_y/2
robust_control_q = qctrl.operations.pwc_operator(
signal=pulse_q, operator=sigma_y / 2.0
)
# H_control = Omega_I(t) sigma_x/2 + Omega_Q(t) sigma_y/2
control_hamiltonian = qctrl.operations.pwc_sum([robust_control_i, robust_control_q])
# sigma_z / 2w
noise_operator = qctrl.operations.constant_pwc_operator(
robust_duration, sigma_z / 2.0 / robust_duration
)
# create U_target
target_unitary = qctrl.operations.target(operator=not_gate)
# create I_robust(v) = I_control(v) + I_noise(v)
infidelity = qctrl.operations.infidelity_pwc(
hamiltonian=control_hamiltonian,
noise_operators=[
noise_operator,
],
target_operator=target_unitary,
name="infidelity",
)
```
When you run an optimization, a series of searches are performed and the pulse with the smallest cost is returned. The optimization is stochastic and therefore a different result will be returned each time, but they will always satisfy the constraints.
A pulse that is both robust and completes the correct operation will have a cost which is very close to zero. If the cost returned does not satisfy this condition, you may need to reduce your constraints. Increasing the total duration and/or the number of segments will often help.
```
optimization_result = qctrl.functions.calculate_optimization(
cost_node_name="infidelity",
output_node_names=["infidelity", "I", "Q"],
graph=graph,
)
optimization_result
print("Best cost:")
print(optimization_result.cost)
```
Once you have completed an optimization with a good cost you can export the segments of the pulse to your device.
```
qv.plot_controls(
plt.figure(),
{
"$\Omega_I$": optimization_result.output["I"],
"$\Omega_Q$": optimization_result.output["Q"],
},
)
plt.show()
```
## Sending the pulse to the cloud to realize the NOT gate
```
Ivals, Qvals = optimization_result.output["I"], optimization_result.output["Q"]
Qvals
control_count = 1
segment_count = len(Ivals)
duration = Ivals[0]['duration']*1e9
shot_count = 512
values = []
R, C = [], []
for RE, COM in zip(Ivals, Qvals):
r = RE['value']
c = COM['value']
R.append(r)
C.append(c)
# R = (np.array(R) - np.mean(R))/ np.std(R)
# C = (np.array(C) - np.mean(C))/ np.std(C)
for r, c in zip(R, C):
values.append(r + 1j * c)
# values = np.array(values)
# values = (values - np.mean(values)) / np.std(values)
norm = np.linalg.norm(values)
values = values/norm
controls = []
controls.append({"duration":duration, "values": np.array(values)})
controls
experiment_results = qctrl.functions.calculate_qchack_measurements(
controls=controls,
shot_count=shot_count,
)
measurements = experiment_results.measurements
for measurement_counts in enumerate(measurements):
print("control: {measurement_counts}")
for measurement_counts in enumerate(measurements):
p0 = measurement_counts.count(0) / shot_count
p1 = measurement_counts.count(1) / shot_count
p2 = measurement_counts.count(2) / shot_count
print(f"control 1: P(|0>) = {p0:.2f}, P(|1>) = {p1:.2f}, P(|2>) = {p2:.2f}")
```
| github_jupyter |
# Tuning Hyperparameters
There are many machine learning algorithms that require *hyperparameters* (parameter values that influence training, but can't be determined from the training data itself). For example, when training a logistic regression model, you can use a *regularization rate* hyperparameter to counteract bias in the model; or when training a convolutional neural network, you can use hyperparameters like *learning rate* and *batch size* to control how weights are adjusted and how many data items are processed in a mini-batch respectively. The choice of hyperparameter values can significantly affect the performance of a trained model, or the time taken to train it; and often you need to try multiple combinations to find the optimal solution.
In this case, you'll use a simple example of a logistic regression model with a single hyperparameter, but the principles apply to any kind of model you can train with Azure Machine Learning.
## Before You Start
Before you start this lab, ensure that you have completed the *Create an Azure Machine Learning Workspace* and *Create a Compute Instance* tasks in [Lab 1: Getting Started with Azure Machine Learning](./labdocs/Lab01.md). Then open this notebook in Jupyter on your Compute Instance.
## Connect to Your Workspace
The first thing you need to do is to connect to your workspace using the Azure ML SDK.
> **Note**: You may be prompted to authenticate. Just copy the code and click the link provided to sign into your Azure subscription, and then return to this notebook.
```
import azureml.core
from azureml.core import Workspace
# Load the workspace from the saved config file
ws = Workspace.from_config()
print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
```
## Prepare Data for an Experiment
In this lab, you'll use a dataset containing details of diabetes patients. Run the cell below to create this dataset (if you already created it, the code will create a new version)
```
from azureml.core import Dataset
default_ds = ws.get_default_datastore()
if 'diabetes dataset' not in ws.datasets:
default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data
target_path='diabetes-data/', # Put it in a folder path in the datastore
overwrite=True, # Replace existing files of the same name
show_progress=True)
#Create a tabular dataset from the path on the datastore (this may take a short while)
tab_data_set = Dataset.Tabular.from_delimited_files(path=(default_ds, 'diabetes-data/*.csv'))
# Register the tabular dataset
try:
tab_data_set = tab_data_set.register(workspace=ws,
name='diabetes dataset',
description='diabetes data',
tags = {'format':'CSV'},
create_new_version=True)
print('Dataset registered.')
except Exception as ex:
print(ex)
else:
print('Dataset already registered.')
```
## Prepare a Training Script
Let's start by creating a folder for the training script you'll use to train a logistic regression model.
```
import os
experiment_folder = 'diabetes_training-hyperdrive'
os.makedirs(experiment_folder, exist_ok=True)
print('Folder ready.')
```
Now create the Python script to train the model. This must include:
- A parameter for each hyperparameter you want to optimize (in this case, there's only the regularization hyperparameter)
- Code to log the performance metric you want to optimize for (in this case, you'll log both AUC and accuracy, so you can choose to optimize the model for either of these)
```
%%writefile $experiment_folder/diabetes_training.py
# Import libraries
import os
import argparse
import joblib
from azureml.core import Run
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
# Set regularization parameter
parser = argparse.ArgumentParser()
parser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01, help='regularization rate')
args = parser.parse_args()
reg = args.reg_rate
# Get the experiment run context
run = Run.get_context()
# load the diabetes dataset
print("Loading Data...")
diabetes = run.input_datasets['diabetes'].to_pandas_dataframe() # Get the training data from the estimator input
# Separate features and labels
X, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values
# Split data into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)
# Train a logistic regression model
print('Training a logistic regression model with regularization rate of', reg)
run.log('Regularization Rate', np.float(reg))
model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train)
# calculate accuracy
y_hat = model.predict(X_test)
acc = np.average(y_hat == y_test)
print('Accuracy:', acc)
run.log('Accuracy', np.float(acc))
# calculate AUC
y_scores = model.predict_proba(X_test)
auc = roc_auc_score(y_test,y_scores[:,1])
print('AUC: ' + str(auc))
run.log('AUC', np.float(auc))
os.makedirs('outputs', exist_ok=True)
# note file saved in the outputs folder is automatically uploaded into experiment record
joblib.dump(value=model, filename='outputs/diabetes_model.pkl')
run.complete()
```
## Prepare a Compute Target
One of the benefits of cloud compute is that it scales on-demand, enabling you to provision enough compute resources to process multiple runs of an experiment in parallel, each with different hyperparameter values.
You'll create an Azure Machine Learning compute cluster in your workspace (or use an existing one if you have created it previously).
> **Important**: Change *your-compute-cluster* to a unique name for your compute cluster in the code below before running it! Cluster names must be globally unique names between 2 to 16 characters in length. Valid characters are letters, digits, and the - character.
```
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
cluster_name = "your-compute-cluster"
try:
# Check for existing compute target
training_cluster = ComputeTarget(workspace=ws, name=cluster_name)
print('Found existing cluster, use it.')
except ComputeTargetException:
# If it doesn't already exist, create it
try:
compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS11_V2', max_nodes=2)
training_cluster = ComputeTarget.create(ws, cluster_name, compute_config)
training_cluster.wait_for_completion(show_output=True)
except Exception as ex:
print(ex)
```
## Run a *Hyperdrive* Experiment
Azure Machine Learning includes a hyperparameter tuning capability through *Hyperdrive* experiments. These experiments launch multiple child runs, each with a different hyperparameter combination. The run producing the best model (as determined by the logged target performance metric for which you want to optimize) can be identified, and its trained model selected for registration and deployment.
```
from azureml.core import Experiment
from azureml.train.sklearn import SKLearn
from azureml.train.hyperdrive import GridParameterSampling, BanditPolicy, HyperDriveConfig, PrimaryMetricGoal, choice
from azureml.widgets import RunDetails
# Sample a range of parameter values
params = GridParameterSampling(
{
# There's only one parameter, so grid sampling will try each value - with multiple parameters it would try every combination
'--regularization': choice(0.001, 0.005, 0.01, 0.05, 0.1, 1.0)
}
)
# Get the training dataset
diabetes_ds = ws.datasets.get("diabetes dataset")
# Create an estimator that uses the remote compute
hyper_estimator = SKLearn(source_directory=experiment_folder,
inputs=[diabetes_ds.as_named_input('diabetes')], # Pass the dataset as an input...
pip_packages=['azureml-sdk'], # ...so we need azureml-dataprep (it's in the SDK!)
entry_script='diabetes_training.py',
compute_target = training_cluster,)
# Configure hyperdrive settings
hyperdrive = HyperDriveConfig(estimator=hyper_estimator,
hyperparameter_sampling=params,
policy=None,
primary_metric_name='AUC',
primary_metric_goal=PrimaryMetricGoal.MAXIMIZE,
max_total_runs=6,
max_concurrent_runs=4)
# Run the experiment
experiment = Experiment(workspace = ws, name = 'diabates_training_hyperdrive')
run = experiment.submit(config=hyperdrive)
# Show the status in the notebook as the experiment runs
RunDetails(run).show()
run.wait_for_completion()
```
You can view the experiment run status in the widget above. You can also view the main Hyperdrive experiment run and its child runs in [Azure Machine Learning studio](https://ml.azure.com).
> **Note**: The widget may not refresh. You'll see summary information displayed below the widget when the run has completed.
## Determine the Best Performing Run
When all of the runs have finished, you can find the best one based on the performance metric you specified (in this case, the one with the best AUC).
```
for child_run in run.get_children_sorted_by_primary_metric():
print(child_run)
best_run = run.get_best_run_by_primary_metric()
best_run_metrics = best_run.get_metrics()
parameter_values = best_run.get_details() ['runDefinition']['arguments']
print('Best Run Id: ', best_run.id)
print(' -AUC:', best_run_metrics['AUC'])
print(' -Accuracy:', best_run_metrics['Accuracy'])
print(' -Regularization Rate:',parameter_values)
```
Now that you've found the best run, you can register the model it trained.
```
from azureml.core import Model
# Register model
best_run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',
tags={'Training context':'Hyperdrive'},
properties={'AUC': best_run_metrics['AUC'], 'Accuracy': best_run_metrics['Accuracy']})
# List registered models
for model in Model.list(ws):
print(model.name, 'version:', model.version)
for tag_name in model.tags:
tag = model.tags[tag_name]
print ('\t',tag_name, ':', tag)
for prop_name in model.properties:
prop = model.properties[prop_name]
print ('\t',prop_name, ':', prop)
print('\n')
```
> **More Information**: For more information about Hyperdrive, see the [Azure ML documentation](https://docs.microsoft.com/azure/machine-learning/how-to-tune-hyperparameters).
| github_jupyter |
### Introduction
This notebook records the experiments I have done in the article of "Computing Semantic Similarity of Concepts in Knowledge Graphs". If someone is interested in reproducing the experiments, one can install Sematch and use this notebook for reference.
```
from sematch.semantic.similarity import WordNetSimilarity
from IPython.display import display
import pandas as pd
```
### A simple example of word similarity
```
wns = WordNetSimilarity()
words = ['artist', 'musician', 'scientist', 'physicist', 'actor', 'movie']
sim_matrix = [[wns.word_similarity(w1, w2, 'wpath') for w1 in words] for w2 in words]
df = pd.DataFrame(sim_matrix, index=words,columns=words)
display(df)
```
### Evaluations on Word Similarity Datasets
We have collected some well known word similarity datasets for evaluating semantic similarity metrics. Several python classes can be used to separate the dataset for specicial purpose and evaluate the metric function automatically.
We put them together and provide a uniformed framework to evaluate different semantic measures. The word similarity datasets include:
- [Rubenstein and Goodenough (RG)](http://www.cs.cmu.edu/~mfaruqui/word-sim/EN-RG-65.txt)
Herbert Rubenstein and John B. Goodenough. 1965. Contextual correlates of synonymy. Commun. ACM 8, 10 (October 1965), 627-633. DOI=10.1145/365628.365657
- [Miller and Charles (MC)](http://www.cs.cmu.edu/~mfaruqui/word-sim/EN-MC-30.txt)
Miller, George A., and Walter G. Charles. "Contextual correlates of semantic similarity." Language and cognitive processes 6.1 (1991): 1-28.
- [Wordsim353 (WS353)](http://www.cs.technion.ac.il/~gabr/resources/data/wordsim353/)
Lev Finkelstein, Evgeniy Gabrilovich, Yossi Matias, Ehud Rivlin, Zach Solan, Gadi Wolfman, and Eytan Ruppin, "Placing Search in Context: The Concept Revisited", ACM Transactions on Information Systems, 20(1):116-131, January 2002
- [wordsim353 similarity and relatedness (WS353Sim)](http://alfonseca.org/eng/research/wordsim353.html)
Eneko Agirre, Enrique Alfonseca, Keith Hall, Jana Kravalova, Marius Pasca, Aitor Soroa, A Study on Similarity and Relatedness Using Distributional and WordNet-based Approaches, In Proceedings of NAACL-HLT 2009.
- [SimLex-999 (SIMLEX)](http://www.cl.cam.ac.uk/~fh295/simlex.html)
SimLex-999: Evaluating Semantic Models with (Genuine) Similarity Estimation. 2014. Felix Hill, Roi Reichart and Anna Korhonen. Preprint pubslished on arXiv. arXiv:1408.3456
```
from sematch.evaluation import WordSimEvaluation
from sematch.semantic.similarity import WordNetSimilarity, YagoTypeSimilarity
from nltk.corpus import wordnet as wn
data_word_noun = ['noun_rg','noun_mc','noun_ws353','noun_ws353-sim','noun_simlex']
data_word_graph = ['graph_rg','graph_mc','graph_ws353','graph_ws353-sim','graph_simlex']
data_word_type = ['type_rg','type_mc','type_ws353','type_ws353-sim','type_simlex']
sim_methods_noun = ['path','lch','wup','li','res','lin','jcn','wpath']
sim_methods_graph = ['path','lch','wup','li','res','res_graph','lin','jcn','wpath','wpath_graph']
sim_methods_type = ['path','lch','wup','li','res','res_graph','lin','lin_graph','jcn','jcn_graph','wpath','wpath_graph']
ws_eval = WordSimEvaluation()
wns = WordNetSimilarity()
yagosim = YagoTypeSimilarity()
```
To produce the TABLE 2 in the article "The illustration of Semantic Similarity Methods on Some Concept Pair Examples". We manually create the word to synset mapping and compute their semantic similarity scores using different semantic similarity metrics.
```
aspects = {'beef':wn.synset('beef.n.02'), 'lamb':wn.synset('lamb.n.05'), 'octopus':wn.synset('octopus.n.01'),
'shellfish':wn.synset('shellfish.n.01'), 'meat':wn.synset('meat.n.01'), 'seafood':wn.synset('seafood.n.01'),
'food':wn.synset('food.n.02'), 'service':wn.synset('service.n.02'),'atmosphere':wn.synset('atmosphere.n.01'),
'coffee':wn.synset('coffee.n.01')}
aspect_pairs = [('beef', 'octopus'), ('beef', 'lamb'), ('meat','seafood'), ('octopus', 'shellfish'),
('beef','service'),('beef','atmosphere'),('beef', 'coffee'), ('food','coffee')]
aspects_sim_matrix = [[wns.similarity(aspects[w1], aspects[w2], m) for m in sim_methods_noun]
for w1, w2 in aspect_pairs]
aspect_index = [x+'-'+y for x, y in aspect_pairs]
aspect_df = pd.DataFrame(aspects_sim_matrix, index=aspect_index, columns=sim_methods_noun)
display(aspect_df)
```
#### WPATH method with different K in Word Noun Datasets
The data_word_noun contains word pairs that can be mapped to WordNet noun taxonomy. The k settings are varied with interval 0.1 started from 0.1.
```
wpath_cors = [ws_eval.evaluate_wpath_k(dataset) for _, dataset in enumerate(data_word_noun)]
cors_matrix = [[cors[i] for _, cors in enumerate(wpath_cors)] for i in range(1,11)]
wpath_index = map(lambda x: str(x/10.0), range(1, 11))
df_wpath = pd.DataFrame(cors_matrix, index=wpath_index, columns=data_word_noun)
display(df_wpath)
```
#### WPATH method with different K in Word Graph Datasets
In word graph dataset, we performed the evaluation of wpath with different k using corpus-based IC and graph-based IC respectively.
```
#evaluate with corpus-based IC
wpath_cors = [ws_eval.evaluate_wpath_k(dataset) for _, dataset in enumerate(data_word_graph)]
cors_matrix = [[cors[i] for _, cors in enumerate(wpath_cors)] for i in range(1,11)]
df_wpath_graph = pd.DataFrame(cors_matrix, index=wpath_index, columns=data_word_graph)
display(df_wpath_graph)
#evaluate with graph-based IC
wpath_cors = [ws_eval.evaluate_wpath_k(dataset, 'graph') for _, dataset in enumerate(data_word_graph)]
cors_matrix = [[cors[i] for _, cors in enumerate(wpath_cors)] for i in range(1,11)]
df_wpath_graph = pd.DataFrame(cors_matrix, index=wpath_index, columns=data_word_graph)
display(df_wpath_graph)
```
#### WPATH method with different K in Word Type Datasets
```
#evaluate with corpus-based IC
wpath_cors = [ws_eval.evaluate_wpath_k(dataset) for _, dataset in enumerate(data_word_type)]
cors_matrix = [[cors[i] for _, cors in enumerate(wpath_cors)] for i in range(1,11)]
df_wpath_type = pd.DataFrame(cors_matrix, index=wpath_index, columns=data_word_type)
display(df_wpath_type)
#evaluate with graph-based IC
wpath_cors = [ws_eval.evaluate_wpath_k(dataset, 'graph') for _, dataset in enumerate(data_word_type)]
cors_matrix = [[cors[i] for _, cors in enumerate(wpath_cors)] for i in range(1,11)]
df_wpath_type = pd.DataFrame(cors_matrix, index=wpath_index, columns=data_word_type)
display(df_wpath_type)
```
#### Baseline semantic similarity metrics on Word Noun Datasets
```
path = lambda x, y: wns.word_similarity(x, y, 'path')
lch = lambda x, y: wns.word_similarity(x, y, 'lch')
wup = lambda x, y: wns.word_similarity(x, y, 'wup')
li = lambda x, y: wns.word_similarity(x, y, 'li')
res = lambda x, y: wns.word_similarity(x, y, 'res')
lin = lambda x, y: wns.word_similarity(x, y, 'lin')
jcn = lambda x, y: wns.word_similarity(x, y, 'jcn')
methods = {'path':path, 'lch':lch, 'wup':wup, 'li':li, 'res':res, 'lin':lin, 'jcn':jcn}
cor_dicts = [ws_eval.evaluate_multiple_metrics(methods, dataset) for dataset in data_word_noun]
baseline_cors_matrix = [[cors[m] for _, cors in enumerate(cor_dicts)] for m in sim_methods_noun[0:7]]
df_baselines_noun = pd.DataFrame(baseline_cors_matrix, index=sim_methods_noun[0:7], columns=data_word_noun)
display(df_baselines_noun)
```
#### Baseline semantic similarity metrics on Word Graph Datasets
```
res_graph = lambda x, y: yagosim.word_similarity(x, y, 'res_graph')
methods['res_graph'] = res_graph
cor_dicts = [ws_eval.evaluate_multiple_metrics(methods, dataset) for dataset in data_word_graph]
baseline_cors_matrix = [[cors[m] for _, cors in enumerate(cor_dicts)] for m in sim_methods_graph[0:8]]
df_baselines_graph = pd.DataFrame(baseline_cors_matrix, index=sim_methods_graph[0:8], columns=data_word_graph)
display(df_baselines_graph)
```
#### Baseline semantic similarity metrics on Word Type Datasets
```
lin_graph = lambda x, y: yagosim.word_similarity(x, y, 'lin_graph')
jcn_graph = lambda x, y: yagosim.word_similarity(x, y, 'jcn_graph')
methods['lin_graph'] = lin_graph
methods['jcn_graph'] = jcn_graph
cor_dicts = [ws_eval.evaluate_multiple_metrics(methods, dataset) for dataset in data_word_type]
baseline_cors_matrix = [[cors[m] for _, cors in enumerate(cor_dicts)] for m in sim_methods_type[0:10]]
df_baselines_type = pd.DataFrame(baseline_cors_matrix, index=sim_methods_type[0:10], columns=data_word_type)
display(df_baselines_type)
```
#### Steiger's Z Significance Test on Word Noun Dataset
```
wpath_rg = lambda x, y: wns.word_similarity_wpath(x, y, 0.9)
wpath_mc = lambda x, y: wns.word_similarity_wpath(x, y, 0.4)
wpath_ws353 = lambda x, y: wns.word_similarity_wpath(x, y, 0.5)
wpath_ws353sim = lambda x, y: wns.word_similarity_wpath(x, y, 0.8)
wpath_simlex = lambda x, y: wns.word_similarity_wpath(x, y, 0.8)
methods = {'wpath_rg':wpath_rg, 'wpath_mc':wpath_mc, 'wpath_ws353':wpath_ws353,
'wpath_ws353sim':wpath_ws353sim,'wpath_simlex':wpath_simlex}
cor_dicts = [ws_eval.evaluate_multiple_metrics(methods, dataset) for dataset in data_word_noun]
wpath_dic = {'noun_rg':'wpath_rg', 'noun_mc':'wpath_mc', 'noun_ws353':'wpath_ws353',
'noun_ws353-sim':'wpath_ws353sim', 'noun_simlex':'wpath_simlex'}
cors_matrix = [[cor_dicts[i][wpath_dic[dataset]] for i, dataset in enumerate(data_word_noun)]]
df_cors = pd.DataFrame(cors_matrix, index=['metrics'], columns=data_word_noun)
display(df_cors)
```
To perform the Steiger's Z Significance Test, one can use the implementation integrated in Sematch framework, or use the R, cocor package. The example scripts using cocor package to perform statistical test in Simlex dataset is shown as:
```
require(cocor) # load package
#j means dependent sample, k and h means comparison sample
#we have wpath with human (jk), jcn with human (jh), and wpath with jcn (kh)
#simlex
#wpath with path Pass
cocor.dep.groups.overlap(r.jk=+0.603, r.jh=+0.584, r.kh=+0.955, n=666, alternative="greater", alpha=0.05, conf.level=0.95, null.value=0)
#wpath with lch Pass
cocor.dep.groups.overlap(r.jk=+0.603, r.jh=+0.584, r.kh=+0.955, n=666, alternative="greater", alpha=0.05, conf.level=0.95, null.value=0)
#wpath with wup Pass
cocor.dep.groups.overlap(r.jk=+0.603, r.jh=+0.542, r.kh=+0.946, n=666, alternative="greater", alpha=0.05, conf.level=0.95, null.value=0)
#wpath with li Pass
cocor.dep.groups.overlap(r.jk=+0.603, r.jh=+0.586, r.kh=+0.965, n=666, alternative="greater", alpha=0.05, conf.level=0.95, null.value=0)
#wpath with res Pass
cocor.dep.groups.overlap(r.jk=+0.603, r.jh=+0.535, r.kh=+0.913, n=666, alternative="greater", alpha=0.05, conf.level=0.95, null.value=0)
#wpath with lin Pass
cocor.dep.groups.overlap(r.jk=+0.603, r.jh=+0.582, r.kh=+0.944, n=666, alternative="greater", alpha=0.05, conf.level=0.95, null.value=0)
```
The example of using the integrated Statistical Test is illustrate in the following codes.
```
stats_tests = []
for _, dataset in enumerate(data_word_noun):
stats = {}
for _, m in enumerate(sim_methods_noun[0:7]):
cor, p_value = ws_eval.statistical_test(wpath_dic[dataset], m, dataset)
stats[m] = '('+str(round(cor,3))+','+str(p_value)+')'
stats_tests.append(stats)
stats_matrix = [[cors[m] for _, cors in enumerate(stats_tests)] for _, m in enumerate(sim_methods_noun[0:7])]
df_stats = pd.DataFrame(stats_matrix, index=sim_methods_noun[0:7], columns=data_word_noun)
display(df_stats)
```
| github_jupyter |
```
# !python -m spacy download en_core_web_sm
# import spacy
# spacy.load('en_core_web_sm')
import spacy
import torch
import torchtext
from torchtext.legacy import datasets, data
import torch.nn.functional as F
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Containers for tokenisation
# using tokenize="spacy" because it's the best.
text_field = data.Field(tokenize="spacy", tokenizer_language="en_core_web_sm", fix_length=100, batch_first=True)
label_field = data.LabelField(dtype=torch.float) # torch.float because GPUs use floats
# Load dataset and split to train and test data
# IMDB dataset (about movies)
train, test = datasets.IMDB.splits(text_field=text_field, label_field=label_field)
# Split to train and validation set - 80% to train_set, 20% to validation_set
# The original set is 25k descriptions(?) so train_set after the split is 20k and valid_set is 5k.
train_set, valid_set = train.split(0.8)
len(train_set), len(valid_set) # 20_000, 5_000
text_field.build_vocab(train_set, max_size=25_000, vectors="glove.6B.100d")
label_field.build_vocab(train_set)
assert len(text_field.vocab) == 25_002
# Map int to string and string to int
# text_field.vocab.itos[186] -> 'though'
# text_field.vocab.stoi['though'] -> 186
text_field.vocab.itos[:10]
len(max(train_set, key=lambda x: len(x.text)).text)
# but we can do better!
train_buckets, valid_buckets, test_buckets = data.BucketIterator.splits(
(train_set, valid_set, test), batch_size=64, device=device
)
from torch import nn
from typing import Tuple
class NLPModuleCNN(nn.Module):
def __init__(
self,
num_embedding: int,
embedding_dim: int,
out_channels: int,
kernel_size: Tuple[int],
out_features: int,
p_dropout: float,
pad_index: int,
):
super().__init__()
self.embedding = nn.Embedding(
num_embedding, embedding_dim, padding_idx=pad_index
)
self.convo2d_0 = nn.Conv2d(1, out_channels, (kernel_size[0], embedding_dim))
self.convo2d_1 = nn.Conv2d(1, out_channels, (kernel_size[1], embedding_dim))
self.convo2d_2 = nn.Conv2d(1, out_channels, (kernel_size[2], embedding_dim))
self.pooling0 = nn.MaxPool1d(kernel_size=(99,))
self.pooling1 = nn.MaxPool1d(kernel_size=(98,))
self.pooling2 = nn.MaxPool1d(kernel_size=(94,))
self.linear = nn.Linear(in_features=out_channels * 3, out_features=out_features)
self.dropout = nn.Dropout(p=p_dropout)
def forward(self, input):
embed = self.embedding(input).unsqueeze(1)
c0 = F.relu(self.convo2d_0(embed).squeeze(3))
c1 = F.relu(self.convo2d_1(embed).squeeze(3))
c2 = F.relu(self.convo2d_2(embed).squeeze(3))
c0 = self.pooling0(c0).squeeze(2)
c1 = self.pooling1(c1).squeeze(2)
c2 = self.pooling2(c2).squeeze(2)
cc = torch.cat([c0, c1, c2], dim=1)
drop = self.dropout(cc)
lin = self.linear(drop)
return lin
num_embedding = len(text_field.vocab)
embedding_dim = 100
hidden_size = 256
out_features = 1
model = NLPModuleCNN(
num_embedding=num_embedding,
embedding_dim=embedding_dim,
out_channels=100,
kernel_size=(2, 3, 7),
out_features=out_features,
p_dropout=0.5,
pad_index=text_field.vocab.stoi[text_field.pad_token],
)
model.embedding
for i in range(5):
train_losses, train_metrics = train(model, train_buckets, optimiser, criterion)
# validated_losses, validated_metrics = validate(model, valid_buckets, criterion)
print()
print("Train metrics", np.mean(train_losses), np.mean(train_metrics))
# print("Validation metrics", np.mean(validated_losses), np.mean(validated_metrics))
pre_trained_embeddings = text_field.vocab.vectors
model.embedding.weight.data.copy_(pre_trained_embeddings)
def policz(mod):
return sum(p.numel() for p in mod.parameters())
policz(model)
# Stochastic gradient descent SGD
# minimalizować funkcję kosztu (szukanie minimum)
import torch.optim as optim
optimiser = optim.Adam(model.parameters())
criterion = nn.BCEWithLogitsLoss()
ciretrion = criterion.to(device)
model = model.to(device)
def binary_accuracy(prediction, target):
prediction = F.sigmoid(prediction)
prediction = torch.round(prediction)
compared = (prediction == target).float()
return torch.mean(compared)
T = torch.tensor
binary_accuracy(T([0, 0.5, .2, 0.001, 0.8]), T([0, 1, 1, 1, 1]))
import numpy as np
import tqdm
def train(mod, data, optimiser, criterion):
losses = []
metrics = []
mod = mod.to(device)
# train pozwala na akumulację błędów, które potem będziemy propagować wstecz
mod.train()
for bucket in tqdm.tqdm(data):
optimiser.zero_grad()
output = mod(bucket.text).squeeze(0).squeeze(1)
loss = criterion(output, bucket.label)
metric = binary_accuracy(output, bucket.label)
losses.append(loss.item())
metrics.append(metric.item())
loss.backward()
optimiser.step()
# print(np.mean(losses), losses[-1], np.mean(metrics), metrics[-1])
return losses, metrics
def validate(mod, data, criterion):
losses = []
metrics = []
# wyłącza akumulacje błędów (z którego korzystaliśmy w train)
mod.eval()
i = 0
for bucket in tqdm.tqdm(data):
i += 1
output = mod(bucket.text).squeeze(0).squeeze(1)
output2 = F.sigmoid(output)
# print(" ".join(text_field.vocab.itos[t] for t in bucket.text[0]))
# print(f"{bucket.label[0]}")
# print(f"{output2[0]}")
# if i > 10:
# break
loss = criterion(output, bucket.label)
metric = binary_accuracy(output, bucket.label)
losses.append(loss.item())
metrics.append(metric.item())
# print(np.mean(losses), losses[-1], np.mean(metrics), metrics[-1])
return losses, metrics
tokenizer = spacy.load("en_core_web_sm")
validated_losses, validated_metrics = validate(model, valid_buckets, criterion)
print("Validation metrics", np.mean(validated_losses), np.mean(validated_metrics))
def s2(model, sentence: str) -> bool:
tt = [t for t in sentence.split()]
tt = tt[:100]
while len(tt) < 100:
tt.append("<pad>")
m = F.sigmoid(model(torch.LongTensor([[text_field.vocab.stoi[t] for t in tt],]).to(device)))
print(sentence, m.to("cpu").detach().numpy().ravel())
s2(model, "it's bad")
s2(model, "it's good")
s2(model, "it's very bad")
s2(model, "it's very good")
s2(model, "it's aweful")
s2(model, "it's awesome")
s2(model, "it's great")
s2(model, "i like this film")
s2(model, "i don't like this film")
s2(model, "it is the best movie I have ever seen")
s2(model, "it is the worst movie I have ever seen")
s2(model, "borat was the great success, i very much liked this movie, best movie ever")
s2(model, "very boring movie I didn't like it")
def sentiment(model, sentence: str) -> bool:
tokens = tokenizer.tokenizer(sentence)
tokenized = [text_field.vocab.stoi[t.text] for t in tokens]
print("|".join(text_field.vocab.itos[t] for t in tokenized))
result = F.sigmoid(model(torch.LongTensor(tokenized).unsqueeze(1).to(device)))
print(result.to("cpu").detach().numpy().ravel(), sentence)
sentiment(model, "it's bad")
sentiment(model, "it's good")
sentiment(model, "it's very bad")
sentiment(model, "it's very good")
sentiment(model, "it's aweful")
sentiment(model, "it's awesome")
sentiment(model, "it's great")
sentiment(model, "i like this film")
sentiment(model, "i don't like this film")
sentiment(model, "it is the best movie I have ever seen")
sentiment(model, "it is the worst movie I have ever seen")
sentiment(model, "borat was the great success, i very much liked this movie, best movie ever")
sentiment(model, "very boring movie I didn't like it")
shawshank = """
Why do I want to write the 234th comment on The Shawshank Redemption? I am not sure - almost everything that could be possibly said about it has been said. But like so many other people who wrote comments, I was and am profoundly moved by this simple and eloquent depiction of hope and friendship and redemption.
The only other movie I have ever seen that effects me as strongly is To Kill a Mockingbird. Both movies leave me feeling cleaner for having watched them.
"""
sentiment(model, shawshank)
shawshank2 = """
This film is nothing but one cliche after another. Having seen many of the 100's of prison films made from the early 30's to the 50's, I was able to pull almost every minute of Shawcrap from one of those films.
While it is visually well made and acted, the story has every plot point of the "standard" prison film. They have the evil warden, innocent main character, friendly guilty guy, thugs and one good old prisoner. Don't waste your time on this one. Rent or buy some of the classic's of the prison genre
"""
sentiment(model, shawshank2)
reddit = """............ . . . . . . .. ... … ...................................................................................................."""
sentiment(model, reddit)
klasa = """
Kant has written a treatise on _The Vital Powers_; but I should like to
write a dirge on them, since their lavish use in the form of knocking,
hammering, and tumbling things about has made the whole of my life a
daily torment. Certainly there are people, nay, very many, who will
smile at this, because they are not sensitive to noise; it is precisely
these people, however, who are not sensitive to argument, thought,
poetry or art, in short, to any kind of intellectual impression: a fact
to be assigned to the coarse quality and strong texture of their brain
tissues.
"""
sentiment(model, klasa)
sentiment(model, "great success")
# Funkcja kosztu, im bliżej 1 (target) tym funkcja kosztu maleje.
target = torch.ones([1, 1], dtype=torch.float32) # 64 classes, batch size = 10
input_ = torch.full([1, 1], 0.1) # A prediction (logit)
print(F.binary_cross_entropy_with_logits(input_, target))
target = torch.ones([1, 1], dtype=torch.float32) # 64 classes, batch size = 10
input_ = torch.full([1, 1], 0.4) # A prediction (logit)
print(F.binary_cross_entropy_with_logits(input_, target))
target = torch.ones([1, 1], dtype=torch.float32) # 64 classes, batch size = 10
input_ = torch.full([1, 1], 0.7) # A prediction (logit)
print(F.binary_cross_entropy_with_logits(input_, target))
target = torch.ones([1, 1], dtype=torch.float32) # 64 classes, batch size = 10
input_ = torch.full([1, 1], 0.9) # A prediction (logit)
print(F.binary_cross_entropy_with_logits(input_, target))
target, input_
>>> rnn = nn.RNN(3, 2, 1)
>>> input = torch.randn(5, 3, 3)
>>> h0 = torch.randn(1, 3, 2)
>>> output, hn = rnn(input, h0)
output, hn
>>> # an Embedding module containing 10 tensors of size 3
>>> embedding = nn.Embedding(100, 19)
>>> # a batch of 2 samples of 4 indices each
>>> input = torch.LongTensor([[1,98,1,0, 4,3,2,9],[4,3,2,9, 4,3,2,9]])
>>> embedding(input)
```
| github_jupyter |
## Image网 Submission `128x128`
This contains a submission for the Image网 leaderboard in the `128x128` category.
In this notebook we:
1. Train on 1 pretext task:
- Train a network to do image inpatining on Image网's `/train`, `/unsup` and `/val` images.
2. Train on 4 downstream tasks:
- We load the pretext weights and train for `5` epochs.
- We load the pretext weights and train for `20` epochs.
- We load the pretext weights and train for `80` epochs.
- We load the pretext weights and train for `200` epochs.
Our leaderboard submissions are the accuracies we get on each of the downstream tasks.
```
import os
os.chdir('..')
import json
import torch
import numpy as np
from functools import partial
from fastai2.basics import *
from fastai2.vision.all import *
torch.cuda.set_device(6)
# Chosen parameters
lr=2e-2
sqrmom=0.99
mom=0.95
beta=0.
eps=1e-4
bs=64
sa=1
m = xresnet34
act_fn = Mish
pool = MaxPool
nc=20
source = untar_data(URLs.IMAGEWANG_160)
len(get_image_files(source/'unsup')), len(get_image_files(source/'train')), len(get_image_files(source/'val'))
# Use the Ranger optimizer
opt_func = partial(ranger, mom=mom, sqr_mom=sqrmom, eps=eps, beta=beta)
m_part = partial(m, c_out=nc, act_cls=torch.nn.ReLU, sa=sa, pool=pool)
model_meta[m_part] = model_meta[xresnet34]
save_name = 'models/imagewang_contrast_kornia_80ep_loweraug_temp5'
```
## Pretext Task: Contrastive Learning
```
#export
from pytorch_metric_learning import losses
class XentLoss(losses.NTXentLoss):
def forward(self, output1, output2):
stacked = torch.cat((output1, output2), dim=0)
labels = torch.arange(output1.shape[0]).repeat(2)
return super().forward(stacked, labels, None)
class ContrastCallback(Callback):
run_before=Recorder
def __init__(self, size=256, aug_targ=None, aug_pos=None, temperature=0.1):
self.aug_targ = ifnone(aug_targ, get_aug_pipe(size))
self.aug_pos = ifnone(aug_pos, get_aug_pipe(size))
self.temperature = temperature
def update_size(self, size):
pipe_update_size(self.aug_targ, size)
pipe_update_size(self.aug_pos, size)
def begin_fit(self):
self.old_lf = self.learn.loss_func
self.old_met = self.learn.metrics
self.learn.metrics = []
self.learn.loss_func = losses.NTXentLoss(self.temperature)
def after_fit(self):
self.learn.loss_fun = self.old_lf
self.learn.metrics = self.old_met
def begin_batch(self):
xb, = self.learn.xb
xb_targ = self.aug_targ(xb)
xb_pos = self.aug_pos(xb)
self.learn.xb = torch.cat((xb_targ, xb_pos), dim=0),
self.learn.yb = torch.arange(xb_targ.shape[0]).repeat(2),
#export
def pipe_update_size(pipe, size):
for tf in pipe.fs:
if isinstance(tf, RandomResizedCropGPU):
tf.size = size
def get_dbunch(size, bs, workers=8, dogs_only=False):
path = URLs.IMAGEWANG_160 if size <= 160 else URLs.IMAGEWANG
source = untar_data(path)
folders = ['unsup', 'val'] if dogs_only else None
files = get_image_files(source, folders=folders)
tfms = [[PILImage.create, ToTensor, RandomResizedCrop(size, min_scale=0.9)],
[parent_label, Categorize()]]
# dsets = Datasets(files, tfms=tfms, splits=GrandparentSplitter(train_name='unsup', valid_name='val')(files))
dsets = Datasets(files, tfms=tfms, splits=RandomSplitter(valid_pct=0.1)(files))
# batch_tfms = [IntToFloatTensor, *aug_transforms(p_lighting=1.0, max_lighting=0.9)]
batch_tfms = [IntToFloatTensor]
dls = dsets.dataloaders(bs=bs, num_workers=workers, after_batch=batch_tfms)
dls.path = source
return dls
size = 128
bs = 256
dbunch = get_dbunch(160, bs)
len(dbunch.train.dataset)
dbunch.show_batch()
# # xb = TensorImage(torch.randn(1, 3,128,128))
# afn_tfm, lght_tfm = aug_transforms(p_lighting=1.0, max_lighting=0.8, p_affine=1.0)
# # lght_tfm.split_idx = None
# xb.allclose(afn_tfm(xb)), xb.allclose(lght_tfm(xb, split_idx=0))
import kornia
#export
def get_aug_pipe(size, stats=None, s=.6):
stats = ifnone(stats, imagenet_stats)
rrc = kornia.augmentation.RandomResizedCrop((size,size), scale=(0.2, 1.0), ratio=(3/4, 4/3))
rhf = kornia.augmentation.RandomHorizontalFlip()
rcj = kornia.augmentation.ColorJitter(0.8*s, 0.8*s, 0.8*s, 0.2*s)
tfms = [rrc, rhf, rcj, Normalize.from_stats(*stats)]
pipe = Pipeline(tfms)
pipe.split_idx = 0
return pipe
aug = get_aug_pipe(size)
aug2 = get_aug_pipe(size)
cbs = ContrastCallback(size=size, aug_targ=aug, aug_pos=aug2, temperature=0.5)
xb,yb = dbunch.one_batch()
nrm = Normalize.from_stats(*imagenet_stats)
xb_dec = nrm.decodes(aug(xb))
show_images([xb_dec[0], xb[0]])
ch = nn.Sequential(nn.AdaptiveAvgPool2d(1), Flatten(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 128))
learn = cnn_learner(dbunch, m_part, opt_func=opt_func,
metrics=[], loss_func=CrossEntropyLossFlat(), cbs=cbs, pretrained=False,
config={'custom_head':ch}
).to_fp16()
learn.unfreeze()
learn.fit_flat_cos(80, 2e-2, wd=1e-2, pct_start=0.5)
torch.save(learn.model[0].state_dict(), f'{save_name}.pth')
# learn.save(save_name)
```
## Downstream Task: Image Classification
```
def get_dbunch(size, bs, workers=8, dogs_only=False):
path = URLs.IMAGEWANG_160 if size <= 160 else URLs.IMAGEWANG
source = untar_data(path)
if dogs_only:
dog_categories = [f.name for f in (source/'val').ls()]
dog_train = get_image_files(source/'train', folders=dog_categories)
valid = get_image_files(source/'val')
files = dog_train + valid
splits = [range(len(dog_train)), range(len(dog_train), len(dog_train)+len(valid))]
else:
files = get_image_files(source)
splits = GrandparentSplitter(valid_name='val')(files)
item_aug = [RandomResizedCrop(size, min_scale=0.35), FlipItem(0.5)]
tfms = [[PILImage.create, ToTensor, *item_aug],
[parent_label, Categorize()]]
dsets = Datasets(files, tfms=tfms, splits=splits)
batch_tfms = [IntToFloatTensor, Normalize.from_stats(*imagenet_stats)]
dls = dsets.dataloaders(bs=bs, num_workers=workers, after_batch=batch_tfms)
dls.path = source
return dls
def do_train(size=128, bs=64, lr=1e-2, epochs=5, runs=5, dogs_only=False, save_name=None, ch=None):
dbunch = get_dbunch(size, bs, dogs_only=dogs_only)
for run in range(runs):
print(f'Run: {run}')
ch = ifnone(ch, nn.Sequential(nn.AdaptiveAvgPool2d(1), Flatten(), nn.Linear(512, 20)))
learn = cnn_learner(dbunch, m_part, opt_func=opt_func, normalize=False,
metrics=[accuracy,top_k_accuracy], loss_func=LabelSmoothingCrossEntropy(),
# metrics=[accuracy,top_k_accuracy], loss_func=CrossEntropyLossFlat(),
pretrained=False,
config={'custom_head':ch})
if save_name is not None:
state_dict = torch.load(f'{save_name}.pth')
learn.model[0].load_state_dict(state_dict)
learn.unfreeze()
learn.fit_flat_cos(epochs, lr, wd=1e-2)
```
### 5 Epochs
```
epochs = 5
runs = 5
do_train(epochs=epochs, runs=runs, lr=2e-2, dogs_only=False, save_name=save_name)
```
### 20 Epochs
```
epochs = 20
runs = 1
# LATEST
do_train(epochs=epochs, runs=runs, lr=2e-2, dogs_only=False, save_name=save_name)
```
## Larger HEAD
```
ch = create_head(512, 20, concat_pool=False)
do_train(epochs=epochs, runs=runs, lr=2e-2, dogs_only=False, save_name=save_name, ch=ch)
ch = create_head(1024, 20, concat_pool=True, ps=0.25)
do_train(epochs=epochs, runs=runs, lr=2e-2, dogs_only=False, save_name=save_name, ch=ch)
```
## 80 epochs
```
epochs = 80
runs = 1
do_train(epochs=epochs, runs=runs, dogs_only=False, save_name=save_name)
```
Accuracy: **62.18%**
### 200 epochs
```
epochs = 200
runs = 1
do_train(epochs=epochs, runs=runs, dogs_only=False, save_name=save_name)
```
Accuracy: **62.03%**
| github_jupyter |
# Topic Modelling (LDA) of Turing Institute publications
# 0: Set up
### Required packages
```
#data manipulation and organisation
import pandas as pd
import numpy as np
#topic modelling
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
#visualisations
import pyLDAvis
from pyLDAvis import sklearn
import seaborn as sns
import matplotlib.pyplot as plt
#other
import random, pkg_resources, os, json
print('Require sklearn version 0.19, have: ' + pkg_resources.get_distribution("scikit-learn").version)
print("If have lower version, need to change 'n_components' to 'n_topics' when calling LatentDirichletAllocation")
##might need to download nltk corpora and packages
#import nltk
#nltk.download()
```
# 1: Load data and check
```
if os.path.isfile('data_files/final_dataset_full.csv'):
publications = pd.read_csv('data_files/final_dataset_full.csv')
else:
publications_1 = pd.read_csv('data_files/final_dataset_1.csv')
publications_2 = pd.read_csv('data_files/final_dataset_2.csv')
publications = pd.concat([publications_1, publications_2])
publications = publications.rename(columns={'full_name': 'name', 'current_uni': 'uni'})
publications.head()
#check how many fellows have associated with each university
uni_names = publications['uni'].unique()
uni_fellows = publications.groupby('uni')['name'].unique()
for i in range(len(uni_names)):
print(uni_names[i] + ": " + str(len(uni_fellows[i])) + " fellows")
num_fellows = len(publications['name'].unique())
print('\nExcpect 138 fellows overall, have: ' + str(num_fellows))
```
# 2: Note instances of multiple Turing fellows associated with 1 paper - remove duplicates based on paper ID (but keep note of all authors to attribute later)
paper_id_to_authors dictionary keys correspond to all unique paper ids
dictionary value is a list of authors associated with that paper (most instances have 1 but in some cases have multiple)
```
paper_id_to_authors = {}
for idx, row in publications.iterrows():
if row['paper_id'] not in paper_id_to_authors.keys():
paper_id_to_authors[row['paper_id']] = [row['name']]
else:
paper_id_to_authors[row['paper_id']].append(row['name'])
#drop duplicates - rename df
publications_data = publications.drop_duplicates(subset = 'paper_id')
#relabel index numbers
publications_data = publications_data.reset_index(drop=True)
print('Dataset contains {0[0]} unique articles'.format(publications_data.shape))
```
# 3: LDA
### Create document-term matrix from text data
```
#1: create vector representation of vocabulary
vectorizer = CountVectorizer(max_df=0.95, min_df=2)
#create document_term_matrix
dtm = vectorizer.fit_transform(publications_data['full_text'].values.astype('U'))
#retrieve word names at each vocabulary position
feature_names = vectorizer.get_feature_names()
```
### Train model
```
n_topics = 25
lda = LatentDirichletAllocation(n_components = n_topics, max_iter = 50,
learning_method = 'online', random_state = 0)
lda.fit(dtm)
```
### Visualise topics (LDAvis)
```
pyLDAvis.enable_notebook
prepared_data = pyLDAvis.sklearn.prepare(lda, dtm, vectorizer)
pyLDAvis.display(prepared_data)
```
## 4: Organise LDA outputs
### Retrieve topic_term and document_topic distributions
```
def df_with_names(data, index_name, columns_name):
if type(data) == pd.DataFrame:
#we want our index to be numbered
df = pd.DataFrame(data.values)
else:
df = pd.DataFrame(data)
df.index.name = index_name
df.columns.name = columns_name
return df
def series_with_name(data, name):
if type(data) == pd.Series:
data.name = name
#ensures a numeric index
return data.reset_index()[name]
else:
return pd.Series(data, name=name)
topic_term_dists = lda.components_ / lda.components_.sum(axis=1)[:, None]
doc_topic_dists = lda.transform(dtm)
topic_term_dists = df_with_names(topic_term_dists, 'topic', 'term')
doc_topic_dists = df_with_names(doc_topic_dists, 'doc', 'topic')
```
## 5: Format data for visualisation
### Transform document_topic distribution to fellow_topic and institute_topic information
publications_data df:
each row of the df corresponds to row of same index in doc_topic_dists
this allows us to get paper_id for the doc_topic_distribution of any paper
we can then match the paper_id against known Turing fellows associated with that paper
For each fellow, we get the average of distributions over topics for their documents and multiple by 100 to turn proportion into percentage -- this reflects the average percentage that their articles have been assigned each topic (which is based on how many words in each document have been assigned to each topic)
Overall topic importance is the average of above topic value assignment across all fellows - this means each fellow contributes equally to the topic importance/size evaluation (even if they overall contributed fewer papers)
### Extract topic proportions for each author
```
author_names = publications_data['name'].unique()
author_topic_dists = {}
author_counts = {}
for index, row in publications_data.iterrows():
#most papers have 1 author but some have multiple so this assures paper topics are assigned to all relevant authors
for name in paper_id_to_authors[row['paper_id']]:
if name in author_topic_dists.keys():
author_topic_dists[name] += doc_topic_dists.iloc[index]
author_counts[name] += 1
else:
author_topic_dists[name] = doc_topic_dists.iloc[index]
author_counts[name] = 1
# percentage of topics per author
for name in author_topic_dists.keys():
if author_topic_dists[name].sum() != 0:
author_topic_dists[name] = author_topic_dists[name]/author_counts[name]*100
```
### Extract overall institute topic "importance" (size) information
```
topic_importance, total = {}, 0
for i in range(n_topics):
topic_importance[i] = 0
for name in author_topic_dists:
topic_importance[i] += author_topic_dists[name][i]
topic_importance[i] = topic_importance[i]/num_fellows
total += topic_importance[i]
```
### Combine all topic information in one df - save topic order
```
author_topic_info = pd.DataFrame.from_dict(author_topic_dists, orient = 'columns')
topic_info = pd.DataFrame.from_dict(topic_importance, orient='index')
merged = pd.concat([author_topic_info, topic_info], axis =1 )
merged = merged.rename(columns={0: 'topicVal'})
##order topics by topicVal (overall topic importance)
merged = merged.sort_values(['topicVal'], ascending = 0)
topic_order = merged.index.values
```
### Combine topics that have assigned topic value < 1.5 (out of 100) into 1 topic that will be labeled 'other'
```
to_combine = merged.loc[merged['topicVal'] < 1.5]
key_topics = merged.loc[merged['topicVal'] >= 1.5]
key_topics = key_topics.append(to_combine.sum(), ignore_index=True)
```
### Save to csv
```
key_topics.to_csv("visualisation/data_final.csv", index_label='topicNum')
```
## 6: Determine order in which to display researchers - ordered by university, by most prevalent topic
### Order researchers by university + extract prevalent topic info
```
researchers_dict = {}
for column in merged:
name = column
topics_order = merged.sort_values([column], ascending = 0)
topic_num = topics_order.index.values[0]
topic_val = topics_order[column][topic_num]
if name != 'topicVal':
#use original df to search for uni in case some researchers where removed during duplicates deletion
uni = publications.loc[publications['name']== name]['uni'].values[0]
if uni not in researchers_dict.keys():
researchers_dict[uni] = {topic_num:[[name, topic_val]]}
else:
if topic_num not in researchers_dict[uni].keys():
researchers_dict[uni][topic_num] = [[name, topic_val]]
else:
researchers_dict[uni][topic_num].append([name, topic_val])
```
### Order researchers in descending order by topic (within each university)
```
topic_order
#loop through universities
researchers_order = []
for i in sorted(researchers_dict.keys()):
topics = researchers_dict[i]
for j in topic_order:
if j in topics.keys():
researchers = topics[j]
if len(researchers) == 1:
researchers_order.append(researchers[0][0])
else:
researchers.sort(key=lambda x: x[1], reverse=True)
for k in researchers:
researchers_order.append(k[0])
```
### Save author order to use in visualisation
```
with open('visualisation/author_order_final.json', 'w') as fp:
json.dump(researchers_order, fp)
```
## 7: Topic interpretation
### Extract top documents for each topic (with associated top words and titles and AK API keywords)
For each topic we extract top N words associated with that topic (this is very standard and is the same as displayed in the LDAvis visualisation)
Further, for each topic we get the titles of key articles associated with that topic - this makes topics easier to interpret
Each document has been assigned some proportion of each topic (with sum of all topic proportions within document = 1). For each topic, we ordered documents based on how much of that topic they were assigned. Then we looped through the documents extracting top 10 key article titles with the condition that if a researcher already contributed 2 papers to the top 10 key titles then we skipped their subsequent papers. This ensured that the top 10 key titles contained contributions of at least 5 researchers (as compared to trying to evaluate the meaning of a topic based on articles written by only one Turing fellow). This seemed reasonable given most topics were assigned to a number of researchers.
### Get N top words for different values of lambda (1.0, 0.6, 0.2) -- from N most frequent to N most unique
```
def calc_topic_freq(dtm, doc_topic_dists):
"""
same as LDAvis, define topic frequency by proportion of words assigned to topic
"""
doc_lengths = dtm.sum(axis=1).getA1()
topic_freq = (doc_topic_dists.T * doc_lengths).T.sum()
return topic_freq
def get_relevance(topic_freq, topic_term_dists, lambda_):
"""
function for calculating relevance
if lambda_ = 1 result is same as top N mot frequent words
if lambda_ = 0; returns list of top unique words for each topic
unique = not shared by other topics
"""
term_topic_freq = (topic_term_dists.T * topic_freq).T
term_frequency = np.sum(term_topic_freq, axis=0)
term_proportion = term_frequency / term_frequency.sum()
log_lift = np.log(topic_term_dists / term_proportion)
log_ttd = np.log(topic_term_dists)
relevance = lambda_ * log_ttd + (1 - lambda_) * log_lift
return relevance
def get_top_words(relevance, feature_names, n_top):
"""
function to extract n_top words per topic using relevance (which determines what words are ordered by)
"""
topic_top_words = {}
for idx, item in enumerate(relevance.as_matrix()):
top_words = [feature_names[i] for i in item.argsort()[:-n_top - 1:-1]]
topic_top_words[idx] = top_words
return topic_top_words
def topic_top_words(topic_term_dists, topic_num, feature_names, n_top):
"""
similar to above but returns topic info for single topic only
returns most frequent words for that topic
"""
topic_term_dist = topic_term_dists.loc[topic_num]
top_words = [feature_names[i] for i in topic_term_dist.argsort()[:-n_words - 1:-1]]
return top_words
lambdas = [1, .6, .2]
topic_freq = calc_topic_freq(dtm, doc_topic_dists)
n_top = 10
top_words_dict = {}
for lambda_ in lambdas:
relevance = get_relevance(topic_freq, topic_term_dists, lambda_)
top_words = get_top_words(relevance, feature_names, n_top)
top_words_dict[lambda_] = top_words
```
### Collate all topic info
```
#create dictionary with all information of interest for each topic
#get new order of topics
topic_doc_dict = {}
all_names = []
num_papers = 10
n_words = 15
#loop through topics
for column in doc_topic_dists:
#order docs by how much topic assigned + save indexes of top docs
doc_topic_dists = doc_topic_dists.sort_values([column], ascending = 0)
indexes = doc_topic_dists.index.values
topic_doc_dict[column] = [[indexes]]
#get top words for all 3 lambda values
top_words_10 = top_words_dict[1][column]
top_words_06 = top_words_dict[.6][column]
top_words_02 = top_words_dict[.2][column]
topic_doc_dict[column].append({1:top_words_10, .6:top_words_06, .2:top_words_02})
#loop through indexes and retrieve document information
titles, keywords, names = [], [], []
topic_names = {}
top_n = []
for i in indexes:
#if don't have asked for N papers yet
if len(titles) < num_papers:
#get paper ID and use that to retrieve remaining information
paper_id = publications_data.get_value(i, 'paper_id')
#retrieve top N article titles + associated keywords
if len(top_n) < num_papers:
to_append = [publications_data.get_value(i, 'title'), doc_topic_dists.loc[i][column]]
for name in paper_id_to_authors[paper_id]:
to_append.append(name)
top_n.append(to_append)
to_add = False
for name in paper_id_to_authors[paper_id]:
if name in topic_names.keys():
topic_names[name] += 1
else:
topic_names[name] = 1
names.append(name)
if topic_names[name] <= 2:
to_add = True
if to_add:
titles.append([publications_data.get_value(i, 'title'), doc_topic_dists.loc[i][column]])
ak_keywords = publications_data.loc[publications_data['paper_id']==paper_id]['ak_keywords'].values[0]
if type(ak_keywords) != float:
keywords += ak_keywords.split('; ')
#save all extracted information
topic_doc_dict[column].append(titles)
topic_doc_dict[column].append(list(set(keywords)))
topic_doc_dict[column].append(set(names))
all_names.extend(names)
print('Number of researchers that have been listed in at least one set of top 10 papers: ', len(set(all_names)))
```
### Inspect results
```
#print results of top 10 key article titles
n = 1
for topic in topic_order:
data = topic_doc_dict[topic]
print('Topic: ', n, "\n")
for key in data[1]:
print('Top words lambda ' + str(key) + ': ', *data[1][key], '\n')
print("Article titles:")
for i in data[2]:
print(i[0])
print(i[1],'\n')
print("AK keywords: ", *data[3], '\n')
print("Researchers: ", *data[4], '\n')
n += 1
```
## OTHER
### Re-order merged, doc_topic and topic_term distributions by overall topic size
```
def get_topic_order(dtm, doc_topic_dists):
"""
function which returns same topic order as LDAvis
"""
doc_lengths = series_with_name(dtm.sum(axis=1).getA1(), 'doc_length')
topic_freq = (doc_topic_dists.T * doc_lengths).T.sum()
topic_proportion = (topic_freq / topic_freq.sum()).sort_values(ascending=False)
return topic_proportion.index
def set_topic_order(topic_term_dists, doc_topic_dists, topic_order):
topic_term_dists = topic_term_dists.ix[topic_order]
doc_topic_dists = doc_topic_dists[topic_order]
return topic_term_dists, doc_topic_dists
def rename_topic_order(topic_term_dists, doc_topic_dists):
topic_term_dists = topic_term_dists.reset_index(drop=True)
topic_term_dists.index.name = 'topic'
doc_topic_dists.columns = [i for i in range(25)]
doc_topic_dists.columns.name = 'topic'
return topic_term_dists, doc_topic_dists
topic_order = merged.index.values
topic_term_dists, doc_topic_dists = set_topic_order(topic_term_dists, doc_topic_dists, topic_order)
topic_term_dists, doc_topic_dists = rename_topic_order(topic_term_dists, doc_topic_dists)
merged = merged.reset_index(drop=True)
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.