code stringlengths 2.5k 150k | kind stringclasses 1 value |
|---|---|
```
import os, sys, subprocess
# Colab setup ------------------
if "google.colab" in sys.modules:
# Mount drive
from google.colab import drive
print('Select your Caltech Google Account')
drive.mount('/content/drive/')
import numpy as np
import pandas as pd
from scipy.signal import filtfilt, butter
import holoviews as hv
import panel as pn
# import holoviews.operation.datashader
import bokeh
from holoviews import opts
hv.extension('bokeh', 'matplotlib')
!pip install -e drive/MyDrive/My\ Science\ Practice/13\ Dissemination\ Publication\ Outreach/ERGo/erg
import drive/MyDrive/My\ Science\ Practice/13\ Dissemination\ Publication\ Outreach/ERGo/erg
ergram = ERGio.ERG(r'../../data/BYB_Recording_2020-12-23_13.47.39.wav')
```
### Data validation: confirming that the shifted times are sawtoothed and the normal times look like a slippery staircase
```
%%opts Curve {+axiswise}
hv.Curve(
ergram.df['shifted time (s)'].values,
label='shifted'
) + hv.Curve(
ergram.df['time (s)'].values,
label='normal'
)
```
### Visualize TTL pulses for each frequency
For a specific frequency, this is where all of that frequency occurred for each color.
```
color_dict = {
'IR':'deeppink',
'R':'firebrick',
'G':'green',
'B':'blue',
'UV':'violet'
}
frequency_picker = pn.widgets.Select(
name="Frequency (Hz)",
options=sorted(list(ergram.df['theoretical frequency'].unique())),
value=8,
width=100
)
@pn.depends(frequency=frequency_picker.param.value)
def plot_stimuli_select_frequency(frequency):
return hv.NdOverlay(
{
color: hv.Curve(
data=ergram.df[
(ergram.df.color==color)
& (ergram.df['theoretical frequency']==frequency)
],
kdims=['time (s)'],
vdims=[
'TTL'
],
).opts(
color=color_dict[color],
width=600,
height=200
) for color in list(color_dict.keys())
},
kdims='Color'
).opts(
legend_position='right'
)
color_picker = pn.widgets.Select(
name="Color",
options=sorted(list(ergram.df.color.unique())),
value='R',
width=100
)
@pn.depends(color=color_picker.param.value)
def plot_stimuli_select_color(color):
return hv.NdOverlay(
{
frequency: hv.Curve(
data=ergram.df[
(ergram.df.color==color)
& (ergram.df['theoretical frequency']==frequency)
],
kdims=['time (s)'],
vdims=['TTL'],
).opts(
color=color_dict[color],
width=600,
height=200
) for frequency in list(ergram.df['theoretical frequency'].unique())
},
kdims='Color'
).opts(
legend_position='right'
)
pn.Column(frequency_picker, plot_stimuli_select_frequency, color_picker, plot_stimuli_select_color)
```
### Visualize responses to light
```
# Make a selector for the color to display
color_selector = pn.widgets.Select(
name="Color",
options=list(color_dict.keys()),
value="R",
width=100
)
# Plot the colors
@pn.depends(color=color_selector.param.value)
def plot_responses(color):
return hv.Curve(
data=ergram.df[ergram.df['color']==color],
kdims=['shifted time (s)'],
vdims=[
('channel 1', 'Voltage'),
('theoretical frequency', 'frequency (Hz)')
]
).groupby(
['theoretical frequency']
).layout(
'theoretical frequency'
).opts(
opts.Curve(
line_width=2,
color=color_dict[color],
xaxis=None, yaxis=None
)
).cols(5)
pn.Column(color_selector, plot_responses)
```
So this is kind of interesting. Toward the end of the end of stimulation, especially with prolonged periods of stimulation (e.g., at high frequencies or low frequencies), you get some movement artifact. I saw the cockroaches really seem to not like that- they would squirm a lot. Another observation which I think is even more important, at around the halfway point, you see some short upward notch.
```
def RMS(arr):
# mean-center
arr -= np.mean(arr)
# Square
squared = arr ** 2
# Mean
mean_squared = np.mean(squared)
# Root
root_mean_squared = np.sqrt(mean_squared)
return root_mean_squared
RMS_df = ergram.df.groupby(
['trial', 'color', 'theoretical frequency']
).agg(
lambda x: RMS(x['channel 1'])
).reset_index()
RMS_df['power'] = RMS_df[0]
```
TODO: make color a numerical thing so you can make it the x-axid
```
hv.Curve(
data=RMS_df,
kdims='theoretical frequency', # consider making this actual frequency
vdims=['power','color'],
).groupby(
'color'
).overlay('color')
```
| github_jupyter |
### Seminar: Spectrogram Madness

#### Today you're finally gonna deal with speech! We'll walk you through all the main steps of speech processing pipeline and you'll get to do voice-warping. It's gonna be fun! ....and creepy. Very creepy.
```
from IPython.display import display, Audio
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import librosa
display(Audio("sample1.wav"))
display(Audio("sample2.wav"))
display(Audio("welcome.wav"))
amplitudes, sample_rate = librosa.core.load("sample1.wav")
display(Audio(amplitudes, rate=sample_rate))
print(sample_rate)
print("Length: {} seconds at sample rate {}".format(amplitudes.shape[0] / sample_rate, sample_rate))
plt.figure(figsize=[16, 4])
plt.title("First 10^4 out of {} amplitudes".format(len(amplitudes)))
plt.plot(amplitudes[:10000]);
```
### Task 1: Mel-Spectrogram (5 points)
As you can see, amplitudes follow a periodic patterns with different frequencies. However, it is very difficult to process these amplitudes directly because there's so many of them! A typical WAV file contains 22050 amplitudes per second, which is already way above a typical sequence length for other NLP applications. Hence, we need to compress this information to something manageable.
A typical solution is to use __spectrogram:__ instead of saving thousands of amplitudes, we can perform Fourier transformation to find which periodics are prevalent at each point in time. More formally, a spectrogram applies [Short-Time Fourier Transform (STFT)](https://en.wikipedia.org/wiki/Short-time_Fourier_transform) to small overlapping windows of the amplitude time-series:
<img src="https://www.researchgate.net/profile/Phillip_Lobel/publication/267827408/figure/fig2/AS:295457826852866@1447454043380/Spectrograms-and-Oscillograms-This-is-an-oscillogram-and-spectrogram-of-the-boatwhistle.png" width="480px">
However, this spectrogram may have extraordinarily large numbers that can break down neural networks. Therefore the standard approach is to convert spectrogram into a __mel-spectrogram__ by changing frequencies to [Mel-frequency spectrum(https://en.wikipedia.org/wiki/Mel-frequency_cepstrum)].
Hence, the algorithm to compute spectrogram of amplitudes $y$ becomes:
1. Compute Short-Time Fourier Transform (STFT): apply fourier transform to overlapping windows
2. Build a spectrogram: $S_{ij} = abs(STFT(y)_{ij}^2)$
3. Convert spectrogram to a Mel basis
```
# Some helpers:
# 1. slice time-series into overlapping windows
def slice_into_frames(amplitudes, window_length, hop_length):
return librosa.core.spectrum.util.frame(
np.pad(amplitudes, int(window_length // 2), mode='reflect'),
frame_length=window_length, hop_length=hop_length)
# output shape: [window_length, num_windows]
dummy_amps = amplitudes[2048: 6144]
dummy_frames = slice_into_frames(dummy_amps, 2048, 512)
print(amplitudes.shape)
plt.figure(figsize=[16, 4])
plt.subplot(121, title='Whole audio sequence', ylim=[-3, 3])
plt.plot(dummy_amps)
plt.subplot(122, title='Overlapping frames', yticks=[])
for i, frame in enumerate(dummy_frames.T):
plt.plot(frame + 10 - i);
# 2. Weights for window transform. Before performing FFT you can scale amplitudes by a set of weights
# The weights we're gonna use are large in the middle of the window and small on the sides
dummy_window_length = 3000
dummy_weights_window = librosa.core.spectrum.get_window('hann', dummy_window_length, fftbins=True)
plt.plot(dummy_weights_window); plt.plot([1500, 1500], [0, 1.1], label='window center'); plt.legend()
# 3. Fast Fourier Transform in Numpy. Note: this function can process several inputs at once (mind the axis!)
dummy_fft = np.fft.rfft(dummy_amps[:3000, None] * dummy_weights_window[:, None], axis=0) # complex[sequence_length, num_sequences]
plt.plot(np.real(dummy_fft)[:, 0])
print(dummy_fft.shape)
```
Okay, now it's time to combine everything into a __S__hort-__T__ime __F__ourier __T__ransform
```
def get_STFT(amplitudes, window_length, hop_length):
""" Compute short-time Fourier Transform """
# slice amplitudes into overlapping frames [window_length, num_frames]
frames = slice_into_frames(amplitudes, window_length, hop_length)
# get weights for fourier transform, float[window_length]
weights_window = <YOUR CODE>
# apply fourier transfrorm to frames scaled by weights
stft = <YOUR CODE>
return stft
stft = get_STFT(amplitudes, window_length=2048, hop_length=512)
plt.plot(abs(stft)[0])
def get_spectrogram(amplitudes, sample_rate=22050, n_mels=128,
window_length=2048, hop_length=512, fmin=1, fmax=8192):
"""
Implement mel-spectrogram as described above.
:param amplitudes: float [num_amplitudes], time-series of sound amplitude, same as above
:param sample rate: num amplitudes per second
:param n_mels: spectrogram channels
:param window_length: length of a patch to which you apply FFT
:param hop_length: interval between consecutive windows
:param f_min: minimal frequency
:param f_max: maximal frequency
:returns: mel-spetrogram [n_mels, duration]
"""
# Step I: compute Short-Time Fourier Transform
stft = <YOUR CODE>
assert stft.shape == (window_length // 2 + 1, len(amplitudes) // hop_length + 1)
# Step II: convert stft to a spectrogram
spectrogram = <YOUR CODE>
return spectrogram
```
#### The Mel Basis
The Mel-scale is a perceptual scale which represents how sensitive humans are to various sounds. We will use it to compress and transform our spectrograms.
```
mel_basis = librosa.filters.mel(22050, n_fft=2048,
n_mels=128, fmin=1, fmax=8192)
plt.figure(figsize=[16, 10])
plt.title("Mel Basis"); plt.xlabel("Frequence"); plt.ylabel("Mel-Basis")
plt.imshow(np.log(mel_basis),origin='lower', cmap=plt.cm.hot,interpolation='nearest', aspect='auto')
plt.colorbar(use_gridspec=True)
# Can
mat= np.matmul(mel_basis.T, mel_basis)
plt.figure(figsize=[16, 10])
plt.title("recovered frequence Basis"); plt.xlabel("Frequence"); plt.ylabel("Frequency")
plt.imshow(np.log(mat),origin='lower', cmap=plt.cm.hot,interpolation='nearest', aspect='auto')
plt.colorbar(use_gridspec=True)
def get_melspectrogram(amplitudes, sample_rate=22050, n_mels=128,
window_length=2048, hop_length=512, fmin=1, fmax=8192):
spectrogram = get_spectrogram(amplitudes, sample_rate=sample_rate, n_mels=n_mels,
window_length=window_length, hop_length=hop_length, fmin=fmin, fmax=fmax)
# Step III: convert spectrogram into Mel basis (multiplying by transformation matrix)
mel_basis = librosa.filters.mel(sample_rate, n_fft=window_length,
n_mels=n_mels, fmin=fmin, fmax=fmax)
# -- matrix [n_mels, window_length / 2 + 1]
mel_spectrogram = <YOUR_CODE>
assert mel_spectrogram.shape == (n_mels, len(amplitudes) // hop_length + 1)
return mel_spectrogram
amplitudes1, s1 = librosa.core.load("./sample1.wav")
amplitudes2, s2 = librosa.core.load("./sample2.wav")
print(s1)
ref1 = librosa.feature.melspectrogram(amplitudes1, sr=sample_rate, n_mels=128, fmin=1, fmax=8192)
ref2 = librosa.feature.melspectrogram(amplitudes2, sr=sample_rate, n_mels=128, fmin=1, fmax=8192)
assert np.allclose(get_melspectrogram(amplitudes1), ref1, rtol=1e-4, atol=1e-4)
assert np.allclose(get_melspectrogram(amplitudes2), ref2, rtol=1e-4, atol=1e-4)
plt.figure(figsize=[16, 4])
plt.subplot(1, 2, 1)
plt.title("That's no moon - it's a space station!"); plt.xlabel("Time"); plt.ylabel("Frequency")
plt.imshow(np.log10(get_melspectrogram(amplitudes1)),origin='lower', vmin=-10, vmax=5, cmap=plt.cm.hot)
plt.colorbar(use_gridspec=True)
plt.subplot(1, 2, 2)
plt.title("Help me, Obi Wan Kenobi. You're my only hope."); plt.xlabel("Time"); plt.ylabel("Frequency")
plt.imshow(np.log10(get_melspectrogram(amplitudes2)),origin='lower', vmin=-10, vmax=5, cmap=plt.cm.hot);
plt.colorbar(use_gridspec=True)
# note that the second spectrogram has higher mean frequency corresponding to the difference in gender
```
### Task 2 - Griffin-Lim Algorithm - 5 Points
In this task you are going to reconstruct the original audio signal from a spectrogram using the __Griffin-Lim Algorithm (GLA)__ . The Griffin-Lim Algorithm is a phase reconstruction method based on the redundancy of the short-time Fourier transform. It promotes the consistency of a spectrogram by iterating two projections, where a spectrogram is said to be consistent when its inter-bin dependency owing to the redundancy of STFT is retained. GLA is based only on the consistency and does not take any prior knowledge about the target signal into account.
This algorithm expects to recover a __complex-valued spectrogram__, which is consistent and maintains the given amplitude $\mathbf{A}$, by the following alternative projection procedure. Initialize a random "reconstruced" signal $\mathbf{x}$, and obtain it's STFT
$$\mathbf{X} = \text{STFT}(\mathbf{x})$$
Then we __discard__ the magnitude of $\mathbf{X}$ and keep only a random phase $\mathbf{\phi}$. Using the phase and the given magnitude $\mathbf{A}$ we construct a new complex value spectrogram $ \mathbf{\tilde X}$ using the euler equation
$$\mathbf{\tilde X} = \mathbf{A}\cdot e^{j\mathbf{\phi}}$$
Then we reconstruct the signal $\mathbf{\tilde x}$ using an __inverse STFT__:
$$\mathbf{\tilde x} = \text{iSTFT}(\mathbf{\tilde X})$$
We update our value of the signal reconstruction:
$$ \mathbf{x} = \mathbf{\tilde x} $$
Finally, we interate this procedure multiple times and return the final $$\mathbf{x}$$.
```
# STEP 1: Reconstruct your Spectrogram from the Mel-Spectrogram
def inv_mel_spectrogram(mel_spectrogram, sample_rate=22050, n_mels=128,
window_length=2048, hop_length=512, fmin=1, fmax=8192):
mel_basis = librosa.filters.mel(sample_rate, n_fft=window_length,
n_mels=n_mels, fmin=fmin, fmax=fmax)
inv_mel_basis = <INSERT YOUR CODE>
spectrogram = <INSERT YOUT CODE>
return spectrogram
amplitudes, sample_rate = librosa.core.load("welcome.wav")
display(Audio(amplitudes, rate=sample_rate))
true_spec = get_spectrogram(amplitudes)
mel_spec = get_melspectrogram(amplitudes, window_length=2048, hop_length=512)
#!!! Here you can modify your Mel-Spectrogram. Let your twisted imagination fly wild here !!!
#mel_spec[40:50,:]=0 # Zero out some freqs
# mel_spec[10:124,:] = mel_spec[0:114,:] # #Pitch-up
# mel_spec[0:10,:]=0
# mel_spec[0:114,:] = mel_spec[10:124,:] # #Pitch-down
# mel_spec[114:124,:]=0
#mel_spec[:,:] = mel_spec[:,::-1] #Time reverse
#mel_spec[64:,:] = mel_spec[:64,:] # Trippy Shit
#mel_spec[:,:] = mel_spec[::-1,:] # Aliens are here
#mel_spec[64:,:] = mel_spec[:64,:] # Trippy Shit
#mel_spec[:,:] = mel_spec[::-1,::-1] # Say hello to your friendly neighborhood Chaos God
#!!! END MADNESS !!!
#Convert Back to Spec
spec = inv_mel_spectrogram(mel_spec, window_length=2048, hop_length=512)
scale_1 = 1.0 / np.amax(mel_spec)
scale_1 = 1.0 / np.amax(true_spec)
scale_2 = 1.0 / np.amax(spec)
plt.figure(figsize=[16, 4])
plt.subplot(1, 2, 1)
plt.title("Welcome...!"); plt.xlabel("Time"); plt.ylabel("Frequency")
plt.imshow((true_spec*scale_1)**0.125,origin='lower',interpolation='nearest', cmap=plt.cm.hot, aspect='auto')
plt.colorbar(use_gridspec=True)
plt.subplot(1, 2, 2)
plt.title("Xkdfsas...!"); plt.xlabel("Time"); plt.ylabel("Frequency")
plt.imshow((spec*scale_2)**0.125,origin='lower',interpolation='nearest', cmap=plt.cm.hot, aspect='auto')
plt.colorbar(use_gridspec=True)
plt.figure(figsize=[16, 10])
plt.title("Xkdfsas...!"); plt.xlabel("Time"); plt.ylabel("Frequency")
plt.imshow((mel_spec**0.125),origin='lower',interpolation='nearest', cmap=plt.cm.hot, aspect='auto')
plt.colorbar(use_gridspec=True)
# Lets examine how to take an inverse FFT
dummy_window_length = 3000
dummy_weights_window = librosa.core.spectrum.get_window('hann', dummy_window_length, fftbins=True)
dummy_fft = np.fft.rfft(dummy_amps[:3000, None] * dummy_weights_window[:, None], axis=0) # complex[sequence_length, num_sequences]
print(dummy_fft.shape)
rec_dummy_amps = dummy_weights_window*np.real(np.fft.irfft(dummy_fft[:,0]))
plt.plot(dummy_amps[:3000])
plt.plot(rec_dummy_amps[:3000])
plt.legend(['Original', 'Reconstructed'])
# Step II: Reconstruct amplitude samples from STFT
def get_iSTFT(spectrogram, window_length, hop_length):
""" Compute inverse short-time Fourier Transform """
# get weights for fourier transform, float[window_length]
window = librosa.core.spectrum.get_window('hann', window_length, fftbins=True)
time_slices = spectrogram.shape[1]
len_samples = int(time_slices*hop_length+window_length)
x = np.zeros(len_samples)
# apply inverse fourier transfrorm to frames scaled by weights and save into x
amplitudes = <YOUR CODE>
# Trim the array to correct length from both sides
x = <YOUR_CODE>
return x
# Step III: Implement the Griffin-Lim Algorithm
def griffin_lim(power_spectrogram, window_size, hop_length, iterations, seed=1, verbose=True):
"""Reconstruct an audio signal from a magnitude spectrogram.
Given a power spectrogram as input, reconstruct
the audio signal and return it using the Griffin-Lim algorithm from the paper:
"Signal estimation from modified short-time fourier transform" by Griffin and Lim,
in IEEE transactions on Acoustics, Speech, and Signal Processing. Vol ASSP-32, No. 2, April 1984.
Args:
power_spectrogram (2-dim Numpy array): The power spectrogram. The rows correspond to the time slices
and the columns correspond to frequency bins.
window_size (int): The FFT size, which should be a power of 2.
hop_length (int): The hope size in samples.
iterations (int): Number of iterations for the Griffin-Lim algorithm. Typically a few hundred
is sufficient.
Returns:
The reconstructed time domain signal as a 1-dim Numpy array.
"""
time_slices = power_spectrogram.shape[1]
len_samples = int(time_slices*hop_length-hop_length)
# Obtain STFT magnitude from Spectrogram
magnitude_spectrogram = <YOUR CODE>
# Initialize the reconstructed signal to noise.
np.random.seed(seed)
x_reconstruct = np.random.randn(len_samples)
for n in range(iterations):
# Get the SFTF of a random signal
reconstruction_spectrogram = <YOUR_CODE>
# Obtain the angle part of random STFT. Hint: unit np.angle
reconstruction_angle = <YOUR_CODE>
# Discard magnitude part of the reconstruction and use the supplied magnitude spectrogram instead.
proposal_spectrogram = <YOUR_CODE>
assert proposal_spectrogram.dtype == np.complex
# Save previous construction
prev_x = x_reconstruct
# Reconstruct signal
x_reconstruct = <YOUR CODE>
# Measure RMSE
diff = np.sqrt(sum((x_reconstruct - prev_x)**2)/x_reconstruct.size)
if verbose:
# HINT: This should decrease over multiple iterations. If its not, your code doesn't work right!
# Use this to debug your code!
print('Reconstruction iteration: {}/{} RMSE: {} '.format(n, iterations, diff))
return x_reconstruct
rec_amplitudes1 = griffin_lim(true_spec, 2048, 512, 1, verbose=False)
display(Audio(rec_amplitudes1, rate=sample_rate))
rec_amplitudes2 = griffin_lim(true_spec, 2048, 512, 50, verbose=False)
display(Audio(rec_amplitudes2, rate=sample_rate))
rec_amplitudes3 = griffin_lim(spec, 2048, 512, 1, verbose=False)
display(Audio(rec_amplitudes3, rate=sample_rate))
rec_amplitudes4 = griffin_lim(spec, 2048, 512, 50, verbose=False)
display(Audio(rec_amplitudes4, rate=sample_rate))
# THIS IS AN EXAMPLE OF WHAT YOU ARE SUPPORT TO GET
# Remember to apply sqrt to spectrogram to get magnitude, note power here.
# Let's try this on a real spectrogram
ref_amplitudes1 = librosa.griffinlim(np.sqrt(true_spec), n_iter=1, hop_length=512, win_length=2048)
display(Audio(ref_amplitudes1, rate=sample_rate))
ref_amplitudes2 = librosa.griffinlim(np.sqrt(true_spec), n_iter=50, hop_length=512, win_length=2048)
display(Audio(ref_amplitudes2, rate=sample_rate))
# Not let's try this on a reconstructed spectrogram
ref_amplitudes3 = librosa.griffinlim(np.sqrt(spec), n_iter=1, hop_length=512, win_length=2048)
display(Audio(ref_amplitudes3, rate=sample_rate))
ref_amplitudes4 = librosa.griffinlim(np.sqrt(spec), n_iter=50, hop_length=512, win_length=2048)
display(Audio(ref_amplitudes4, rate=sample_rate))
```
| github_jupyter |
# Deep Q-learning
In this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use Q-learning to train an agent to play a game called [Cart-Pole](https://gym.openai.com/envs/CartPole-v0). In this game, a freely swinging pole is attached to a cart. The cart can move to the left and right, and the goal is to keep the pole upright as long as possible.

We can simulate this game using [OpenAI Gym](https://gym.openai.com/). First, let's check out how OpenAI Gym works. Then, we'll get into training an agent to play the Cart-Pole game.
```
import gym
import tensorflow as tf
import numpy as np
```
>**Note:** Make sure you have OpenAI Gym cloned into the same directory with this notebook. I've included `gym` as a submodule, so you can run `git submodule --init --recursive` to pull the contents into the `gym` repo.
```
# Create the Cart-Pole game environment
env = gym.make('CartPole-v0')
```
We interact with the simulation through `env`. To show the simulation running, you can use `env.render()` to render one frame. Passing in an action as an integer to `env.step` will generate the next step in the simulation. You can see how many actions are possible from `env.action_space` and to get a random action you can use `env.action_space.sample()`. This is general to all Gym games. In the Cart-Pole game, there are two possible actions, moving the cart left or right. So there are two actions we can take, encoded as 0 and 1.
Run the code below to watch the simulation run.
```
env.reset()
rewards = []
for _ in range(100):
env.render()
state, reward, done, info = env.step(env.action_space.sample()) # take a random action
rewards.append(reward)
if done:
rewards = []
env.reset()
```
To shut the window showing the simulation, use `env.close()`.
If you ran the simulation above, we can look at the rewards:
```
print(rewards[-20:])
```
The game resets after the pole has fallen past a certain angle. For each frame while the simulation is running, it returns a reward of 1.0. The longer the game runs, the more reward we get. Then, our network's goal is to maximize the reward by keeping the pole vertical. It will do this by moving the cart to the left and the right.
## Q-Network
We train our Q-learning agent using the Bellman Equation:
$$
Q(s, a) = r + \gamma \max{Q(s', a')}
$$
where $s$ is a state, $a$ is an action, and $s'$ is the next state from state $s$ and action $a$.
Before we used this equation to learn values for a Q-_table_. However, for this game there are a huge number of states available. The state has four values: the position and velocity of the cart, and the position and velocity of the pole. These are all real-valued numbers, so ignoring floating point precisions, you practically have infinite states. Instead of using a table then, we'll replace it with a neural network that will approximate the Q-table lookup function.
<img src="assets/deep-q-learning.png" width=450px>
Now, our Q value, $Q(s, a)$ is calculated by passing in a state to the network. The output will be Q-values for each available action, with fully connected hidden layers.
<img src="assets/q-network.png" width=550px>
As I showed before, we can define our targets for training as $\hat{Q}(s,a) = r + \gamma \max{Q(s', a')}$. Then we update the weights by minimizing $(\hat{Q}(s,a) - Q(s,a))^2$.
For this Cart-Pole game, we have four inputs, one for each value in the state, and two outputs, one for each action. To get $\hat{Q}$, we'll first choose an action, then simulate the game using that action. This will get us the next state, $s'$, and the reward. With that, we can calculate $\hat{Q}$ then pass it back into the $Q$ network to run the optimizer and update the weights.
Below is my implementation of the Q-network. I used two fully connected layers with ReLU activations. Two seems to be good enough, three might be better. Feel free to try it out.
```
class QNetwork:
def __init__(self, learning_rate=0.01, state_size=4,
action_size=2, hidden_size=10,
name='QNetwork'):
# state inputs to the Q-network
with tf.variable_scope(name):
self.inputs_ = tf.placeholder(tf.float32, [None, state_size], name='inputs')
# One hot encode the actions to later choose the Q-value for the action
self.actions_ = tf.placeholder(tf.int32, [None], name='actions')
one_hot_actions = tf.one_hot(self.actions_, action_size)
# Target Q values for training
self.targetQs_ = tf.placeholder(tf.float32, [None], name='target')
# ReLU hidden layers
self.fc1 = tf.contrib.layers.fully_connected(self.inputs_, hidden_size)
self.fc2 = tf.contrib.layers.fully_connected(self.fc1, hidden_size)
# Linear output layer
self.output = tf.contrib.layers.fully_connected(self.fc2, action_size,
activation_fn=None)
### Train with loss (targetQ - Q)^2
# output has length 2, for two actions. This next line chooses
# one value from output (per row) according to the one-hot encoded actions.
self.Q = tf.reduce_sum(tf.multiply(self.output, one_hot_actions), axis=1)
self.loss = tf.reduce_mean(tf.square(self.targetQs_ - self.Q))
self.opt = tf.train.AdamOptimizer(learning_rate).minimize(self.loss)
```
## Experience replay
Reinforcement learning algorithms can have stability issues due to correlations between states. To reduce correlations when training, we can store the agent's experiences and later draw a random mini-batch of those experiences to train on.
Here, we'll create a `Memory` object that will store our experiences, our transitions $<s, a, r, s'>$. This memory will have a maxmium capacity, so we can keep newer experiences in memory while getting rid of older experiences. Then, we'll sample a random mini-batch of transitions $<s, a, r, s'>$ and train on those.
Below, I've implemented a `Memory` object. If you're unfamiliar with `deque`, this is a double-ended queue. You can think of it like a tube open on both sides. You can put objects in either side of the tube. But if it's full, adding anything more will push an object out the other side. This is a great data structure to use for the memory buffer.
```
from collections import deque
class Memory():
def __init__(self, max_size = 1000):
self.buffer = deque(maxlen=max_size)
def add(self, experience):
self.buffer.append(experience)
def sample(self, batch_size):
idx = np.random.choice(np.arange(len(self.buffer)),
size=batch_size,
replace=False)
return [self.buffer[ii] for ii in idx]
```
## Exploration - Exploitation
To learn about the environment and rules of the game, the agent needs to explore by taking random actions. We'll do this by choosing a random action with some probability $\epsilon$ (epsilon). That is, with some probability $\epsilon$ the agent will make a random action and with probability $1 - \epsilon$, the agent will choose an action from $Q(s,a)$. This is called an **$\epsilon$-greedy policy**.
At first, the agent needs to do a lot of exploring. Later when it has learned more, the agent can favor choosing actions based on what it has learned. This is called _exploitation_. We'll set it up so the agent is more likely to explore early in training, then more likely to exploit later in training.
## Q-Learning training algorithm
Putting all this together, we can list out the algorithm we'll use to train the network. We'll train the network in _episodes_. One *episode* is one simulation of the game. For this game, the goal is to keep the pole upright for 195 frames. So we can start a new episode once meeting that goal. The game ends if the pole tilts over too far, or if the cart moves too far the left or right. When a game ends, we'll start a new episode. Now, to train the agent:
* Initialize the memory $D$
* Initialize the action-value network $Q$ with random weights
* **For** episode = 1, $M$ **do**
* **For** $t$, $T$ **do**
* With probability $\epsilon$ select a random action $a_t$, otherwise select $a_t = \mathrm{argmax}_a Q(s,a)$
* Execute action $a_t$ in simulator and observe reward $r_{t+1}$ and new state $s_{t+1}$
* Store transition $<s_t, a_t, r_{t+1}, s_{t+1}>$ in memory $D$
* Sample random mini-batch from $D$: $<s_j, a_j, r_j, s'_j>$
* Set $\hat{Q}_j = r_j$ if the episode ends at $j+1$, otherwise set $\hat{Q}_j = r_j + \gamma \max_{a'}{Q(s'_j, a')}$
* Make a gradient descent step with loss $(\hat{Q}_j - Q(s_j, a_j))^2$
* **endfor**
* **endfor**
## Hyperparameters
One of the more difficult aspects of reinforcememt learning are the large number of hyperparameters. Not only are we tuning the network, but we're tuning the simulation.
```
train_episodes = 1000 # max number of episodes to learn from
max_steps = 200 # max steps in an episode
gamma = 0.99 # future reward discount
# Exploration parameters
explore_start = 1.0 # exploration probability at start
explore_stop = 0.01 # minimum exploration probability
decay_rate = 0.0001 # exponential decay rate for exploration prob
# Network parameters
hidden_size = 64 # number of units in each Q-network hidden layer
learning_rate = 0.0001 # Q-network learning rate
# Memory parameters
memory_size = 10000 # memory capacity
batch_size = 20 # experience mini-batch size
pretrain_length = batch_size # number experiences to pretrain the memory
tf.reset_default_graph()
mainQN = QNetwork(name='main', hidden_size=hidden_size, learning_rate=learning_rate)
```
## Populate the experience memory
Here I'm re-initializing the simulation and pre-populating the memory. The agent is taking random actions and storing the transitions in memory. This will help the agent with exploring the game.
```
# Initialize the simulation
env.reset()
# Take one random step to get the pole and cart moving
state, reward, done, _ = env.step(env.action_space.sample())
memory = Memory(max_size=memory_size)
# Make a bunch of random actions and store the experiences
for ii in range(pretrain_length):
# Uncomment the line below to watch the simulation
# env.render()
# Make a random action
action = env.action_space.sample()
next_state, reward, done, _ = env.step(action)
if done:
# The simulation fails so no next state
next_state = np.zeros(state.shape)
# Add experience to memory
memory.add((state, action, reward, next_state))
# Start new episode
env.reset()
# Take one random step to get the pole and cart moving
state, reward, done, _ = env.step(env.action_space.sample())
else:
# Add experience to memory
memory.add((state, action, reward, next_state))
state = next_state
```
## Training
Below we'll train our agent. If you want to watch it train, uncomment the `env.render()` line. This is slow because it's rendering the frames slower than the network can train. But, it's cool to watch the agent get better at the game.
```
# Now train with experiences
saver = tf.train.Saver()
rewards_list = []
with tf.Session() as sess:
# Initialize variables
sess.run(tf.global_variables_initializer())
step = 0
for ep in range(1, train_episodes):
total_reward = 0
t = 0
while t < max_steps:
step += 1
# Uncomment this next line to watch the training
# env.render()
# Explore or Exploit
explore_p = explore_stop + (explore_start - explore_stop)*np.exp(-decay_rate*step)
if explore_p > np.random.rand():
# Make a random action
action = env.action_space.sample()
else:
# Get action from Q-network
feed = {mainQN.inputs_: state.reshape((1, *state.shape))}
Qs = sess.run(mainQN.output, feed_dict=feed)
action = np.argmax(Qs)
# Take action, get new state and reward
next_state, reward, done, _ = env.step(action)
total_reward += reward
if done:
# the episode ends so no next state
next_state = np.zeros(state.shape)
t = max_steps
print('Episode: {}'.format(ep),
'Total reward: {}'.format(total_reward),
'Training loss: {:.4f}'.format(loss),
'Explore P: {:.4f}'.format(explore_p))
rewards_list.append((ep, total_reward))
# Add experience to memory
memory.add((state, action, reward, next_state))
# Start new episode
env.reset()
# Take one random step to get the pole and cart moving
state, reward, done, _ = env.step(env.action_space.sample())
else:
# Add experience to memory
memory.add((state, action, reward, next_state))
state = next_state
t += 1
# Sample mini-batch from memory
batch = memory.sample(batch_size)
states = np.array([each[0] for each in batch])
actions = np.array([each[1] for each in batch])
rewards = np.array([each[2] for each in batch])
next_states = np.array([each[3] for each in batch])
# Train network
target_Qs = sess.run(mainQN.output, feed_dict={mainQN.inputs_: next_states})
# Set target_Qs to 0 for states where episode ends
episode_ends = (next_states == np.zeros(states[0].shape)).all(axis=1)
target_Qs[episode_ends] = (0, 0)
targets = rewards + gamma * np.max(target_Qs, axis=1)
loss, _ = sess.run([mainQN.loss, mainQN.opt],
feed_dict={mainQN.inputs_: states,
mainQN.targetQs_: targets,
mainQN.actions_: actions})
saver.save(sess, "checkpoints/cartpole.ckpt")
```
## Visualizing training
Below I'll plot the total rewards for each episode. I'm plotting the rolling average too, in blue.
```
%matplotlib inline
import matplotlib.pyplot as plt
def running_mean(x, N):
cumsum = np.cumsum(np.insert(x, 0, 0))
return (cumsum[N:] - cumsum[:-N]) / N
eps, rews = np.array(rewards_list).T
smoothed_rews = running_mean(rews, 10)
plt.plot(eps[-len(smoothed_rews):], smoothed_rews)
plt.plot(eps, rews, color='grey', alpha=0.3)
plt.xlabel('Episode')
plt.ylabel('Total Reward')
```
## Testing
Let's checkout how our trained agent plays the game.
```
test_episodes = 10
test_max_steps = 400
env.reset()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
for ep in range(1, test_episodes):
t = 0
while t < test_max_steps:
env.render()
# Get action from Q-network
feed = {mainQN.inputs_: state.reshape((1, *state.shape))}
Qs = sess.run(mainQN.output, feed_dict=feed)
action = np.argmax(Qs)
# Take action, get new state and reward
next_state, reward, done, _ = env.step(action)
if done:
t = test_max_steps
env.reset()
# Take one random step to get the pole and cart moving
state, reward, done, _ = env.step(env.action_space.sample())
else:
state = next_state
t += 1
env.close()
```
## Extending this
So, Cart-Pole is a pretty simple game. However, the same model can be used to train an agent to play something much more complicated like Pong or Space Invaders. Instead of a state like we're using here though, you'd want to use convolutional layers to get the state from the screen images.

I'll leave it as a challenge for you to use deep Q-learning to train an agent to play Atari games. Here's the original paper which will get you started: http://www.davidqiu.com:8888/research/nature14236.pdf.
| github_jupyter |
# NASA Data Exploration
```
raw_data_dir = '../data/raw'
processed_data_dir = '../data/processed'
figsize_width = 12
figsize_height = 8
output_dpi = 72
# Imports
import os
import numpy as np
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
# Load Data
nasa_temp_file = os.path.join(raw_data_dir, 'nasa_temperature_anomaly.txt')
nasa_sea_file = os.path.join(raw_data_dir, 'nasa_sea_level.txt')
nasa_co2_file = os.path.join(raw_data_dir, 'nasa_carbon_dioxide_levels.txt')
# Variable Setup
default_fig_size = (figsize_width, figsize_height)
# - Process temperature data
temp_data = pd.read_csv(nasa_temp_file, sep='\t', header=None)
temp_data.columns = ['Year', 'Annual Mean', 'Lowness Smoothing']
temp_data.set_index('Year', inplace=True)
fig, ax = plt.subplots(figsize=default_fig_size)
temp_data.plot(ax=ax)
ax.grid(True, linestyle='--', color='grey', alpha=0.6)
ax.set_title('Global Temperature Anomaly Data', fontweight='bold')
ax.set_xlabel('')
ax.set_ylabel('Temperature Anomaly ($\degree$C)')
ax.legend()
plt.show();
# - Process Sea-level File
# -- Figure out header rows
with open(nasa_sea_file, 'r') as fin:
all_lines = fin.readlines()
header_lines = np.array([1 for x in all_lines if x.startswith('HDR')]).sum()
sea_level_data = pd.read_csv(nasa_sea_file, delim_whitespace=True,
skiprows=header_lines-1).reset_index()
sea_level_data.columns = ['Altimeter Type', 'File Cycle', 'Year Fraction',
'N Observations', 'N Weighted Observations', 'GMSL',
'Std GMSL', 'GMSL (smoothed)', 'GMSL (GIA Applied)',
'Std GMSL (GIA Applied)', 'GMSL (GIA, smoothed)',
'GMSL (GIA, smoothed, filtered)']
sea_level_data.set_index('Year Fraction', inplace=True)
fig, ax = plt.subplots(figsize=default_fig_size)
sea_level_var = sea_level_data.loc[:, 'GMSL (GIA, smoothed, filtered)'] \
- sea_level_data.loc[:, 'GMSL (GIA, smoothed, filtered)'].iloc[0]
sea_level_var.plot(ax=ax)
ax.grid(True, color='grey', alpha=0.6, linestyle='--')
ax.set_title('Global Sea-Level Height Change over Time', fontweight='bold')
ax.set_xlabel('')
ax.set_ylabel('Sea Height Change (mm)')
ax.legend(loc='upper left')
plt.show();
# - Process Carbon Dioxide Data
with open(nasa_co2_file, 'r') as fin:
all_lines = fin.readlines()
header_lines = np.array([1 for x in all_lines if x.startswith('#')]).sum()
co2_data = pd.read_csv(nasa_co2_file, skiprows=header_lines, header=None,
delim_whitespace=True)
co2_data[co2_data == -99.99] = np.nan
co2_data.columns = ['Year', 'Month', 'Year Fraction', 'Average', 'Interpolated',
'Trend', 'N Days']
co2_data.set_index(['Year', 'Month'], inplace=True)
new_idx = [datetime(x[0], x[1], 1) for x in co2_data.index]
co2_data.index = new_idx
co2_data.index.name = 'Date'
# - Plot
fig, ax = plt.subplots(figsize=default_fig_size)
co2_data.loc[:, 'Average'].plot(ax=ax)
ax.grid(True, linestyle='--', color='grey', alpha=0.6)
ax.set_xlabel('')
ax.set_ylabel('$CO_2$ Level (ppm)')
ax.set_title('Global Carbon Dioxide Level over Time', fontweight='bold')
plt.show();
```
| github_jupyter |
## Predicting Survival on the Titanic
### History
Perhaps one of the most infamous shipwrecks in history, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 people on board. Interestingly, by analysing the probability of survival based on few attributes like gender, age, and social status, we can make very accurate predictions on which passengers would survive. Some groups of people were more likely to survive than others, such as women, children, and the upper-class. Therefore, we can learn about the society priorities and privileges at the time.
### Assignment:
Build a Machine Learning Pipeline, to engineer the features in the data set and predict who is more likely to Survive the catastrophe.
Follow the Jupyter notebook below, and complete the missing bits of code, to achieve each one of the pipeline steps.
```
import re
# to handle datasets
import pandas as pd
import numpy as np
# for visualization
import matplotlib.pyplot as plt
# to divide train and test set
from sklearn.model_selection import train_test_split
# feature scaling
from sklearn.preprocessing import StandardScaler
# to build the models
from sklearn.linear_model import LogisticRegression
# to evaluate the models
from sklearn.metrics import accuracy_score, roc_auc_score
# to persist the model and the scaler
import joblib
# ========== NEW IMPORTS ========
# Respect to notebook 02-Predicting-Survival-Titanic-Solution
# pipeline
from sklearn.pipeline import Pipeline
# for the preprocessors
from sklearn.base import BaseEstimator, TransformerMixin
# for imputation
from feature_engine.imputation import (AddMissingIndicator,
CategoricalImputer,
MeanMedianImputer)
# for encoding categorical variables
from feature_engine.encoding import (OneHotEncoder,
RareLabelEncoder)
# typing
from typing import List
```
## Prepare the data set
```
# load the data - it is available open source and online
data = pd.read_csv('https://www.openml.org/data/get_csv/16826755/phpMYEkMl')
# display data
data.head()
# replace interrogation marks by NaN values
data = data.replace('?', np.nan)
# retain only the first cabin if more than
# 1 are available per passenger
def get_first_cabin(row):
try:
return row.split()[0]
except:
return np.nan
data['cabin'] = data['cabin'].apply(get_first_cabin)
# extracts the title (Mr, Ms, etc) from the name variable
def get_title(passenger):
line = passenger
if re.search('Mrs', line):
return 'Mrs'
elif re.search('Mr', line):
return 'Mr'
elif re.search('Miss', line):
return 'Miss'
elif re.search('Master', line):
return 'Master'
else:
return 'Other'
data['title'] = data['name'].apply(get_title)
# cast numerical variables as floats
data['fare'] = data['fare'].astype('float')
data['age'] = data['age'].astype('float')
# drop unnecessary variables
data.drop(labels=['name','ticket', 'boat', 'body','home.dest'], axis=1, inplace=True)
# display data
data.head()
# # save the data set
# data.to_csv('titanic.csv', index=False)
```
# Begin Assignment
## Configuration
```
# list of variables to be used in the pipeline's transformers
NUMERICAL_VARIABLES = ['age', 'fare']
# The rest of the numerical variables (pclass, sibsp, parch) do not need to be transformed (add missing flag or impute values). That is why they are not included in the list.
CATEGORICAL_VARIABLES = ['sex', 'cabin', 'embarked', 'title']
CABIN = ['cabin']
```
## Separate data into train and test
```
X_train, X_test, y_train, y_test = train_test_split(
data.drop('survived', axis=1), # predictors
data['survived'], # target
test_size=0.2, # percentage of obs in test set
random_state=0) # seed to ensure reproducibility
X_train.shape, X_test.shape
```
## Preprocessors
### Class to extract the letter from the variable Cabin
```
class ExtractLetterTransformer(BaseEstimator, TransformerMixin):
# Extract fist letter of variable
def __init__(self, variables: List[str]) -> None:
self.variables = [variables] \
if not isinstance(variables, list) else variables
def fit(self, X: pd.DataFrame, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
X = X.copy()
for var in self.variables:
X[var] = X[var].str[0]
return X
```
## Pipeline
- Impute categorical variables with string missing
- Add a binary missing indicator to numerical variables with missing data
- Fill NA in original numerical variable with the median
- Extract first letter from cabin
- Group rare Categories
- Perform One hot encoding
- Scale features with standard scaler
- Fit a Logistic regression
```
# set up the pipeline
titanic_pipe = Pipeline([
# ===== IMPUTATION =====
# impute categorical variables with string 'missing'
('categorical_imputation', CategoricalImputer(variables=CATEGORICAL_VARIABLES,
imputation_method='missing')),
# add missing indicator to numerical variables
('missing_indicator', AddMissingIndicator(variables=NUMERICAL_VARIABLES)),
# impute numerical variables with the median
('median_imputation', MeanMedianImputer(variables=NUMERICAL_VARIABLES,
imputation_method='median')),
# Extract first letter from cabin
('extract_letter', ExtractLetterTransformer(variables=CABIN)),
# == CATEGORICAL ENCODING ======
# remove categories present in less than 5% of the observations (0.05)
# group them in one category called 'Rare'
('rare_label_encoder', RareLabelEncoder(variables=CATEGORICAL_VARIABLES,
tol=0.05,
n_categories=1,
replace_with='Other')),
# encode categorical variables using one hot encoding into k-1 variables
('categorical_encoder', OneHotEncoder(variables=CATEGORICAL_VARIABLES,
drop_last=True)),
# scale using standardization
('scaler', StandardScaler()),
# logistic regression (use C=0.0005 and random_state=0)
('Logit', LogisticRegression(C=5e-4,
random_state=0)),
])
# train the pipeline
titanic_pipe.fit(X_train, y_train)
```
## Make predictions and evaluate model performance
Determine:
- roc-auc
- accuracy
**Important, remember that to determine the accuracy, you need the outcome 0, 1, referring to survived or not. But to determine the roc-auc you need the probability of survival.**
```
# make predictions for train set
class_ = titanic_pipe.predict(X_train)
pred = titanic_pipe.predict_proba(X_train)[:, 1]
# determine mse and rmse
print('train roc-auc: {}'.format(roc_auc_score(y_train, pred)))
print('train accuracy: {}'.format(accuracy_score(y_train, class_)))
print()
# make predictions for test set
class_ = titanic_pipe.predict(X_test)
pred = titanic_pipe.predict_proba(X_test)[:, 1]
# determine mse and rmse
print('test roc-auc: {}'.format(roc_auc_score(y_test, pred)))
print('test accuracy: {}'.format(accuracy_score(y_test, class_)))
print()
```
That's it! Well done
**Keep this code safe, as we will use this notebook later on, to build production code, in our next assignement!!**
| github_jupyter |
# Data structures for fast infinte batching or streaming requests processing
> Here we dicuss one of the coolest use of a data structures to address one of the very natural use case scenario of a server processing streaming requests from clients in order.Usually processing these requests involve a pipeline of operations applied based on request and multiple threads are in charge of dealing with these satges of pipeline. The requests gets accessed by these threads and the threads performing operations in the later part of the pipeline will have to wait for the earlier threads to finish their execution.
The usual way to ensure the correctness of multiple threads handling the same data concurrently is use locks.The problem is framed as a producer / consumer problems , where one threads finishes its operation and become producer of the data to be worked upon by another thread, which is a consumer. These two threads needs to be synchronized.
> Note: In this blog we will discuss a "lock-free" circular queue data structure called disruptor. It was designed to be an efficient concurrent message passing datastructure.The official implementations and other discussions are available [here](https://lmax-exchange.github.io/disruptor/#_discussion_blogs_other_useful_links). This blog intends to summarise its use case and show the points where the design of the disruptor scores big.
# LOCKS ARE BAD
Whenever we have a scenario where mutliple concurrent running threads contend on a shared data structure and you need to ensure visibility of changes (i.e. a consumer thread can only get its hand over the data after the producer has processed it and put it for further processing). The usual and most common way to ensure these two requirements is to use a lock.
Locks need the operating system to arbitrate which thread has the responsibility on a shared piece of data. The operating system might schedule other processes and the software's thread may be waiting in a queue. Moreover, if other threads get scheduled by the CPU then the cache memory of the softwares's thread will be overwritten and when it finally gets access to the CPU, it may have to go as far as the main memory to get it's required data. All this adds a lot of overhead and is evident by the simple experiment of incrementing a single shared variable. In the experiment below we increment a shared variable in three different ways. In the first case, we have a single process incrementing the variable, in the second case we again have two threads, but they synchronize their way through the operation using locks.
In the third case, we have two threads which increment the variables and they synchronize their operation using atomic locks.
## SINGLE PROCESS INCREMENTING A SINGLE VARIABLE
```
import time
def single_thread():
start = time.time()
x = 0
for i in range(500000000):
x += 1
end = time.time()
return(end-start)
print(single_thread())
#another way for single threaded increment using
class SingleThreadedCounter():
def __init__(self):
self.val = 0
def increment(self):
self.val += 1
```
## TWO PROCESS INCREMENTING A SINGLE VARIABLE
```
import time
from threading import Thread, Lock
mutex = Lock()
x = 0
def thread_fcn():
global x
mutex.acquire()
for i in range(250000000):
x += 1
mutex.release()
def mutex_increment():
start = time.time()
t1 = Thread(target=thread_fcn)
t2 = Thread(target=thread_fcn)
t1.start()
t2.start()
t1.join()
t2.join()
end = time.time()
return (end-start)
print(mutex_increment())
```
> Note: As we can see that the time for performing the increment operation has gone up substantially when we would have expected it take half the time.
> Important: In the rest of the blog we will take in a very usual scenario we see in streaming request processing.
A client sends in requests to a server in a streaming fashion. The server at its end needs to process the client's request, it may have multiple stages of processing. For example, imagine the client sends in a stream of requests and the server in JSON format. Now the probable first task that the client needs to perform is to parse the JSON request.Imagine a thread being assigned to do this parsing task. It parses requests one after another and hands over the parsed request in some form to another thread which may be responsible for performing business logic for that client. Usually the data structure to manage this message passing and flow control in screaming scenario is handled by a queue data structure. The producer threads (parser thread) puts in parsed data in this queue, from which the consumer thread (the business logic thread) will read of the parsed data. Because we have two threads working concurrently on a single data structure (the queue) we can expect contention to kick in.
## WHY QUEUES ARE FLAWED
The queue could be an obvious choice for handling data communication between multiple threads, but the queue data structure is fundamentally flawed for communication between multiple threads. Imagine the case of the first two threads of the a system using a queue for data communication, the listener thread and the parsing thread. The listener thread listens to bytes from the wire and puts it in a queue and the parser thread will pick up bytes from the queue and parse it. Typically, a queue data structure will have a head field, a tail field and a size field (to tell an empty queue from a full one). The head field will be modified by the parser thread and the tail field by the parser thread. The size field though will be modified by both of the threads and it effectively makes the queue data structure having two writers.

Moreover, the entire data structure will fall in the same cache line and hence when say the listener thread modifies the tail field, the head field in another core also gets invalidated and needs to be fetched from a level 2 cache.

## CAN WE AVOID LOCKS ?
So, using a queue structure for inter-thread communication with expensive locks could cost a lot of performance for any system. Hence, we move towards a better data structure that solves the issues of synchronization among threads.
The data structure we use doesn't use locks.
The main components of the data structure are -
A. A circular buffer
B. A sequence number field which has a number indicating a specific slot in the circular buffer.
C. Each of the worker threads have their own sequence number.
The circular buffer is written to by the producers . The producer in each case updates the sequence number for each of the circular buffers. The worker threads (consumer thread) have their own sequence number indicating the slots they have consumed so far from the circular buffer.

>Note: In the design, each of the elements has a SINGLE WRITER. The producer threads of the circular ring write to the ring buffer, and its sequence number. The worker consumer threads will write their own local sequence number. No field or data have more than one writer in this data structure.
## WRITE OPERATION ON THE LOCK-FREE DATA STRUCTURE
Before writing a slot in the circular buffer, the thread has to make sure that it doesn't overwrite old bytes that have not yet been processed by the consumer thread. The consumer thread also maintains a sequence number, this number indicates the slots that have been already processed. So the producer thread before writing grabs the circular buffer's sequence number, adds one to it (mod size of the circular buffer) to get the next eligible slot for writing. But before putting in the bytes in that slot it checks with the dependent consumer thread (by reading their local sequence number) if they have processed this slot. If say the consumer has not yet processed this slot, then the producer thread goes in a busy wait till the slot is available to write to. When the slot is overwritten then the circular buffer's sequence number is updated by the producer thread. This indicates to consumer threads that they have a new slot to consume.

Writing to the circular buffers is a 2-phase commit. In the first phase, we check out a slot from the circular buffer. We can only check out a slot if it has already been consumed. This is ensured by following the logic mentioned above. Once the slot is checked out the producer writes the next byte to it. Then it sends a commit message to commit the entry by updating the circular buffer's sequence number to its next logical value(+1 mod size of the circular buffer)

## READ OPERATION ON THE LOCK_FREE DATA STRUCTURE
The consumer thread reads the slots from circular buffer -1. Before reading the next slot, it checks (read) the buffer's sequence number. This number is indicative of the slots till which the buffer can read.

## ENSURING THAT THE READS HAPPEN IN PROGRAM ORDER
There is just one piece of detail that needs to be addressed for the above data structure to work. Compilers and CPU take the liberty to reorder independent instructions for optimizations. This doesn’t have any issues in the single process case where the program’s logic integrity is maintained. But this could logic breakdown in case of multiple threads.
Imagine a typical simplified read/write to the circular buffer described above—
Say the publisher thread’s sequence of operation is indicated in black, and the consumer thread’s in brown. The publisher checks in a slot and it updates the sequence number. Then the consumer thread reads the (wrong) sequence number of the buffer and goes on to access the slot which is yet to be written.

The way we could solve this is by putting memory fences around the variables which tells the compiler and CPU to not reorder reads / writes before and after those shared variables. In that way programs logic integrity is maintained.

| github_jupyter |
# 用飛槳+ DJL 實作人臉口罩辨識
在這個教學中我們將會展示利用 PaddleHub 下載預訓練好的 PaddlePaddle 模型並針對範例照片做人臉口罩辨識。這個範例總共會分成兩個步驟:
- 用臉部檢測模型識別圖片中的人臉(無論是否有戴口罩)
- 確認圖片中的臉是否有戴口罩
這兩個步驟會包含使用兩個 Paddle 模型,我們會在接下來的內容介紹兩個模型對應需要做的前後處理邏輯
## 導入相關環境依賴及子類別
在這個例子中的前處理飛槳深度學習引擎需要搭配 DJL 混合模式進行深度學習推理,原因是引擎本身沒有包含 NDArray 操作,因此需要藉用其他引擎的 NDArray 操作能力來完成。這邊我們導入 PyTorch 來做協同的前處理工作:
```
// %mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/
%maven ai.djl:api:0.16.0
%maven ai.djl.paddlepaddle:paddlepaddle-model-zoo:0.16.0
%maven org.slf4j:slf4j-simple:1.7.32
// second engine to do preprocessing and postprocessing
%maven ai.djl.pytorch:pytorch-engine:0.16.0
import ai.djl.*;
import ai.djl.inference.*;
import ai.djl.modality.*;
import ai.djl.modality.cv.*;
import ai.djl.modality.cv.output.*;
import ai.djl.modality.cv.transform.*;
import ai.djl.modality.cv.translator.*;
import ai.djl.modality.cv.util.*;
import ai.djl.ndarray.*;
import ai.djl.ndarray.types.Shape;
import ai.djl.repository.zoo.*;
import ai.djl.translate.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;
```
## 臉部偵測模型
現在我們可以開始處理第一個模型,在將圖片輸入臉部檢測模型前我們必須先做一些預處理:
• 調整圖片尺寸: 以特定比例縮小圖片
• 用一個數值對縮小後圖片正規化
對開發者來說好消息是,DJL 提供了 Translator 介面來幫助開發做這樣的預處理. 一個比較粗略的 Translator 架構如下:

在接下來的段落,我們會利用一個 FaceTranslator 子類別實作來完成工作
### 預處理
在這個階段我們會讀取一張圖片並且對其做一些事先的預處理,讓我們先示範讀取一張圖片:
```
String url = "https://raw.githubusercontent.com/PaddlePaddle/PaddleHub/release/v1.5/demo/mask_detection/python/images/mask.jpg";
Image img = ImageFactory.getInstance().fromUrl(url);
img.getWrappedImage();
```
接著,讓我們試著對圖片做一些預處理的轉換:
```
NDList processImageInput(NDManager manager, Image input, float shrink) {
NDArray array = input.toNDArray(manager);
Shape shape = array.getShape();
array = NDImageUtils.resize(
array, (int) (shape.get(1) * shrink), (int) (shape.get(0) * shrink));
array = array.transpose(2, 0, 1).flip(0); // HWC -> CHW BGR -> RGB
NDArray mean = manager.create(new float[] {104f, 117f, 123f}, new Shape(3, 1, 1));
array = array.sub(mean).mul(0.007843f); // normalization
array = array.expandDims(0); // make batch dimension
return new NDList(array);
}
processImageInput(NDManager.newBaseManager(), img, 0.5f);
```
如上述所見,我們已經把圖片轉成如下尺寸的 NDArray: (披量, 通道(RGB), 高度, 寬度). 這是物件檢測模型輸入的格式
### 後處理
當我們做後處理時, 模型輸出的格式是 (number_of_boxes, (class_id, probability, xmin, ymin, xmax, ymax)). 我們可以將其存入預先建立好的 DJL 子類別 DetectedObjects 以便做後續操作. 我們假設有一組推論後的輸出是 ((1, 0.99, 0.2, 0.4, 0.5, 0.8)) 並且試著把人像框顯示在圖片上
```
DetectedObjects processImageOutput(NDList list, List<String> className, float threshold) {
NDArray result = list.singletonOrThrow();
float[] probabilities = result.get(":,1").toFloatArray();
List<String> names = new ArrayList<>();
List<Double> prob = new ArrayList<>();
List<BoundingBox> boxes = new ArrayList<>();
for (int i = 0; i < probabilities.length; i++) {
if (probabilities[i] >= threshold) {
float[] array = result.get(i).toFloatArray();
names.add(className.get((int) array[0]));
prob.add((double) probabilities[i]);
boxes.add(
new Rectangle(
array[2], array[3], array[4] - array[2], array[5] - array[3]));
}
}
return new DetectedObjects(names, prob, boxes);
}
NDArray tempOutput = NDManager.newBaseManager().create(new float[]{1f, 0.99f, 0.1f, 0.1f, 0.2f, 0.2f}, new Shape(1, 6));
DetectedObjects testBox = processImageOutput(new NDList(tempOutput), Arrays.asList("Not Face", "Face"), 0.7f);
Image newImage = img.duplicate();
newImage.drawBoundingBoxes(testBox);
newImage.getWrappedImage();
```
### 生成一個翻譯器並執行推理任務
透過這個步驟,你會理解 DJL 中的前後處理如何運作,現在讓我們把前數的幾個步驟串在一起並對真實圖片進行操作:
```
class FaceTranslator implements NoBatchifyTranslator<Image, DetectedObjects> {
private float shrink;
private float threshold;
private List<String> className;
FaceTranslator(float shrink, float threshold) {
this.shrink = shrink;
this.threshold = threshold;
className = Arrays.asList("Not Face", "Face");
}
@Override
public DetectedObjects processOutput(TranslatorContext ctx, NDList list) {
return processImageOutput(list, className, threshold);
}
@Override
public NDList processInput(TranslatorContext ctx, Image input) {
return processImageInput(ctx.getNDManager(), input, shrink);
}
}
```
要執行這個人臉檢測推理,我們必須先從 DJL 的 Paddle Model Zoo 讀取模型,在讀取模型之前我們必須指定好 `Crieteria` . `Crieteria` 是用來確認要從哪邊讀取模型而後執行 `Translator` 來進行模型導入. 接著,我們只要利用 `Predictor` 就可以開始進行推論
```
Criteria<Image, DetectedObjects> criteria = Criteria.builder()
.setTypes(Image.class, DetectedObjects.class)
.optModelUrls("djl://ai.djl.paddlepaddle/face_detection/0.0.1/mask_detection")
.optFilter("flavor", "server")
.optTranslator(new FaceTranslator(0.5f, 0.7f))
.build();
var model = criteria.loadModel();
var predictor = model.newPredictor();
DetectedObjects inferenceResult = predictor.predict(img);
newImage = img.duplicate();
newImage.drawBoundingBoxes(inferenceResult);
newImage.getWrappedImage();
```
如圖片所示,這個推論服務已經可以正確的辨識出圖片中的三張人臉
## 口罩分類模型
一旦有了圖片的座標,我們就可以將圖片裁剪到適當大小並且將其傳給口罩分類模型做後續的推論
### 圖片裁剪
圖中方框位置的數值範圍從0到1, 只要將這個數值乘上圖片的長寬我們就可以將方框對應到圖片中的準確位置. 為了使裁剪後的圖片有更好的精確度,我們將圖片裁剪成方形,讓我們示範一下:
```
int[] extendSquare(
double xmin, double ymin, double width, double height, double percentage) {
double centerx = xmin + width / 2;
double centery = ymin + height / 2;
double maxDist = Math.max(width / 2, height / 2) * (1 + percentage);
return new int[] {
(int) (centerx - maxDist), (int) (centery - maxDist), (int) (2 * maxDist)
};
}
Image getSubImage(Image img, BoundingBox box) {
Rectangle rect = box.getBounds();
int width = img.getWidth();
int height = img.getHeight();
int[] squareBox =
extendSquare(
rect.getX() * width,
rect.getY() * height,
rect.getWidth() * width,
rect.getHeight() * height,
0.18);
return img.getSubImage(squareBox[0], squareBox[1], squareBox[2], squareBox[2]);
}
List<DetectedObjects.DetectedObject> faces = inferenceResult.items();
getSubImage(img, faces.get(2).getBoundingBox()).getWrappedImage();
```
### 事先準備 Translator 並讀取模型
在使用臉部檢測模型的時候,我們可以利用 DJL 預先建好的 `ImageClassificationTranslator` 並且加上一些轉換。這個 Translator 提供了一些基礎的圖片翻譯處理並且同時包含一些進階的標準化圖片處理。以這個例子來說, 我們不需要額外建立新的 `Translator` 而使用預先建立的就可以
```
var criteria = Criteria.builder()
.setTypes(Image.class, Classifications.class)
.optModelUrls("djl://ai.djl.paddlepaddle/mask_classification/0.0.1/mask_classification")
.optFilter("flavor", "server")
.optTranslator(
ImageClassificationTranslator.builder()
.addTransform(new Resize(128, 128))
.addTransform(new ToTensor()) // HWC -> CHW div(255)
.addTransform(
new Normalize(
new float[] {0.5f, 0.5f, 0.5f},
new float[] {1.0f, 1.0f, 1.0f}))
.addTransform(nd -> nd.flip(0)) // RGB -> GBR
.build())
.build();
var classifyModel = criteria.loadModel();
var classifier = classifyModel.newPredictor();
```
### 執行推論任務
最後,要完成一個口罩識別的任務,我們只需要將上述的步驟合在一起即可。我們先將圖片做裁剪後並對其做上述的推論操作,結束之後再生成一個新的分類子類別 `DetectedObjects`:
```
List<String> names = new ArrayList<>();
List<Double> prob = new ArrayList<>();
List<BoundingBox> rect = new ArrayList<>();
for (DetectedObjects.DetectedObject face : faces) {
Image subImg = getSubImage(img, face.getBoundingBox());
Classifications classifications = classifier.predict(subImg);
names.add(classifications.best().getClassName());
prob.add(face.getProbability());
rect.add(face.getBoundingBox());
}
newImage = img.duplicate();
newImage.drawBoundingBoxes(new DetectedObjects(names, prob, rect));
newImage.getWrappedImage();
```
| github_jupyter |
## Train a model with Iris data using XGBoost algorithm
### Model is trained with XGBoost installed in notebook instance
### In the later examples, we will train using SageMaker's XGBoost algorithm
```
# Install xgboost in notebook instance.
#### Command to install xgboost
!pip install xgboost==1.2
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import itertools
import xgboost as xgb
from sklearn import preprocessing
from sklearn.metrics import classification_report, confusion_matrix
column_list_file = 'iris_train_column_list.txt'
train_file = 'iris_train.csv'
validation_file = 'iris_validation.csv'
columns = ''
with open(column_list_file,'r') as f:
columns = f.read().split(',')
columns
# Encode Class Labels to integers
# Labeled Classes
labels=[0,1,2]
classes = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']
le = preprocessing.LabelEncoder()
le.fit(classes)
# Specify the column names as the file does not have column header
df_train = pd.read_csv(train_file,names=columns)
df_validation = pd.read_csv(validation_file,names=columns)
df_train.head()
df_validation.head()
X_train = df_train.iloc[:,1:] # Features: 1st column onwards
y_train = df_train.iloc[:,0].ravel() # Target: 0th column
X_validation = df_validation.iloc[:,1:]
y_validation = df_validation.iloc[:,0].ravel()
# Launch a classifier
# XGBoost Training Parameter Reference:
# https://xgboost.readthedocs.io/en/latest/parameter.html
classifier = xgb.XGBClassifier(objective="multi:softmax",
num_class=3,
n_estimators=100)
classifier
classifier.fit(X_train,
y_train,
eval_set = [(X_train, y_train), (X_validation, y_validation)],
eval_metric=['mlogloss'],
early_stopping_rounds=10)
# early_stopping_rounds - needs to be passed in as a hyperparameter in SageMaker XGBoost implementation
# "The model trains until the validation score stops improving.
# Validation error needs to decrease at least every early_stopping_rounds to continue training.
# Amazon SageMaker hosting uses the best model for inference."
eval_result = classifier.evals_result()
training_rounds = range(len(eval_result['validation_0']['mlogloss']))
print(training_rounds)
plt.scatter(x=training_rounds,y=eval_result['validation_0']['mlogloss'],label='Training Error')
plt.scatter(x=training_rounds,y=eval_result['validation_1']['mlogloss'],label='Validation Error')
plt.grid(True)
plt.xlabel('Iteration')
plt.ylabel('LogLoss')
plt.title('Training Vs Validation Error')
plt.legend()
plt.show()
xgb.plot_importance(classifier)
plt.show()
df = pd.read_csv(validation_file,names=columns)
df.head()
X_test = df.iloc[:,1:]
print(X_test[:5])
result = classifier.predict(X_test)
result[:5]
df['predicted_class'] = result #le.inverse_transform(result)
df.head()
# Compare performance of Actual and Model 1 Prediction
plt.figure()
plt.scatter(df.index,df['encoded_class'],label='Actual')
plt.scatter(df.index,df['predicted_class'],label='Predicted',marker='^')
plt.legend(loc=4)
plt.yticks([0,1,2])
plt.xlabel('Sample')
plt.ylabel('Class')
plt.show()
```
<h2>Confusion Matrix</h2>
Confusion Matrix is a table that summarizes performance of classification model.<br><br>
```
# Reference:
# https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
#print("Normalized confusion matrix")
#else:
# print('Confusion matrix, without normalization')
#print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
# Compute confusion matrix
cnf_matrix = confusion_matrix(df['encoded_class'],
df['predicted_class'],labels=labels)
cnf_matrix
# Plot confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=classes,
title='Confusion matrix - Count')
# Plot confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=classes,
title='Confusion matrix - Count',normalize=True)
print(classification_report(
df['encoded_class'],
df['predicted_class'],
labels=labels,
target_names=classes))
```
| github_jupyter |
# Keyboard shortcuts
In this notebook, you'll get some practice using keyboard shortcuts. These are key to becoming proficient at using notebooks and will greatly increase your work speed.
First up, switching between edit mode and command mode. Edit mode allows you to type into cells while command mode will use key presses to execute commands such as creating new cells and openning the command palette. When you select a cell, you can tell which mode you're currently working in by the color of the box around the cell. In edit mode, the box and thick left border are colored green. In command mode, they are colored blue. Also in edit mode, you should see a cursor in the cell itself.
By default, when you create a new cell or move to the next one, you'll be in command mode. To enter edit mode, press Enter/Return. To go back from edit mode to command mode, press Escape.
> **Exercise:** Click on this cell, then press Enter + Shift to get to the next cell. Switch between edit and command mode a few times.
```
# mode practice
```
## Help with commands
If you ever need to look up a command, you can bring up the list of shortcuts by pressing `H` in command mode. The keyboard shortcuts are also available above in the Help menu. Go ahead and try it now.
## Creating new cells
One of the most common commands is creating new cells. You can create a cell above the current cell by pressing `A` in command mode. Pressing `B` will create a cell below the currently selected cell.
> **Exercise:** Create a cell above this cell using the keyboard command.
> **Exercise:** Create a cell below this cell using the keyboard command.
## Switching between Markdown and code
With keyboard shortcuts, it is quick and simple to switch between Markdown and code cells. To change from Markdown to a code cell, press `Y`. To switch from code to Markdown, press `M`.
> **Exercise:** Switch the cell below between Markdown and code cells.
```
## Practice here
def fibo(n): # Recursive Fibonacci sequence!
if n == 0:
return 0
elif n == 1:
return 1
return fibo(n-1) + fibo(n-2)
```
## Line numbers
A lot of times it is helpful to number the lines in your code for debugging purposes. You can turn on numbers by pressing `L` (in command mode of course) on a code cell.
> **Exercise:** Turn line numbers on and off in the above code cell.
## Deleting cells
Deleting cells is done by pressing `D` twice in a row so `D`, `D`. This is to prevent accidently deletions, you have to press the button twice!
> **Exercise:** Delete the cell below.
## Saving the notebook
Notebooks are autosaved every once in a while, but you'll often want to save your work between those times. To save the book, press `S`. So easy!
## The Command Palette
You can easily access the command palette by pressing Shift + Control/Command + `P`.
> **Note:** This won't work in Firefox and Internet Explorer unfortunately. There is already a keyboard shortcut assigned to those keys in those browsers. However, it does work in Chrome and Safari.
This will bring up the command palette where you can search for commands that aren't available through the keyboard shortcuts. For instance, there are buttons on the toolbar that move cells up and down (the up and down arrows), but there aren't corresponding keyboard shortcuts. To move a cell down, you can open up the command palette and type in "move" which will bring up the move commands.
> **Exercise:** Use the command palette to move the cell below down one position.
```
# below this cell
# Move this cell down
```
## Finishing up
There is plenty more you can do such as copying, cutting, and pasting cells. I suggest getting used to using the keyboard shortcuts, you’ll be much quicker at working in notebooks. When you become proficient with them, you'll rarely need to move your hands away from the keyboard, greatly speeding up your work.
Remember, if you ever need to see the shortcuts, just press `H` in command mode.
| github_jupyter |
<a href="https://colab.research.google.com/github/alewis/AdvMPS/blob/master/jit_qr.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# This is formatted as code
```
# Practice writing efficient Jit code on the Householder QR algorithm.
```
import jax
import jax.numpy as jnp
from jax.ops import index, index_update, index_add
import numpy as np
# import jit
# import scipy as sp
# import tensorflow as tf
# from copy import deepcopy
import random
import time
import functools
import matplotlib.pyplot as plt
import sys
import unittest
import cProfile
import pstats
import os
import getpass
import urllib
%load_ext autoreload
%autoreload 2
repo_loaded = False
```
# Credentials.
This block imports the git repo so that we can use the relevant libraries.
Change the string in 'username' to your GitHub username. Input your GitHub password when requested by the dialog. Your password is not saved in the
notebook. Solution by Vinoj John Hosan at https://stackoverflow.com/questions/48350226/methods-for-using-git-with-google-colab.
```
def load_repo_from_colab(username, repo_name):
password = getpass.getpass('Password: ')
password = urllib.parse.quote(password) # your password is converted into url format
cmd_string = 'git clone https://{0}:{1}@github.com/{0}/{2}.git'.format(username, password, repo_name)
os.system(cmd_string)
cmd_string, password = "", "" # removing the password from the variable
def is_local():
return not 'google.colab' in sys.modules
if not is_local():
if not repo_loaded:
username = "alewis"
repo_name = "dfact"
load_repo_from_colab(username, repo_name)
repo_loaded = True
else:
!git -C /content/dfact pull
else:
to_append = '/Users/adam/projects/'
if to_append not in sys.path:
sys.path.append(to_append)
import dfact.utv as utv
import dfact.matutils as matutils
from dfact.matutils import dag
import dfact.utv_tests as utv_tests
#import dfact.qr as qr
```
#### Matplotlib Customizations
```
from matplotlib import cycler
colors = cycler('color',
['#EE6666', '#3388BB', '#9988DD',
'#EECC55', '#88BB44', '#FFBBBB'])
# plt.rc('axes', facecolor='#E6E6E6', edgecolor='none',
# axisbelow=True, grid=True, prop_cycle=colors)
# plt.rc('grid', color='w', linestyle='solid')
# plt.rc('xtick', direction='out', color='gray')
# plt.rc('ytick', direction='out', color='gray')
# plt.rc('patch', edgecolor='#E6E6E6')
plt.rc('figure', figsize=(10, 10))
plt.rc('xtick', labelsize=18)
plt.rc('ytick', labelsize=18)
plt.rc('font', size=22 )
plt.rc('lines', linewidth=2)
```
# Notebook Code
```
"""
Jax implementation of householder QR exposing the low-level functionality
needed for the UTV decomposition.
Adam GM Lewis
adam.lws@gmail.com
alewis@perimeterinstitute.ca
"""
import jax
from jax.ops import index_update, index_add, index
import jax.numpy as jnp
import numpy as np
import dfact.matutils as matutils
from dfact.matutils import dag
###############################################################################
# UTILITIES
###############################################################################
@jax.jit
def sign(num):
"""
Sign function using the standard (?) convention sign(x) = x / |x| in
the complex case. Returns 0 with the same type as x if x == 0.
Note the numpy implementation uses the slightly different convention
sign(x) = x / sqrt(x * x).
"""
result = jax.lax.cond(num == 0,
num, lambda num: 0*num, # 0, casted, if num is 0
num, lambda num: num/jnp.abs(num)) # else x/|x|
return result
###############################################################################
# COMPUTATION OF HOUSEHOLDER VECTORS
###############################################################################
@jax.jit
def house(x_in):
"""
Given a real or complex length-m vector x, finds the Householder vector
v and its inverse normalization tau such that
P = I - beta * v \otimes dag(v)
is the symmetric (Hermitian) and orthogonal (unitary) Householder matrix
representing reflections about x.
Returns a list [v, beta], where v is a length-m vector whose first
component is 1, and beta = 2/(dag(v) v).
x will be treated as a flattened vector whatever its shape.
Parameters
----------
x_in: array_like, shape(m,)
The vector about which to compute the Householder reflector. Will
be flattened (inside this fucntion only) to the prescribed shape.
Output
------
[v_out, beta]:
v_out: array_like, shape(m,), the Householder vector including the 1.
beta: float, the normalization 2/|v|
"""
x_in= x_in.ravel()
x_2_norm = jnp.linalg.norm(x_in[1:])
# The next two lines are logically equivalent to
# if x_2_norm == 0:
# v, beta = __house_zero_norm(x)
# else:
# v, beta = __house_nonzero_norm( (x, x_2_norm) )
switch = (x_2_norm == 0)
v_out, beta = jax.lax.cond(switch,
x_in, __house_zero_norm,
(x_in, x_2_norm), __house_nonzero_norm)
return [v_out, beta]
@jax.jit
def __house_zero_norm(x):
"""
Handles house(x) in the case that norm(x[1:])==0.
"""
beta = 2.
v = x
v = index_update(v, index[0], 1.)
beta = jax.lax.cond(x[0] == 0,
x, lambda x: x[0]*0,
x, lambda x: x[0]*0 + 2
).real
return [v, beta]
@jax.jit
def __house_nonzero_norm(xtup):
"""
Handles house(x) in the case that norm(x[1:])!=0.
"""
x, x_2_norm = xtup
x, x_2_norm = xtup
x_norm = jnp.linalg.norm(jnp.array([x[0], x_2_norm]))
rho = sign(x[0])*x_norm
v_1p = x[0] + rho
v_1pabs = jnp.abs(v_1p)
v_1m = x[0] - rho
v_1mabs = jnp.abs(v_1m)
# Pick whichever of v[0] = x[0] +- sign(x[0])*||x||
# has greater ||v[0]||, and thus leads to greater ||v||.
# Golub and van Loan prescribes this "for stability".
v_1, v_1abs = jax.lax.cond(v_1pabs >= v_1mabs,
(v_1p, v_1pabs), lambda x: x,
(v_1m, v_1mabs), lambda x: x)
v = x
v = index_update(v, index[1:], v[1:]/v_1)
v = index_update(v, index[0], 1.)
v_2_norm = x_2_norm / v_1abs
v_norm_sqr = 1 + v_2_norm**2
beta = (2 / v_norm_sqr).real
return [v, beta]
###############################################################################
# MANIPULATION OF HOUSEHOLDER VECTORS
###############################################################################
@jax.jit
def form_dense_P(hlist):
"""
Computes the dense Householder matrix P = I - beta * (v otimes dag(v))
from the Householder reflector stored as hlist = (v, beta). This is
useful for testing.
"""
v, beta = hlist
Id = jnp.eye(v.size, dtype=v.dtype)
P = Id - beta * jnp.outer(v, dag(v))
return P
@jax.jit
def house_leftmult(A, v, beta):
"""
Given the m x n matrix A and the length-n vector v with normalization
beta such that P = I - beta v otimes dag(v) is the Householder matrix that
reflects about v, compute PA.
Parameters
----------
A: array_like, shape(M, N)
Matrix to be multiplied by H.
v: array_like, shape(N).
Householder vector.
beta: float
Householder normalization.
Returns
-------
C = PA
"""
C = A - jnp.outer(beta*v, jnp.dot(dag(v), A))
return C
@jax.jit
def house_rightmult(A, v, beta):
"""
Given the m x n matrix A and the length-n vector v with normalization
beta such that P = I - beta v otimes dag(v) is the Householder matrix that
reflects about v, compute AP.
Parameters
----------
A: array_like, shape(M, N)
Matrix to be multiplied by H.
v: array_like, shape(N).
Householder vector.
beta: float
Householder normalization.
Returns
-------
C = AP
"""
C = A - jnp.outer(A@v, beta*dag(v))
return C
###############################################################################
# MANIPULATION OF FACTORED QR REPRESENTATION
###############################################################################
def factored_rightmult_dense(A, H, betas):
"""
Computes C = A * Q, where Q is in the factored representation.
With A = Hbetalist[0].shape[0], this computes Q, but less economically
than 'factored_to_QR'.
This is a dense implementation written to test 'factored_rightmult' below.
Do not call it in production code.
"""
C = A
n = C.shape[1]
for j, beta in enumerate(betas):
vnz = jnp.array([1.]+list(H[j+1:, j]))
nminus = n - vnz.size
v = jnp.array([0.]*nminus + list(vnz))
P = form_dense_P([v, beta])
C = index_update(C, index[:, :], C@P)
return C
@jax.jit
def factored_rightmult(A, H, betas):
"""
Computes C = A * Q, where Q is in the factored representation.
With A = Hbetalist[0].shape[0], this computes Q, but less economically
than 'factored_to_QR'.
"""
C = A
for j, beta in enumerate(betas):
v = jnp.array([1.]+list(H[j+1:, j]))
C = index_update(C, index[:, j:], house_rightmult(C[:, j:], v, beta))
return C
@jax.jit
def factored_to_QR(h, beta):
"""
Computes dense matrices Q and R from the factored QR representation
[h, tau] as computed by qr with mode == "factored".
"""
m, n = h.shape
R = jnp.triu(h)
Q = jnp.eye(m, dtype=h.dtype)
for j in range(n-1, -1, -1):
v = jnp.concatenate((jnp.array([1.]), h[j+1:, j]))
Q = index_update(Q, index[j:, j:],
house_leftmult(Q[j:, j:], v, beta[j]))
out = [Q, R]
return out
###############################################################################
# MANIPULATION OF WY QR REPRESENTATION
###############################################################################
@jax.jit
def times_householder_vector(A, H, j):
"""
Computes A * v_j where v_j is the j'th Householder vector in H.
Parameters
----------
A: k x M matrix to multiply by v_j.
H: M x k matrix of Householder reflectors.
j: The column of H from which to extract v_j.
Returns
------
vout: length-M vector of output.
"""
vin = jnp.array([1.]+list(H[j+1:, j]))
vout = jnp.zeros(H.shape[0], dtype=H.dtype)
vout = index_update(vout, index[j:], A[:, j:] @ vin)
return vout
@jax.jit
def factored_to_WY(hbetalist):
"""
Converts the 'factored' QR representation [H, beta] into the WY
representation, Q = I - WY^H.
Parameters
----------
hbetalist = [H, beta] : list of array_like, shapes [M, N] and [N].
'factored' QR rep of a matrix A (the output from
house_QR(A, mode='factored')).
Returns
-------
[W, YH]: list of ndarrays of shapes [M, N].
The matrices W and Y generating Q along with R in the 'WY'
representation.
-W (M x N): The matrix W.
-YH (M x N): -Y is the lower triangular matrix with the essential parts of
the Householder reflectors as its columns,
obtained by setting the main diagonal of H to 1 and zeroing
out everything above.
-YH, the h.c. of this matrix, is thus upper triangular
with the full Householder reflectors as its rows. This
function returns YH, which is what one needs to compute
C = Q @ B = (I - WY^H) @ B = B - W @ Y^H @ B.
Note: it is more efficient to store W and Y^H separately
than to precompute their product, since we will
typically have N << M when exploiting this
representation.
"""
H, betas = hbetalist
m, n = matutils.matshape(H)
W = jnp.zeros(H.shape, H.dtype)
vj = jnp.array([1.]+list(H[1:, 0]))
W = index_update(W, index[:, 0], betas[0] * vj)
Y = jnp.zeros(H.shape, H.dtype)
Y = index_update(Y, index[:, 0], vj)
for j in range(1, n):
vj = index_update(vj, index[j+1:], H[j+1:, j])
vj = index_update(vj, index[j], 1.) # vj[j:] stores the current vector
YHv = (dag(Y[j:, :j])) @ vj[j:]
z = W[:, :j] @ YHv
z = index_add(z, index[j:], -vj[j:])
z = index_update(z, index[:], -betas[j]*z)
W = index_update(W, index[:, j], z)
Y = index_update(Y, index[j:, j], vj[j:])
YH = dag(Y)
return [W, YH]
@jax.jit
def B_times_Q_WY(B, W, YH):
"""
Computes C(kxm) = B(kxm)@Q(mxm) with Q given as W and Y^H in
Q = I(mxm) - W(mxr)Y^T(rxm).
"""
C = B - (B@W)@YH
return C
@jax.jit
def Qdag_WY_times_B(B, W, YH):
"""
Computes C(mxk) = QH(mxm)@B(mxk) with Q given as W and Y^H in
Q = I(mxm) - W(mxr)Y^T(rxm)
"""
C = B - dag(YH)@(dag(W)@B)
return C
@jax.jit
def WY_to_Q(W, YH):
"""
Retrieves Q from its WY representation.
"""
m = W.shape[0]
Id = jnp.eye(m, dtype=W.dtype)
return B_times_Q_WY(Id, W, YH)
###############################################################################
# QR DECOMPOSITION
###############################################################################
def house_qr(A, mode="reduced"):
"""
Performs a QR decomposition of the m x n real or complex matrix A
using the Householder algorithm.
The string parameter 'mode' determines the representation of the output.
In this way, one can retrieve various implicit representations of the
factored matrices. This can be a significant optimization in the case
of a highly rectangular A, which is the reason for this function's
existence.
Parameters
----------
A : array_like, shape (M, N)
Matrix to be factored.
mode: {'reduced', 'complete', 'r', 'factored', 'WY'}, optional
If K = min(M, N), then:
- 'reduced': returns Q, R with dimensions (M, K), (K, N)
(default)
- 'complete': returns Q, R with dimensions (M, M), (M, N)
- 'r': returns r only with dimensions (K, N)
- 'factored': returns H, beta with dimensions (N, M), (K), read
below for details.
- 'WY' : returns W, Y with dimensions (M, K), read below for
details.
With 'reduced', 'complete', or 'r', this function simply passes to
jnp.linalg.qr, which depending on the currect status of Jax may lead to
NotImplemented if A is complex.
With 'factored' this function returns the same H, beta as generated by
the Lapack function dgeqrf() (but in row-major form). Thus,
H contains the upper triangular matrix R in its upper triangle, and
the j'th Householder reflector forming Q in the j'th column of its
lower triangle. beta[j] contains the normalization factor of the j'th
reflector, called 'beta' in the function 'house' in this module.
The matrix Q is then represented implicitly as
Q = H(0) H(1) ... H(K), H(i) = I - tau[i] v dag(v)
with v[:j] = 0; v[j]=1; v[j+1:]=A[j+1:, j].
Application of Q (C -> dag{Q} C) can be made directly from this implicit
representation using the function factored_multiply(C). When
K << max(M, N), both the QR factorization and multiplication by Q
using factored_multiply theoretically require far fewer operations than
would an explicit representation of Q. However, these applications
are mostly Level-2 BLAS operations.
With 'WY' this function returns (M, K) matrices W and Y such that
Q = I - W dag(Y).
Y is lower-triangular matrix of Householder vectors, e.g. the lower
triangle
of the matrix H resulting from mode='factored'. W is then computed so
that the above identity holds.
Application of Q can be made directly from the WY representation
using the function WY_multiply(C). The WY representation is
a bit more expensive to compute than the factored one, though still less
expensive than the full Q. Its advantage versus 'factored' is that
WY_multiply calls depend mostly on Level-3 BLAS operations.
Returns
-------
Q: ndarray of float or complex, optional
The column-orthonormal orthogonal/unitary matrix Q.
R: ndarray of float or complex, optional.
The upper-triangular matrix.
[H, beta]: list of ndarrays of float or complex, optional.
The matrix H and scaling factors beta generating Q along with R in the
'factored' representation.
[W, Y, R] : list of ndarrays of float or complex, optional.
The matrices W and Y generating Q along with R in the 'WY'
representation.
Raises
------
LinAlgError
If factoring fails.
NotImplementedError
In reduced, complete, or r mode with complex ijnp.t.
In factored or WY mode in the case M < N.
"""
if mode == "reduced" or mode == "complete" or mode == "r":
return jnp.linalg.qr(A, mode=mode)
else:
m, n = A.shape
if n > m:
raise NotImplementedError("n > m QR not implemented in factored"
+ "or WY mode.")
if mode == "factored":
return __house_qr_factored(A)
elif mode == "WY":
hbetalist = __house_qr_factored(A)
R = jnp.triu(hbetalist[0])
WYlist = factored_to_WY(hbetalist)
output = WYlist + [R]
return output
else:
raise ValueError("Invalid mode: ", mode)
@jax.jit
def __house_qr_factored(A):
"""
Computes the QR decomposition of A in the 'factored' representation.
This is a workhorse function to be accessed externally by
house_qr(A, mode="factored"), and is documented more extensively in
that function's documentation.
"""
H = A
M, N = matutils.matshape(A)
beta = list()
for j in range(A.shape[1]):
v, thisbeta = house(H[j:, j])
beta.append(thisbeta)
H = index_update(H, index[j:, j:], house_leftmult(H[j:, j:], v,
thisbeta))
if j < M:
H = index_update(H, index[j+1:, j], v[1:])
beta = jnp.array(beta)
output = [H, beta]
return output
def __house_qr_factored_scan(A):
"""
Computes the QR decomposition of A in the 'factored' representation.
This is a workhorse function to be accessed externally by
house_qr(A, mode="factored"), and is documented more extensively in
that function's documentation.
This implementation uses jax.lax.scan to reduce the amount of emitted
XLA code.
This should work for N > M!
"""
H = A
M, N = matutils.matshape(A)
js_i = jnp.arange(0, M, 1)
js_f = jnp.arange(M, N, 1)
def house_qr_j_lt_m(H, j):
m, n = H.shape
Htri = jnp.tril(H)
v, thisbeta = house_padded(Htri[:, j], j)
# Hjj = jax.lax.dynamic_slice(H, (j, j), (m-j, n-j)) # H[j:, j:]
# H_update = house_leftmult(Hjj, v, thisbeta)
# H = index_update(H, index[:, :],
# jax.lax.dynamic_update_slice(H, H_update, [j, j]))
# H = index_update(H, index[:, :],
# jax.lax.dynamic_update_slice(H, v[1:], [j+1, j]))
return H, thisbeta
def house_qr_j_gt_m(H, j):
m, n = H.shape
this_slice = jax.lax.dynamic_slice(H, (j, j), (m-j, 1)) # H[j:, j]
v, thisbeta = house(this_slice)
Hjj = jax.lax.dynamic_slice(H, (j, j), (m-j, n-j)) # H[j:, j:]
H_update = house_leftmult(Hjj, v, thisbeta)
H = index_update(H, index[:, :],
jax.lax.dynamic_update_slice(H, H_update, [j, j]))
return H, thisbeta
# def house_qr_j_lt_m(H, j):
# m, n = H.shape
# H, thisbeta = house_qr_j_gt_m(H, j)
# v = jax.lax.dynamic_slice(H, (j+1, j), (m-j-1, 1))
# return H, thisbeta
H, betas_i = jax.lax.scan(house_qr_j_lt_m, H, js_i)
raise ValueError("Meep meep!")
#H, betas_f = jax.lax.scan(house_qr_j_gt_m, H, js_f)
betas = jnp.concatenate([betas_i, betas_f])
output = [H, betas]
return output
import gc
def get_obj_size(obj):
"""
Returns the logical size of 'obj' in bytes.
"""
marked = {id(obj)}
obj_q = [obj]
sz = 0
while obj_q:
sz += sum(map(sys.getsizeof, obj_q))
# Lookup all the object referred to by the object in obj_q.
# See: https://docs.python.org/3.7/library/gc.html#gc.get_referents
all_refr = ((id(o), o) for o in gc.get_referents(*obj_q))
# Filter object that are already marked.
# Using dict notation will prevent repeated objects.
new_refr = {o_id: o for o_id, o in all_refr if o_id not in marked and not isinstance(o, type)}
# The new obj_q will be the ones that were not marked,
# and we will update marked with their ids so we will
# not traverse them again.
obj_q = new_refr.values()
marked.update(new_refr.keys())
return sz
import time
def time_for_jit(func, input_shape, N_med=20, N_inner=20,
dtype=jnp.float32):
"""
Measures the effective bandwidth of func(A), for A an array
of shape input_shape. The wallclock time of the first call is returned
separately.
"""
A = matutils.gaussian_random(shape=input_shape, dtype=dtype)
A_logical_size = get_obj_size(A) # size of A in bytes
c_time_i = time.perf_counter()
out = func(A)
c_time_f = time.perf_counter()
c_time = c_time_f - c_time_i
e_times = []
for _ in range(N_med):
A = matutils.gaussian_random(shape=input_shape, dtype=dtype)
e_time_i = time.perf_counter()
for _ in range(N_inner):
out = func(A)
e_time_f = time.perf_counter()
e_times.append((e_time_f-e_time_i)/N_inner)
e_time = np.median(np.array(e_times))
c_time = c_time - e_time
e_BW = A_logical_size / (1000 * e_time) #GB / s
c_BW = A_logical_size / (1000 * c_time)
return (c_BW, e_BW)
f = functools.partial(house_qr, mode="factored")
times = []
BWs = []
ns = range(2, 40, 1)
comp_BWs = []
ex_BWs = []
for n in ns:
shape = (n, n)
print("n=", n)
comp_BW, ex_BW = time_for_jit(f, shape)
comp_BWs.append(comp_BW)
ex_BWs.append(ex_BW)
plt.plot(ns, ex_BWs, label="Execution", marker="o")
plt.xlabel("n")
plt.ylabel("BW_eff")
plt.title("Execution")
plt.show()
plt.plot(ns, comp_BWs, label="Compilation", marker="o")
plt.xlabel("n")
plt.ylabel("BW_eff")
plt.title("Compilation")
plt.show()
```
| github_jupyter |
# Handling uncertainty with quantile regression
```
%matplotlib inline
```
[Quantile regression](https://www.wikiwand.com/en/Quantile_regression) is useful when you're not so much interested in the accuracy of your model, but rather you want your model to be good at ranking observations correctly. The typical way to perform quantile regression is to use a special loss function, namely the quantile loss. The quantile loss takes a parameter, $\alpha$ (alpha), which indicates which quantile the model should be targeting. In the case of $\alpha = 0.5$, then this is equivalent to asking the model to predict the median value of the target, and not the most likely value which would be the mean.
A nice thing we can do with quantile regression is to produce a prediction interval for each prediction. Indeed, if we predict the lower and upper quantiles of the target then we will be able to obtain a "trust region" in between which the true value is likely to belong. Of course, the likeliness will depend on the chosen quantiles. For a slightly more detailed explanation see [this](https://medium.com/the-artificial-impostor/quantile-regression-part-1-e25bdd8d9d43) blog post.
As an example, let us take the [simple time series model we built in another notebook](building-a-simple-time-series-model.md). Instead of predicting the mean value of the target distribution, we will predict the 5th, 50th, 95th quantiles. This will require training three separate models, so we will encapsulate the model building logic in a function called `make_model`. We also have to slightly adapt the training loop, but not by much. Finally, we will draw the prediction interval along with the predictions from for 50th quantile (i.e. the median) and the true values.
```
import calendar
import math
import matplotlib.pyplot as plt
from river import compose
from river import datasets
from river import linear_model
from river import metrics
from river import optim
from river import preprocessing
from river import stats
from river import time_series
def get_ordinal_date(x):
return {'ordinal_date': x['month'].toordinal()}
def get_month_distances(x):
return {
calendar.month_name[month]: math.exp(-(x['month'].month - month) ** 2)
for month in range(1, 13)
}
def make_model(alpha):
extract_features = compose.TransformerUnion(get_ordinal_date, get_month_distances)
scale = preprocessing.StandardScaler()
learn = linear_model.LinearRegression(
intercept_lr=0,
optimizer=optim.SGD(3),
loss=optim.losses.Quantile(alpha=alpha)
)
model = extract_features | scale | learn
model = time_series.Detrender(regressor=model, window_size=12)
return model
metric = metrics.MAE()
models = {
'lower': make_model(alpha=0.05),
'center': make_model(alpha=0.5),
'upper': make_model(alpha=0.95)
}
dates = []
y_trues = []
y_preds = {
'lower': [],
'center': [],
'upper': []
}
for x, y in datasets.AirlinePassengers():
y_trues.append(y)
dates.append(x['month'])
for name, model in models.items():
y_preds[name].append(model.predict_one(x))
model.learn_one(x, y)
# Update the error metric
metric.update(y, y_preds['center'][-1])
# Plot the results
fig, ax = plt.subplots(figsize=(10, 6))
ax.grid(alpha=0.75)
ax.plot(dates, y_trues, lw=3, color='#2ecc71', alpha=0.8, label='Truth')
ax.plot(dates, y_preds['center'], lw=3, color='#e74c3c', alpha=0.8, label='Prediction')
ax.fill_between(dates, y_preds['lower'], y_preds['upper'], color='#e74c3c', alpha=0.3, label='Prediction interval')
ax.legend()
ax.set_title(metric);
```
An important thing to note is that the prediction interval we obtained should not be confused with a confidence interval. Simply put, a prediction interval represents uncertainty for where the true value lies, whereas a confidence interval encapsulates the uncertainty on the prediction. You can find out more by reading [this](https://stats.stackexchange.com/questions/16493/difference-between-confidence-intervals-and-prediction-intervals) CrossValidated post.
| github_jupyter |
<a id='1'></a>
# 1. Import packages
```
from keras.models import Sequential, Model
from keras.layers import *
from keras.layers.advanced_activations import LeakyReLU
from keras.activations import relu
from keras.initializers import RandomNormal
from keras.applications import *
import keras.backend as K
from tensorflow.contrib.distributions import Beta
import tensorflow as tf
from keras.optimizers import Adam
from image_augmentation import random_transform
from image_augmentation import random_warp
from utils import get_image_paths, load_images, stack_images
from pixel_shuffler import PixelShuffler
import time
import numpy as np
from PIL import Image
import cv2
import glob
from random import randint, shuffle
from IPython.display import clear_output
from IPython.display import display
import matplotlib.pyplot as plt
%matplotlib inline
```
<a id='4'></a>
# 4. Config
mixup paper: https://arxiv.org/abs/1710.09412
Default training data directories: `./faceA/` and `./faceB/`
```
K.set_learning_phase(0)
channel_axis=-1
channel_first = False
IMAGE_SHAPE = (64, 64, 3)
nc_in = 3 # number of input channels of generators
nc_D_inp = 6 # number of input channels of discriminators
use_self_attn = False
w_l2 = 1e-4 # weight decay
batchSize = 8
# Path of training images
img_dirA = './faceA/*.*'
img_dirB = './faceB/*.*'
```
<a id='5'></a>
# 5. Define models
```
class Scale(Layer):
'''
Code borrows from https://github.com/flyyufelix/cnn_finetune
'''
def __init__(self, weights=None, axis=-1, gamma_init='zero', **kwargs):
self.axis = axis
self.gamma_init = initializers.get(gamma_init)
self.initial_weights = weights
super(Scale, self).__init__(**kwargs)
def build(self, input_shape):
self.input_spec = [InputSpec(shape=input_shape)]
# Compatibility with TensorFlow >= 1.0.0
self.gamma = K.variable(self.gamma_init((1,)), name='{}_gamma'.format(self.name))
self.trainable_weights = [self.gamma]
if self.initial_weights is not None:
self.set_weights(self.initial_weights)
del self.initial_weights
def call(self, x, mask=None):
return self.gamma * x
def get_config(self):
config = {"axis": self.axis}
base_config = super(Scale, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
def self_attn_block(inp, nc):
'''
Code borrows from https://github.com/taki0112/Self-Attention-GAN-Tensorflow
'''
assert nc//8 > 0, f"Input channels must be >= 8, but got nc={nc}"
x = inp
shape_x = x.get_shape().as_list()
f = Conv2D(nc//8, 1, kernel_initializer=conv_init)(x)
g = Conv2D(nc//8, 1, kernel_initializer=conv_init)(x)
h = Conv2D(nc, 1, kernel_initializer=conv_init)(x)
shape_f = f.get_shape().as_list()
shape_g = g.get_shape().as_list()
shape_h = h.get_shape().as_list()
flat_f = Reshape((-1, shape_f[-1]))(f)
flat_g = Reshape((-1, shape_g[-1]))(g)
flat_h = Reshape((-1, shape_h[-1]))(h)
s = Lambda(lambda x: tf.matmul(x[0], x[1], transpose_b=True))([flat_g, flat_f])
beta = Softmax(axis=-1)(s)
o = Lambda(lambda x: tf.matmul(x[0], x[1]))([beta, flat_h])
o = Reshape(shape_x[1:])(o)
o = Scale()(o)
out = add([o, inp])
return out
def conv_block(input_tensor, f):
x = input_tensor
x = Conv2D(f, kernel_size=3, strides=2, kernel_regularizer=regularizers.l2(w_l2),
kernel_initializer=conv_init, use_bias=False, padding="same")(x)
x = Activation("relu")(x)
return x
def conv_block_d(input_tensor, f, use_instance_norm=False):
x = input_tensor
x = Conv2D(f, kernel_size=4, strides=2, kernel_regularizer=regularizers.l2(w_l2),
kernel_initializer=conv_init, use_bias=False, padding="same")(x)
x = LeakyReLU(alpha=0.2)(x)
return x
def res_block(input_tensor, f):
x = input_tensor
x = Conv2D(f, kernel_size=3, kernel_regularizer=regularizers.l2(w_l2),
kernel_initializer=conv_init, use_bias=False, padding="same")(x)
x = LeakyReLU(alpha=0.2)(x)
x = Conv2D(f, kernel_size=3, kernel_regularizer=regularizers.l2(w_l2),
kernel_initializer=conv_init, use_bias=False, padding="same")(x)
x = add([x, input_tensor])
x = LeakyReLU(alpha=0.2)(x)
return x
def upscale_ps(filters, use_norm=True):
def block(x):
x = Conv2D(filters*4, kernel_size=3, kernel_regularizer=regularizers.l2(w_l2),
kernel_initializer=RandomNormal(0, 0.02), padding='same')(x)
x = LeakyReLU(0.2)(x)
x = PixelShuffler()(x)
return x
return block
def Discriminator(nc_in, input_size=64):
inp = Input(shape=(input_size, input_size, nc_in))
#x = GaussianNoise(0.05)(inp)
x = conv_block_d(inp, 64, False)
x = conv_block_d(x, 128, False)
x = self_attn_block(x, 128) if use_self_attn else x
x = conv_block_d(x, 256, False)
x = self_attn_block(x, 256) if use_self_attn else x
out = Conv2D(1, kernel_size=4, kernel_initializer=conv_init, use_bias=False, padding="same")(x)
return Model(inputs=[inp], outputs=out)
def Encoder(nc_in=3, input_size=64):
inp = Input(shape=(input_size, input_size, nc_in))
x = Conv2D(64, kernel_size=5, kernel_initializer=conv_init, use_bias=False, padding="same")(inp)
x = conv_block(x,128)
x = conv_block(x,256)
x = self_attn_block(x, 256) if use_self_attn else x
x = conv_block(x,512)
x = self_attn_block(x, 512) if use_self_attn else x
x = conv_block(x,1024)
x = Dense(1024)(Flatten()(x))
x = Dense(4*4*1024)(x)
x = Reshape((4, 4, 1024))(x)
out = upscale_ps(512)(x)
return Model(inputs=inp, outputs=out)
def Decoder_ps(nc_in=512, input_size=8):
input_ = Input(shape=(input_size, input_size, nc_in))
x = input_
x = upscale_ps(256)(x)
x = upscale_ps(128)(x)
x = self_attn_block(x, 128) if use_self_attn else x
x = upscale_ps(64)(x)
x = res_block(x, 64)
x = self_attn_block(x, 64) if use_self_attn else x
#x = Conv2D(4, kernel_size=5, padding='same')(x)
alpha = Conv2D(1, kernel_size=5, padding='same', activation="sigmoid")(x)
rgb = Conv2D(3, kernel_size=5, padding='same', activation="tanh")(x)
out = concatenate([alpha, rgb])
return Model(input_, out)
encoder = Encoder()
decoder_A = Decoder_ps()
decoder_B = Decoder_ps()
x = Input(shape=IMAGE_SHAPE)
netGA = Model(x, decoder_A(encoder(x)))
netGB = Model(x, decoder_B(encoder(x)))
netDA = Discriminator(nc_D_inp)
netDB = Discriminator(nc_D_inp)
```
<a id='6'></a>
# 6. Load Models
```
try:
encoder.load_weights("models/encoder.h5")
decoder_A.load_weights("models/decoder_A.h5")
decoder_B.load_weights("models/decoder_B.h5")
#netDA.load_weights("models/netDA.h5")
#netDB.load_weights("models/netDB.h5")
print ("model loaded.")
except:
print ("Weights file not found.")
pass
```
<a id='7'></a>
# 7. Define Inputs/Outputs Variables
distorted_A: A (batch_size, 64, 64, 3) tensor, input of generator_A (netGA).
distorted_B: A (batch_size, 64, 64, 3) tensor, input of generator_B (netGB).
fake_A: (batch_size, 64, 64, 3) tensor, output of generator_A (netGA).
fake_B: (batch_size, 64, 64, 3) tensor, output of generator_B (netGB).
mask_A: (batch_size, 64, 64, 1) tensor, mask output of generator_A (netGA).
mask_B: (batch_size, 64, 64, 1) tensor, mask output of generator_B (netGB).
path_A: A function that takes distorted_A as input and outputs fake_A.
path_B: A function that takes distorted_B as input and outputs fake_B.
path_mask_A: A function that takes distorted_A as input and outputs mask_A.
path_mask_B: A function that takes distorted_B as input and outputs mask_B.
path_abgr_A: A function that takes distorted_A as input and outputs concat([mask_A, fake_A]).
path_abgr_B: A function that takes distorted_B as input and outputs concat([mask_B, fake_B]).
real_A: A (batch_size, 64, 64, 3) tensor, target images for generator_A given input distorted_A.
real_B: A (batch_size, 64, 64, 3) tensor, target images for generator_B given input distorted_B.
```
def cycle_variables(netG):
distorted_input = netG.inputs[0]
fake_output = netG.outputs[0]
alpha = Lambda(lambda x: x[:,:,:, :1])(fake_output)
rgb = Lambda(lambda x: x[:,:,:, 1:])(fake_output)
masked_fake_output = alpha * rgb + (1-alpha) * distorted_input
fn_generate = K.function([distorted_input], [masked_fake_output])
fn_mask = K.function([distorted_input], [concatenate([alpha, alpha, alpha])])
fn_abgr = K.function([distorted_input], [concatenate([alpha, rgb])])
return distorted_input, fake_output, alpha, fn_generate, fn_mask, fn_abgr
distorted_A, fake_A, mask_A, path_A, path_mask_A, path_abgr_A = cycle_variables(netGA)
distorted_B, fake_B, mask_B, path_B, path_mask_B, path_abgr_B = cycle_variables(netGB)
real_A = Input(shape=IMAGE_SHAPE)
real_B = Input(shape=IMAGE_SHAPE)
```
<a id='11'></a>
# 11. Helper Function: face_swap()
This function is provided for those who don't have enough VRAM to run dlib's CNN and GAN model at the same time.
INPUTS:
img: A RGB face image of any size.
path_func: a function that is either path_abgr_A or path_abgr_B.
OUPUTS:
result_img: A RGB swapped face image after masking.
result_mask: A single channel uint8 mask image.
```
def swap_face(img, path_func):
input_size = img.shape
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # generator expects BGR input
ae_input = cv2.resize(img, (64,64))/255. * 2 - 1
result = np.squeeze(np.array([path_func([[ae_input]])]))
result_a = result[:,:,0] * 255
result_a = cv2.resize(result_a, (input_size[1],input_size[0]))[...,np.newaxis]
result_bgr = np.clip( (result[:,:,1:] + 1) * 255 / 2, 0, 255)
result_bgr = cv2.resize(result_bgr, (input_size[1],input_size[0]))
result = (result_a/255 * result_bgr + (1 - result_a/255) * img).astype('uint8')
result = cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
result = cv2.resize(result, (input_size[1],input_size[0]))
result_a = np.expand_dims(cv2.resize(result_a, (input_size[1],input_size[0])), axis=2)
return result, result_a
whom2whom = "BtoA" # default trainsforming faceB to faceA
if whom2whom is "AtoB":
path_func = path_abgr_B
elif whom2whom is "BtoA":
path_func = path_abgr_A
else:
print ("whom2whom should be either AtoB or BtoA")
input_img = plt.imread("./IMAGE_FILENAME.jpg")
plt.imshow(input_img)
result_img, result_mask = swap_face(input_img, path_func)
plt.imshow(result_img)
plt.imshow(result_mask[:, :, 0]) # cmap='gray'
```
| github_jupyter |
### Privatizing Histograms
Sometimes we want to release the counts of individual outcomes in a dataset.
When plotted, this makes a histogram.
The library currently has two approaches:
1. Known category set `make_count_by_categories`
2. Unknown category set `make_count_by`
The next code block imports just handles boilerplate: imports, data loading, plotting.
```
import os
from opendp.meas import *
from opendp.mod import enable_features, binary_search_chain, Measurement, Transformation
from opendp.trans import *
from opendp.typing import *
enable_features("contrib")
max_influence = 1
budget = (1., 1e-8)
# public information
col_names = ["age", "sex", "educ", "race", "income", "married"]
data_path = os.path.join('.', 'data', 'PUMS_california_demographics_1000', 'data.csv')
size = 1000
with open(data_path) as input_data:
data = input_data.read()
def plot_histogram(sensitive_counts, released_counts):
"""Plot a histogram that compares true data against released data"""
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
fig = plt.figure()
ax = fig.add_axes([1,1,1,1])
plt.ylim([0,225])
tick_spacing = 1.
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.xlim(0,15)
width = .4
ax.bar(list([x+width for x in range(0, len(sensitive_counts))]), sensitive_counts, width=width, label='True Value')
ax.bar(list([x+2*width for x in range(0, len(released_counts))]), released_counts, width=width, label='DP Value')
ax.legend()
plt.title('Histogram of Education Level')
plt.xlabel('Years of Education')
plt.ylabel('Count')
plt.show()
```
### Private histogram via `make_count_by_categories`
This approach is only applicable if the set of potential values that the data may take on is public information.
If this information is not available, then use `make_count_by` instead.
It typically has greater utility than `make_count_by` until the size of the category set is greater than dataset size.
In this data, we know that the category set is public information:
strings consisting of the numbers between 1 and 20.
The counting aggregator computes a vector of counts in the same order as the input categories.
It also includes one extra count at the end of the vector,
consisting of the number of elements that were not members of the category set.
You'll notice that `make_base_geometric` has an additional argument that explicitly sets the type of the domain, `D`.
It defaults to `AllDomain[int]` which works in situations where the mechanism is noising a scalar.
However, in this situation, we are noising a vector of scalars,
and thus the appropriate domain is `VectorDomain[AllDomain[int]]`.
```
# public information
categories = list(map(str, range(1, 20)))
histogram = (
make_split_dataframe(separator=",", col_names=col_names) >>
make_select_column(key="educ", TOA=str) >>
# Compute counts for each of the categories and null
make_count_by_categories(categories=categories)
)
noisy_histogram = binary_search_chain(
lambda s: histogram >> make_base_geometric(scale=s, D=VectorDomain[AllDomain[int]]),
d_in=max_influence, d_out=budget[0])
sensitive_counts = histogram(data)
released_counts = noisy_histogram(data)
print("Educational level counts:\n", sensitive_counts[:-1])
print("DP Educational level counts:\n", released_counts[:-1])
print("DP estimate for the number of records that were not a member of the category set:", released_counts[-1])
plot_histogram(sensitive_counts, released_counts)
```
### Private histogram via `make_count_by`
This approach is applicable when the set of categories is unknown or very large.
Any categories with a noisy count less than a given threshold will be censored from the final release.
The noise scale influences the epsilon parameter of the budget, and the threshold influences the delta parameter in the budget.
`ptr` stands for Propose-Test-Release, a framework for censoring queries for which the local sensitivity is greater than some threshold.
Any category with a count sufficiently small is censored from the release.
It is sometimes referred to as a "stability histogram" because it only releases counts for "stable" categories that exist in all datasets that are considered "neighboring" to your private dataset.
I start out by defining a function that finds the tightest noise scale and threshold for which the stability histogram is (d_in, d_out)-close.
You may find this useful for your application.
```
def make_base_ptr_budget(
preprocess: Transformation,
d_in, d_out,
TK: RuntimeTypeDescriptor) -> Measurement:
"""Make a stability histogram that respects a given d_in, d_out.
:param preprocess: Transformation
:param d_in: Input distance to satisfy
:param d_out: Output distance to satisfy
:param TK: Type of Key (hashable)
"""
from opendp.mod import binary_search_param
def privatize(s, t=1e8):
return preprocess >> make_base_ptr(scale=s, threshold=t, TK=TK)
s = binary_search_param(lambda s: privatize(s=s), d_in, d_out)
t = binary_search_param(lambda t: privatize(s=s, t=t), d_in, d_out)
return privatize(s=s, t=t)
```
I now use the `make_count_by_ptr_budget` constructor to release a private histogram on the education data.
The stability mechanism, as currently written, samples from a continuous noise distribution.
If you haven't already, please read about [floating-point behavior in the docs](https://docs.opendp.org/en/latest/user/measurement-constructors.html#floating-point).
```
from opendp.mod import enable_features
enable_features("floating-point")
preprocess = (
make_split_dataframe(separator=",", col_names=col_names) >>
make_select_column(key="educ", TOA=str) >>
make_count_by(MO=L1Distance[float], TK=str, TV=float)
)
noisy_histogram = make_base_ptr_budget(
preprocess,
d_in=max_influence, d_out=budget,
TK=str)
sensitive_counts = histogram(data)
released_counts = noisy_histogram(data)
# postprocess to make the results easier to compare
postprocessed_counts = {k: round(v) for k, v in released_counts.items()}
print("Educational level counts:\n", sensitive_counts)
print("DP Educational level counts:\n", postprocessed_counts)
def as_array(data):
return [data.get(k, 0) for k in categories]
plot_histogram(sensitive_counts, as_array(released_counts))
```
| github_jupyter |
## Set up the dependencies
```
# for reading and validating data
import emeval.input.spec_details as eisd
import emeval.input.phone_view as eipv
import emeval.input.eval_view as eiev
# Visualization helpers
import emeval.viz.phone_view as ezpv
import emeval.viz.eval_view as ezev
# Metrics helpers
import emeval.metrics.segmentation as ems
# For plots
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
%matplotlib inline
# For maps
import folium
import branca.element as bre
# For easier debugging while working on modules
import importlib
import pandas as pd
import numpy as np
pd.options.display.float_format = '{:.6f}'.format
import arrow
THIRTY_MINUTES = 30 * 60
TIME_THRESHOLD = THIRTY_MINUTES
importlib.reload(ems)
```
## The spec
The spec defines what experiments were done, and over which time ranges. Once the experiment is complete, most of the structure is read back from the data, but we use the spec to validate that it all worked correctly. The spec also contains the ground truth for the legs. Here, we read the spec for the trip to UC Berkeley.
```
DATASTORE_URL = "http://cardshark.cs.berkeley.edu"
AUTHOR_EMAIL = "shankari@eecs.berkeley.edu"
sd_la = eisd.SpecDetails(DATASTORE_URL, AUTHOR_EMAIL, "unimodal_trip_car_bike_mtv_la")
sd_sj = eisd.SpecDetails(DATASTORE_URL, AUTHOR_EMAIL, "car_scooter_brex_san_jose")
sd_ucb = eisd.SpecDetails(DATASTORE_URL, AUTHOR_EMAIL, "train_bus_ebike_mtv_ucb")
```
## The views
There are two main views for the data - the phone view and the evaluation view.
### Phone view
In the phone view, the phone is primary, and then there is a tree that you can traverse to get the data that you want. Traversing that tree typically involves nested for loops; here's an example of loading the phone view and traversing it. You can replace the print statements with real code. When you are ready to check this in, please move the function to one of the python modules so that we can invoke it more generally
```
importlib.reload(eipv)
pv_la = eipv.PhoneView(sd_la)
pv_sj = eipv.PhoneView(sd_sj)
pv_ucb = eipv.PhoneView(sd_ucb)
```
## Number of detected trips versus ground truth trips
Checks to see how many spurious transitions there were
```
importlib.reload(ems)
ems.fill_sensed_trip_ranges(pv_la)
ems.fill_sensed_trip_ranges(pv_sj)
ems.fill_sensed_trip_ranges(pv_ucb)
pv_sj.map()["ios"]["ucb-sdb-ios-2"]["evaluation_ranges"][4]["trip_id"]
```
### Start and end times mismatch
```
curr_run = pv_la.map()["android"]["ucb-sdb-android-2"]["evaluation_ranges"][0]
print(curr_run.keys())
ems.find_matching_segments(curr_run["evaluation_trip_ranges"], "trip_id", curr_run["sensed_trip_ranges"])
[1,2,3][1:2]
def get_tradeoff_entries(pv):
tradeoff_entry_list = []
for phone_os, phone_map in pv.map().items():
print(15 * "=*")
print(phone_os, phone_map.keys())
for phone_label, phone_detail_map in phone_map.items():
print(4 * ' ', 15 * "-*")
print(4 * ' ', phone_label, phone_detail_map.keys())
if "control" in phone_detail_map["role"]:
print("Ignoring %s phone %s since they are always on" % (phone_detail_map["role"], phone_label))
continue
# this spec does not have any calibration ranges, but evaluation ranges are actually cooler
for r in phone_detail_map["evaluation_ranges"]:
print(8 * ' ', 30 * "=")
print(8 * ' ',r.keys())
print(8 * ' ',r["trip_id"], r["eval_common_trip_id"], r["eval_role"], len(r["evaluation_trip_ranges"]))
bcs = r["battery_df"]["battery_level_pct"]
delta_battery = bcs.iloc[0] - bcs.iloc[-1]
print("Battery starts at %d, ends at %d, drain = %d" % (bcs.iloc[0], bcs.iloc[-1], delta_battery))
sensed_trips = len(r["sensed_trip_ranges"])
visit_reports = len(r["visit_sensed_trip_ranges"])
matching_trip_map = ems.find_matching_segments(r["evaluation_trip_ranges"], "trip_id", r["sensed_trip_ranges"])
print(matching_trip_map)
for trip in r["evaluation_trip_ranges"]:
sensed_trip_range = matching_trip_map[trip["trip_id"]]
results = ems.get_count_start_end_ts_diff(trip, sensed_trip_range)
print("Got results %s" % results)
tradeoff_entry = {"phone_os": phone_os, "phone_label": phone_label,
"timeline": pv.spec_details.curr_spec["id"],
"range_id": r["trip_id"],
"run": r["trip_run"], "duration": r["duration"],
"role": r["eval_role_base"], "battery_drain": delta_battery,
"trip_count": sensed_trips, "visit_reports": visit_reports,
"trip_id": trip["trip_id"]}
tradeoff_entry.update(results)
tradeoff_entry_list.append(tradeoff_entry)
return tradeoff_entry_list
# We are not going to look at battery life at the evaluation trip level; we will end with evaluation range
# since we want to capture the overall drain for the timeline
tradeoff_entries_list = []
tradeoff_entries_list.extend(get_tradeoff_entries(pv_la))
tradeoff_entries_list.extend(get_tradeoff_entries(pv_sj))
tradeoff_entries_list.extend(get_tradeoff_entries(pv_ucb))
tradeoff_df = pd.DataFrame(tradeoff_entries_list)
r2q_map = {"power_control": 0, "HAMFDC": 1, "MAHFDC": 2, "HAHFDC": 3, "accuracy_control": 4}
q2r_map = {0: "power", 1: "HAMFDC", 2: "MAHFDC", 3: "HAHFDC", 4: "accuracy"}
# Make a number so that can get the plots to come out in order
tradeoff_df["quality"] = tradeoff_df.role.apply(lambda r: r2q_map[r])
tradeoff_df["count_diff"] = tradeoff_df[["count"]] - 1
import itertools
```
## Trip count analysis
### Scatter plot
```
ifig, ax = plt.subplots(nrows=1, ncols=1, figsize=(12,4))
errorboxes = []
for key, df in tradeoff_df.query("phone_os == 'android'").groupby(["role", "timeline"]):
print(key, df)
tcd = df.trip_count
bd = df.battery_drain
print("Plotting rect with params %s, %d, %d" % (str((tcd.min(), bd.min())),
tcd.max() - tcd.min(),
bd.max() - bd.min()))
print(tcd.min(), tcd.max(), tcd.std())
xerror = np.array([[tcd.min(), tcd.max()]])
print(xerror.shape)
ax.errorbar(x=tcd.mean(), y=bd.mean(), xerr=[[tcd.min()], [tcd.max()]], yerr=[[bd.min()], [bd.max()]], label=key)
plt.legend()
```
### Timeline + trip specific variation
How many sensed trips matched to each ground truth trip?
```
ifig, ax_array = plt.subplots(nrows=2,ncols=3,figsize=(9,6), sharex=False, sharey=True)
timeline_list = ["train_bus_ebike_mtv_ucb", "car_scooter_brex_san_jose", "unimodal_trip_car_bike_mtv_la"]
for i, tl in enumerate(timeline_list):
tradeoff_df.query("timeline == @tl & phone_os == 'android'").boxplot(ax = ax_array[0][i], column=["count_diff"], by=["quality"])
ax_array[0][i].set_title(tl)
tradeoff_df.query("timeline == @tl & phone_os == 'ios'").boxplot(ax = ax_array[1][i], column=["count_diff"], by=["quality"])
ax_array[1][i].set_title("")
# tradeoff_df.query("timeline == @tl & phone_os == 'ios'").boxplot(ax = ax_array[2][i], column=["visit_reports"], by=["quality"])
# ax_array[2][i].set_title("")
# print(android_ax_returned.shape, ios_ax_returned.shape)
for i, ax in enumerate(ax_array[0]):
ax.set_xticklabels([q2r_map[int(t.get_text())] for t in ax.get_xticklabels()])
ax.set_xlabel("")
for i, ax in enumerate(ax_array[1]):
ax.set_xticklabels([q2r_map[int(t.get_text())] for t in ax.get_xticklabels()])
ax.set_xlabel("")
# for ax in ax_array[1]:
# ax.set_xticklabels(q2r_ios_list[1:])
# ax.set_xlabel("")
# for ax in ax_array[2]:
# ax.set_xticklabels(q2r_ios_list[1:])
# ax.set_xlabel("")
ax_array[0][0].set_ylabel("Difference in trip counts (android)")
ax_array[1][0].set_ylabel("Difference in trip counts (ios)")
# ax_array[2][0].set_ylabel("Difference in visit reports (ios)")
ifig.suptitle("Trip count differences v/s configured quality over multiple timelines")
# ifig.tight_layout()
```
### Timeline specific variation
```
def plot_count_with_errors(ax_array, phone_os):
for i, (tl, trip_gt) in enumerate(timeline_trip_gt.items()):
ax_array[i].bar(0, trip_gt)
for q in range(1,4):
curr_df = tradeoff_df.query("timeline == @tl & phone_os == @phone_os & quality == @q")
print("%s %s %s values = %s %s %s" % (phone_os, tl, q2r_map[q], curr_df.trip_count.min(), curr_df.trip_count.mean(), curr_df.trip_count.max()))
lower_error = curr_df.trip_count.mean() - curr_df.trip_count.min()
upper_error = curr_df.trip_count.max() - curr_df.trip_count.mean()
ax_array[i].bar(x=q, height=curr_df.trip_count.mean(),
yerr=[[lower_error], [upper_error]])
print("%s %s %s errors = %s %s %s" % (phone_os, tl, q2r_map[q], lower_error, curr_df.trip_count.mean(), upper_error))
ax_array[i].set_title(tl)
ifig, ax_array = plt.subplots(nrows=2,ncols=3,figsize=(10,5), sharex=False, sharey=True)
timeline_trip_gt = {"train_bus_ebike_mtv_ucb": 3,
"car_scooter_brex_san_jose": 2,
"unimodal_trip_car_bike_mtv_la": 2}
plot_count_with_errors(ax_array[0], "android")
plot_count_with_errors(ax_array[1], "ios")
for ax in ax_array[0]:
ax.set_xticks(range(0,4))
ax.set_xticklabels(["truth"] + [q2r_map[r] for r in range(1,4)])
ax.set_yticks(range(0,tradeoff_df.trip_count.max(),3))
for ax in ax_array[1]:
ax.set_xticks(range(0,4))
ax.set_xticklabels(["truth"] + [q2r_map[r] for r in range(1,4)])
ax.set_yticks(range(0,tradeoff_df.trip_count.max(),3))
ax_array[0,0].set_ylabel("nTrips (android)")
ax_array[1,0].set_ylabel("nTrips (ios)")
ifig.tight_layout(pad=0.85)
```
## Start end results
```
for r, df in tradeoff_df.query("timeline == @tl & phone_os == 'android'").groupby("role"):
print(r, df.trip_count.mean() , df.trip_count.min(), df.trip_count.max())
```
The HAHFDC phone ran out of battery on all three runs of the `train_bus_ebike_mtv_ucb` timeline, so the trips never ended. Let's remove those so that they don't obfuscate the values from the other runs.
```
out_of_battery_phones = tradeoff_df.query("timeline=='train_bus_ebike_mtv_ucb' & role=='HAHFDC' & trip_id=='berkeley_to_mtv_SF_express_bus_0' & phone_os == 'android'")
for i in out_of_battery_phones.index:
tradeoff_df.loc[i,"end_diff_mins"] = float('nan')
tradeoff_df.query("timeline=='train_bus_ebike_mtv_ucb' & role=='HAHFDC' & trip_id=='berkeley_to_mtv_SF_express_bus_0' & phone_os == 'android'")
```
### Overall results
```
ifig, ax_array = plt.subplots(nrows=1,ncols=4,figsize=(16,4), sharex=False, sharey=True)
tradeoff_df.query("phone_os == 'android'").boxplot(ax = ax_array[0], column=["start_diff_mins"], by=["quality"])
ax_array[0].set_title("start time (android)")
tradeoff_df.query("phone_os == 'android'").boxplot(ax = ax_array[1], column=["end_diff_mins"], by=["quality"])
ax_array[1].set_title("end time (android)")
tradeoff_df.query("phone_os == 'ios'").boxplot(ax = ax_array[2], column=["start_diff_mins"], by=["quality"])
ax_array[2].set_title("start_time (ios)")
tradeoff_df.query("phone_os == 'ios'").boxplot(ax = ax_array[3], column=["end_diff_mins"], by=["quality"])
ax_array[3].set_title("end_time (ios)")
# print(android_ax_returned.shape, ios_ax_returned.shape)
ax_array[0].set_xticklabels([q2r_map[int(t.get_text())] for t in ax_array[0].get_xticklabels()])
ax_array[1].set_xticklabels([q2r_map[int(t.get_text())] for t in ax_array[1].get_xticklabels()])
ax_array[2].set_xticklabels([q2r_map[int(t.get_text())] for t in ax_array[2].get_xticklabels()])
ax_array[3].set_xticklabels([q2r_map[int(t.get_text())] for t in ax_array[3].get_xticklabels()])
for ax in ax_array:
ax.set_xlabel("")
ax_array[1].text(0.55,25,"Excluding trips where battery ran out")
ax_array[0].set_ylabel("Diff (mins)")
ifig.suptitle("Trip start end accuracy v/s configured quality")
ifig.tight_layout(pad=1.7)
```
### Timeline specific
```
ifig, ax_array = plt.subplots(nrows=4,ncols=3,figsize=(10,10), sharex=False, sharey=True)
timeline_list = ["train_bus_ebike_mtv_ucb", "car_scooter_brex_san_jose", "unimodal_trip_car_bike_mtv_la"]
for i, tl in enumerate(timeline_list):
tradeoff_df.query("timeline == @tl & phone_os == 'android'").boxplot(ax = ax_array[0][i], column=["start_diff_mins"], by=["quality"])
ax_array[0][i].set_title(tl)
tradeoff_df.query("timeline == @tl & phone_os == 'android'").boxplot(ax = ax_array[1][i], column=["end_diff_mins"], by=["quality"])
ax_array[1][i].set_title("")
tradeoff_df.query("timeline == @tl & phone_os == 'ios'").boxplot(ax = ax_array[2][i], column=["start_diff_mins"], by=["quality"])
ax_array[2][i].set_title("")
tradeoff_df.query("timeline == @tl & phone_os == 'ios'").boxplot(ax = ax_array[3][i], column=["end_diff_mins"], by=["quality"])
ax_array[3][i].set_title("")
# print(android_ax_returned.shape, ios_ax_returned.shape)
for ax in ax_array[0]:
ax.set_xticklabels([q2r_map[int(t.get_text())] for t in ax.get_xticklabels()])
ax.set_xlabel("")
for ax in ax_array[1]:
ax.set_xticklabels([q2r_map[int(t.get_text())] for t in ax.get_xticklabels()])
ax.set_xlabel("")
ax_array[1,0].text(0.55,25,"Excluding trips where battery ran out")
for ax in ax_array[2]:
ax.set_xticklabels([q2r_map[int(t.get_text())] for t in ax.get_xticklabels()])
ax.set_xlabel("")
for ax in ax_array[3]:
ax.set_xticklabels([q2r_map[int(t.get_text())] for t in ax.get_xticklabels()])
ax.set_xlabel("")
ax_array[0][0].set_ylabel("Start time diff (android)")
ax_array[1][0].set_ylabel("End time diff (android)")
ax_array[2][0].set_ylabel("Start time diff (ios)")
ax_array[3][0].set_ylabel("End time diff (ios)")
ifig.suptitle("Trip start end accuracy (mins) v/s configured quality over multiple timelines")
# ifig.tight_layout(pad=2.5)
```
## Outlier checks
We can have unexpected values for both time and count. Unfortunately, there is no overlap between the two (intersection is zero). So we will look at a random sample from both cases
```
expected_legs = "&".join(["not (trip_id == 'bus trip with e-scooter access_0' & count == 2)",
"not (trip_id == 'mtv_to_berkeley_sf_bart_0' & count == 3)"])
count_outliers = tradeoff_df.query("count > 1 & %s" % expected_legs)
count_outliers[["phone_os", "range_id", "trip_id", "run", "role", "count", "start_diff_mins", "end_diff_mins"]].head()
tradeoff_df.query("count < 1 & role == 'HAHFDC'")
time_outliers = tradeoff_df.query("start_diff_mins == 30 | end_diff_mins == 30")
time_outliers[["phone_os", "range_id", "trip_id", "run", "role", "start_diff_mins", "end_diff_mins"]].head()
print(len(time_outliers.index.union(count_outliers.index)), len(time_outliers.index.intersection(count_outliers.index)))
time_outliers.sample(n=3, random_state=1)[["phone_os", "range_id", "trip_id", "run", "role", "count", "start_diff_mins", "end_diff_mins"]]
count_outliers.sample(n=3, random_state=1)[["phone_os", "range_id", "trip_id", "run", "role", "count", "start_diff_mins", "end_diff_mins"]]
fmt = lambda ts: arrow.get(ts).to("America/Los_Angeles")
def check_outlier(eval_range, trip_idx, mismatch_key):
eval_trip_range = eval_range["evaluation_trip_ranges"][trip_idx]
print("Trip %s, ground truth experiment for metric %s, %s, trip %s" % (eval_range["trip_id"], mismatch_key, fmt(eval_range[mismatch_key]), fmt(eval_trip_range[mismatch_key])))
print(eval_trip_range["transition_df"][["transition", "fmt_time"]])
print("**** For entire experiment ***")
print(eval_range["transition_df"][["transition", "fmt_time"]])
if mismatch_key == "end_ts":
# print("Transitions after trip end")
# print(eval_range["transition_df"].query("ts > %s" % eval_trip_range["end_ts"])[["transition", "fmt_time"]])
return ezpv.display_map_detail_from_df(eval_trip_range["location_df"])
else:
return ezpv.display_map_detail_from_df(eval_trip_range["location_df"])
```
##### MAHFDC is just terrible
It looks like with MAHFDC, we essentially get no trip ends on android. Let's investigate these a bit further.
- run 0: trip never ended: trip actually ended just before next trip started `15:01:26`. And then next trip had geofence exit, but we didn't detect it because it never ended, so we didn't create a sensed range for it.
- run 1: trip ended but after 30 mins: similar behavior; trip ended just before next trip started `15:49:39`.
```
tradeoff_df.query("phone_os == 'android' & role == 'MAHFDC' & timeline == 'car_scooter_brex_san_jose'")[["range_id", "trip_id", "run", "role", "count", "start_diff_mins", "end_diff_mins"]]
FMT_STRING = "HH:mm:SS"
for t in pv_sj.map()["android"]["ucb-sdb-android-3"]["evaluation_ranges"][3]["evaluation_trip_ranges"]:
print(sd_sj.fmt(t["start_ts"], FMT_STRING), "->", sd_sj.fmt(t["end_ts"], FMT_STRING))
pv_sj.map()["android"]["ucb-sdb-android-3"]["evaluation_ranges"][3]["transition_df"]
FMT_STRING = "HH:mm:SS"
for t in pv_sj.map()["android"]["ucb-sdb-android-3"]["evaluation_ranges"][4]["evaluation_trip_ranges"]:
print(sd_sj.fmt(t["start_ts"], FMT_STRING), "->", sd_sj.fmt(t["end_ts"], FMT_STRING))
pv_sj.map()["android"]["ucb-sdb-android-3"]["evaluation_ranges"][4]["transition_df"]
```
##### Visit detection kicked in almost at the end of the trip
```
# 44 ios suburb_city_driving_weekend_0 1 HAMFDC 0 30.000000 30.000000
check_outlier(pv_la.map()["ios"]["ucb-sdb-ios-3"]["evaluation_ranges"][4], 0, "start_ts")
```
##### Trip end never detected
Trip ended at 14:11, experiment ended at 14:45. No stopped_moving for the last trip
```
# 65 android bus trip with e-scooter access_0 2 HAMFDC 1 3.632239 30.000000
check_outlier(pv_sj.map()["android"]["ucb-sdb-android-3"]["evaluation_ranges"][2], 1, "end_ts")
```
##### Trip end detection errors on iOS
Original experiment, explanation for the outliers on the HAHFDC and MAHFDC first runs to San Jose
- HAHFDC: Trip end detected 1.5 hours after real end, but before next trip start
- MAHFDC: Trip end detected 5 hours after real end, at the end of the next trip
- MAHFDC: Clearly this was not even detected as a separate trip, so this is correct. There was a spurious trip from `17:42:22` - `17:44:22` which ended up matching this. But clearly because of the missing trip end detection, both the previous trip and this one were incorrect. You can click on the points at the Mountain View library to confirm when the trip ended.
```
fig = bre.Figure()
fig.add_subplot(1,3,1).add_child(check_outlier(pv_sj.map()["ios"]["ucb-sdb-ios-2"]["evaluation_ranges"][0], 0, "end_ts"))
fig.add_subplot(1,3,2).add_child(check_outlier(pv_sj.map()["ios"]["ucb-sdb-ios-3"]["evaluation_ranges"][0], 0, "end_ts"))
fig.add_subplot(1,3,3).add_child(check_outlier(pv_sj.map()["ios"]["ucb-sdb-ios-3"]["evaluation_ranges"][0], 1, "start_ts"))
# check_outlier(pv_sj.map()["ios"]["ucb-sdb-ios-2"]["evaluation_ranges"][0], 0, "end_ts")
```
##### No geofence exit ever detected
On the middle trip of the second round of data collection to the San Jose library, we got no geofence exits. The entire list of transitions is
```
transition fmt_time
3 T_VISIT_ENDED 2019-08-06T11:29:20.573817-07:00
6 T_VISIT_STARTED 2019-08-06T11:29:20.911773-07:00
8 T_VISIT_ENDED 2019-08-06T11:35:38.250980-07:00
9 T_VISIT_STARTED 2019-08-06T12:00:05.445936-07:00
12 T_TRIP_ENDED 2019-08-06T12:00:07.093790-07:00
15 T_VISIT_ENDED 2019-08-06T15:59:13.998068-07:00
18 T_VISIT_STARTED 2019-08-06T17:12:38.808743-07:00
21 T_TRIP_ENDED 2019-08-06T17:12:40.504285-07:00
```
We did get visit notifications, so we did track location points (albeit after a long time), and we did get the trip end notifications, but we have no sensed trips. Had to handle this in the code as well
```
check_outlier(pv_sj.map()["ios"]["ucb-sdb-ios-2"]["evaluation_ranges"][4], 0, "start_ts")
```
##### No geofence exit ever detected
On the middle trip of the second round of data collection to the San Jose library, we got no geofence exits.
We did get visit notifications, so we did track location points (albeit after a long time), and we did get the trip end notifications, but we have no sensed trips. Had to handle this in the code as well
```
# 81 ios bus trip with e-scooter access_0 1 HAHFDC 0 30.000000 30.000000
check_outlier(pv_sj.map()["ios"]["ucb-sdb-ios-2"]["evaluation_ranges"][4], 1, "end_ts")
```
### 7 mapped trips for one
This is essentially from the time that I wandered around looking for the bikeshare bike. This raises the question of whether I should filter out the points within the polygon in this case too. Overall, I think not. The only part within the polygon that we don't guarantee is the ground truth trajectory. We still do have the ground truth of the trip/section start end, and there really is no reason why we should have had so many "trips" when I was walking around. I certainly didn't wait for too long while walking and this was not semantically a "trip" by any stretch of the imagination.
```
# 113 android berkeley_to_mtv_SF_express_bus_0 2 HAMFDC 7 2.528077 3.356611
check_outlier(pv_ucb.map()["android"]["ucb-sdb-android-3"]["evaluation_ranges"][2], 2, "end_ts")
```
### Trip split into two in medium accuracy *only*
Actual trip ends at `14:21`. In medium accuracy, detected trips were `14:12:15 -> 14:17:33` and `14:22:14 -> 14:24:15`. This was after we reached the destination, but there is a large gap because we basically got no points for a large part of the trip. This seems correct - it looks like iOS is just prematurely detecting the trip end in the MA case.
```
# 127 ios walk_urban_university_0 1 MAHFDC 2 4.002549 2.352913
fig = bre.Figure()
def compare_med_high_accuracy():
trip_idx = 1
mismatch_key = "end_ts"
ha_range = pv_ucb.map()["ios"]["ucb-sdb-ios-2"]["evaluation_ranges"][1]
ha_trip_range = ha_range["evaluation_trip_ranges"][trip_idx]
eval_range = pv_ucb.map()["ios"]["ucb-sdb-ios-3"]["evaluation_ranges"][1]
eval_trip_range = eval_range["evaluation_trip_ranges"][trip_idx]
print("Trip %s, ground truth experiment for metric %s, %s, trip %s, high accuracy %s" %
(eval_range["trip_id"], mismatch_key,
fmt(eval_range[mismatch_key]), fmt(eval_trip_range[mismatch_key]), fmt(ha_trip_range[mismatch_key])))
print(eval_trip_range["transition_df"][["transition", "fmt_time"]])
print("**** Expanded ***")
print(eval_range["transition_df"].query("%s < ts < %s" %
((eval_trip_range["end_ts"] - 30*60), (eval_trip_range["end_ts"] + 30*60)))[["transition", "fmt_time"]])
fig = bre.Figure()
fig.add_subplot(1,2,1).add_child(ezpv.display_map_detail_from_df(ha_trip_range["location_df"]))
fig.add_subplot(1,2,2).add_child(ezpv.display_map_detail_from_df(eval_trip_range["location_df"]))
return fig
compare_med_high_accuracy()
[{'start_ts': fmt(1564089135.368705), 'end_ts': fmt(1564089453.8783798)},
{'start_ts': fmt(1564089734.305933), 'end_ts': fmt(1564089855.8683748)}]
```
### We just didn't detect any trip ends in the middle
We only detected a trip end at the Mountain View station. This is arguably more correct than the multiple trips that we get with a dwell time.
```
# 120 ios mtv_to_berkeley_sf_bart_0 2 HAHFDC 2 3.175024 1.046759
check_outlier(pv_ucb.map()["ios"]["ucb-sdb-ios-2"]["evaluation_ranges"][2], 0, "end_ts")
```
| github_jupyter |
<a href="https://colab.research.google.com/github/project-ccap/project-ccap.github.io/blob/master/2021notebooks/2021_1010facial_keypoints_detection.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# -*- coding: utf-8 -*-
```
---
title: Getting Started with Facial Keypoint Detection using Deep Learning and PyTorch
author: Sovit Ranjan
date: 2020October
source: https://debuggercafe.com/getting-started-with-facial-keypoint-detection-using-pytorch/
---
- [Kaggle](https://www.kaggle.com/c/facial-keypoints-detection/data)
- Kaggle からデータ入手
```bash
kaggle competitions download -c facial-keypoints-detection
```
```
%%shell
curl -sc /tmp/cookie "https://drive.google.com/uc?export=download&id=1r1XxfBOQMzfhaohgg6aq-KbsYACkiWNa" > /dev/null
CODE="$(awk '/_warning_/ {print $NF}' /tmp/cookie)"
curl -Lb /tmp/cookie "https://drive.google.com/uc?export=download&confirm=${CODE}&id=1r1XxfBOQMzfhaohgg6aq-KbsYACkiWNa" -o kaggle_facial_keypoints_detection.tar.gz
!gunzip kaggle_facial_keypoints_detection.tar.gz
!tar -xf kaggle_facial_keypoints_detection.tar
```
# 深層学習とPyTorchを使った顔のキーポイント検出
PyTorch を使った顔のキーポイント検出デモ
<center>
<img src="https://debuggercafe.com/wp-content/uploads/2020/10/intro_exmp.png" width="33%"><br/>
<p style="text-align:left;width:88%; background-color:cornsilk">
Figure 1. An example of facial keypoint detection using deep learning and PyTorch. We will try to achieve similar results after going through this tutorial.
</p>
</center>
図 1 は濃淡画像上での顔のキーポイント検出の例です。
このチュートリアルの終わりまでに, 同様の結果を得ることを目標としています。
* 顔のキーポイント検出の必要性を簡単に紹介します。
* 深層学習と PyTorch を使って、顔のキーポイント検出を始めるための簡単なデータセットを使用しています。
* シンプルな畳み込みニューラルネットワークモデルを使って、データセット上で訓練を行います。
* 次に、訓練されたモデルを使って、テストデータセットの未見の画像の顔のキーポイントを検出します。
* 最後に、メリット、デメリット、さらなる実験と改善のために取るべきステップにたどり着きます。
# 1. なぜ顔のキーポイント検出が必要なのか?
先に進む前に、素朴な疑問に答えてみましょう。
なぜ、顔のキーポイント検出のような技術が必要なのか?たくさんありますが、いくつかをご紹介します。
スマートフォンのアプリで, フィルターを見たことがある人も多いのではないでしょうか。
このようなフィルターを顔に正確に適用するためには,人の顔のキーポイント (注目点) を正しく判断する必要があります。
そのためには, 顔のキーポイントを検出する必要があります。
また、顔のキーポイント検出は、人の年齢を判定するのにも利用できます。
実際、多くの産業や企業がこの技術を利用しています。
顔認証によるスマートフォンのロック解除にも、顔のキーポイント検出が使われています。
上記は、実際の使用例の一部に過ぎません。
他にもたくさんありますが、それらの詳細については今は触れません。
もっと詳しく知りたい方は、ユースケースについてより多くのポイントを説明した[こちらの記事をお読みください](https://www.facefirst.com/blog/amazing-uses-for-face-recognition-facial-recognition-use-cases/)。
上述したように、このチュートリアルでは、顔のキーポイント検出にディープラーニングを使用します。
深層学習と畳み込みニューラルネットワークは、現在、顔認識とキーポイント検出の分野で大きな役割を果たしています。
## 1.1 データセット
<!-- ## 1.1 The Dataset-->
過去に開催された Kaggle のコンペティションのデータセットを使用します。
競技名は Facial Keypoints Detection です。
競技のルールに同意した後、データセットをダウンロードするように言われたら、ダウンロードしてください。
データセットは大きくありません。約 80 MBしかありません。
訓練データセットとテストデータセットを含む CSV ファイルで構成されています。
画像も CSV ファイルの中にピクセル値で入っています。
画像はすべて 96×96 次元の濃淡画像です。
濃淡画像で次元が小さいため、深層学習による顔のキーポイント検出を始めるのに適した、簡単なデータセットです。
このデータセットには (x, y) 形式の 15 個の座標特徴のキーポイントが含まれています。
つまり、各顔画像には合計 30 個のポイント特徴があるということです。
すべてのデータポイントは CSV ファイルの異なる列に入っており、最後の列には画像のピクセル値が入っています。
<!--
We will use a dataset from one of the past Kaggle competitions.
The competition is Facial Keypoints Detection. Go ahead and download the dataset after accepting the competition rules if it asks you to do so.
The dataset is not big. It is only around 80 MB.
It consists of CSV files containing the training and test dataset.
The images are also within the CSV files with the pixel values.
All the images are 96×96 dimensional grayscale images.
As the images are grayscale and small in dimension, that is why it is a good and easy dataset to start with facial keypoint detection using deep learning.
The dataset contains the keypoints for 15 coordinate features in the form of (x, y).
So, there are a total of 30 point features for each face image.
All the data points are in different columns of the CSV file with the final column holding the image pixel values.-->
次のコードスニペットは CSV ファイルのデータフォーマットを示しています。
<!-- The following code snippet shows the data format in the CSV files. -->
<pre style="background-color:powderblue">
left_eye_center_x left_eye_center_y right_eye_center_x ... mouth_center_bottom_lip_x mouth_center_bottom
_lip_y Image
0 66.033564 39.002274 30.227008 ... 43.130707
84.485774 238 236 237 238 240 240 239 241 241 243 240 23...
1 64.332936 34.970077 29.949277 ... 45.467915
85.480170 219 215 204 196 204 211 212 200 180 168 178 19...
2 65.057053 34.909642 30.903789 ... 47.274947
78.659368 144 142 159 180 188 188 184 180 167 132 84 59 ...
3 65.225739 37.261774 32.023096 ... 51.561183
78.268383 193 192 193 194 194 194 193 192 168 111 50 12 ...
4 66.725301 39.621261 32.244810 ... 44.227141
86.871166 147 148 160 196 215 214 216 217 219 220 206 18...
... ... ... ... ... ...
... ...
7044 67.402546 31.842551 29.746749 ... 50.426637
79.683921 71 74 85 105 116 128 139 150 170 187 201 209 2...
7045 66.134400 38.365501 30.478626 ... 50.287397
77.983023 60 60 62 57 55 51 49 48 50 53 56 56 106 89 77 ...
7046 66.690732 36.845221 31.666420 ... 49.462572
78.117120 74 74 74 78 79 79 79 81 77 78 80 73 72 81 77 1...
7047 70.965082 39.853666 30.543285 ... 50.065186
79.586447 254 254 254 254 254 238 193 145 121 118 119 10...
7048 66.938311 43.424510 31.096059 ... 45.900480
82.773096 53 62 67 76 86 91 97 105 105 106 107 108 112 1...</pre>
キーポイントとなる特徴的な列を見ることができます。
このような列は、顔の左側と右側で30個あります。
最後の列は、ピクセル値を示す「画像」の列です。
これは文字列形式です。
このように、データセットに深層学習技術を適用する前に、少しだけ前処理を行う必要があります。
<!-- You can see the keypoint feature columns.
There are 30 such columns for the left and right sides of the face.
The last column is the Image column with the pixel values.
They are in string format.
So, we will have to do a bit of preprocessing before we can apply our deep learning techniques to the dataset. -->
以下は、顔にキーポイントを設定した `training.csv` ファイルのサンプル画像です。
<!-- The following are some sample images from the training.csv file with the keypoints on the faces. -->
<center>
<img src="https://debuggercafe.com/wp-content/uploads/2020/10/training_samples.png" width="66%"><br/>
<p style="text-align:left;width:77%;background-color:cornsilk">
Figure 2. Some samples from the training set with their facial keypoints.
We will use this dataset to train our deep neural network using PyTorch.</p>
</center>
また、このデータセットには多くの欠損値が含まれています。
7048 個のインスタンス (行) のうち 4909 行は 1 つ以上の列で少なくとも 1 つの NULL 値を含んでいます。
また、全てのキーポイントが揃っている完全なデータは 2140 行のみです。
このような状況は、データセットを作成する際に対処しなければなりません。
# 2. 深層学習とPyTorchによる顔のキーポイント検出
<!-- # 2. Facial Keypoint Detection using Deep Learning and PyTorch -->
PyTorch フレームワークを使った顔のキーポイント検出のためのコーディング作業に入っていきます。
```
import torch
import torch.optim as optim
import matplotlib.pyplot as plt
import torch.nn as nn
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
!pip install japanize_matplotlib
import japanize_matplotlib
import torch
ROOT_PATH = 'kaggle_facial_keypoints_detection'
!mkdir outputs
OUTPUT_PATH = 'outputs'
# learning parameters
BATCH_SIZE = 256
LR = 0.0001
EPOCHS = 300
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# train/test split
TEST_SPLIT = 0.2
TEST_SPLIT = 0.1
# show dataset keypoint plot
SHOW_DATASET_PLOT = True
```
トレーニングと検証のための学習パラメータは以下の通りです。
* バッチサイズは 256 としています。
画像のサイズが 96×96 と小さく、また濃淡画像であるため,ミニバッチサイズを大きくしてもメモリの問題は発生しません。
ただし GPU のメモリに応じて、バッチサイズを自由に増減させてください。
* 学習率は 0.0001 です。
様々な学習率を試した結果、今回使用するモデルとデータセットでは、この学習率が最も安定していると思われます。
* 顔のキーポイントのデータセットに対して 300 エポックでモデルを学習します。
多いと思われるかもしれませんが、実際には, このように多くのエポックを行うことで, モデルは恩恵を受けます。
* 0.2 のテスト分割を使用しています。
データの 80 %をトレーニングに,20 %を検証に使用します。
* SHOW_DATASET_PLOT が True の場合, 訓練直前に,いくつかの顔と,それに対応する顔のキーポイントのプロットが表示されます。
必要であれば,これを False にしておくこともできます。
## 2.1 深層学習と PyTorch による顔のキーポイント検出のためのユーティリティー関数の作成
この節では、作業を容易にするためのユーティリティー関数をいくつか書きます。
ユーティリティー関数は全部で 3 つあります。
この 3 つのユーティリティー関数はすべて、顔の画像上に顔のキーポイントをプロットするのに役立ちます。
しかし 3 つとも異なるシナリオに対応しています。
1 つずつ取り組んでいきましょう。
### 2.1.1 顔に検証キーポイントをプロットする関数
まず、検証用のキーポイントをプロットする関数を紹介します。
この関数を `valid_keypoints_plot()` と呼ぶことにします。
この関数は基本的に,与えられた一定のエポック数の後に,画像の顔上に検証(回帰したキーポイント)をプロットします.
まずはコードを書いてみましょう。その後、重要な部分の説明に入ります。
```
def valid_keypoints_plot(image, outputs, orig_keypoints, epoch):
"""
This function plots the regressed (predicted) keypoints and the actual keypoints after each validation epoch for one image in the batch.
"""
# detach the image, keypoints, and output tensors from GPU to CPU
image = image.detach().cpu()
outputs = outputs.detach().cpu().numpy()
orig_keypoints = orig_keypoints.detach().cpu().numpy()
# just get a single datapoint from each batch
img = image[0]
output_keypoint = outputs[0]
orig_keypoint = orig_keypoints[0]
img = np.array(img, dtype=float)
img = np.transpose(img, (1, 2, 0))
img = img.reshape(96, 96)
plt.imshow(img, cmap='gray')
output_keypoint = output_keypoint.reshape(-1, 2)
orig_keypoint = orig_keypoint.reshape(-1, 2)
for p in range(output_keypoint.shape[0]):
plt.plot(output_keypoint[p, 0], output_keypoint[p, 1], 'r.')
plt.text(output_keypoint[p, 0], output_keypoint[p, 1], f"{p}")
plt.plot(orig_keypoint[p, 0], orig_keypoint[p, 1], 'g.')
plt.text(orig_keypoint[p, 0], orig_keypoint[p, 1], f"{p}")
plt.savefig(f"{OUTPUT_PATH}/val_epoch_{epoch}.png")
plt.close()
def test_keypoints_plot(images_list, outputs_list, figsize=(10,10)):
"""
This function plots the keypoints for the outputs and images
in `test.csv` file.
"""
plt.figure(figsize=figsize)
for i in range(len(images_list)):
outputs = outputs_list[i]
image = images_list[i]
outputs = outputs.cpu().detach().numpy()
outputs = outputs.reshape(-1, 2)
plt.subplot(3, 3, i+1)
#plt.imshow(image, cmap='gray')
plt.imshow(image.reshape(96,96), cmap='gray')
for p in range(outputs.shape[0]):
plt.plot(outputs[p, 0], outputs[p, 1], 'r.')
plt.text(outputs[p, 0], outputs[p, 1], f"{p}")
plt.axis('off')
plt.savefig(f"{OUTPUT_PATH}/test_output.pdf")
plt.show()
plt.close()
def dataset_keypoints_plot(data, figsize=(22,20), n_samples=30):
"""
This function shows the image faces and keypoint plots that the model will actually see.
This is a good way to validate that our dataset is in fact corrent and the faces align wiht the keypoint features.
The plot will be show just before training starts. Press `q` to quit the plot and start training.
"""
plt.figure(figsize=figsize)
for i in range(n_samples):
sample = data[i]
img = sample['image']
img = np.array(img, dtype=float)
img = np.transpose(img, (1, 2, 0))
img = img.reshape(96, 96)
plt.subplot(5, 6, i+1)
plt.imshow(img, cmap='gray')
keypoints = sample['keypoints']
for j in range(len(keypoints)):
plt.plot(keypoints[j, 0], keypoints[j, 1], 'r.')
plt.show()
plt.close()
```
最初の 2 行のコメントを読めば,この関数の要点が容易に理解できると思います。
画像テンソル(`image`),出力テンソル(`outputs`),データセットからのオリジナルキーポイント(`orig_keypoints`)を,エポック番号とともに関数に渡します.
<!-- If you read the comment in the first two lines then you will easily get the gist of the function.
We provide the image tensors (`image`), the output tensors (`outputs`), and the original keypoints from the dataset (`orig_keypoints`) along with the epoch number to the function.-->
* 7, 8, 9行目では GPU からデータを切り離し CPU にロードしています。
* テンソルは,画像,予測されたキーポイント,オリジナルのキーポイントそれぞれについて 256 個のデータポイントを含むバッチの形をしています.
12 行目から 14 行目で、それぞれの最初のデータポイントを取得します。
* 次に,画像を NumPy の配列形式に変換し,チャンネルを最後にして転置し,元の 96×96 のサイズに整形します。
そして,Matplotlib を使って画像をプロットします。
* 21 行目と 22 行目では,予測されたキーポイントと元のキーポイントの形状を変更します.
21 行目と 22 行目で,予測キーポイントとオリジナルキーポイントの形状を変更します.
* 23 行目から 27 行目まで,顔の画像上に予測キーポイントとオリジナルキーポイントをプロットします。
予測されたキーポイントは赤のドットで、オリジナルのキーポイントは緑のドットになります。
また,`plt.text()`を用いて,対応するキーポイントの番号をプロットします。
* 最後に,画像を `outputs` フォルダに保存します。
<!--
* At lines 7, 8, and 9 we detach the data from the GPU and load them onto the CPU.
* The tensors are in the form of a batch containing 256 datapoints each for the image, the predicted keypoints, and the original keypoints.
We get just the first datapoint from each from lines 12 to 14.
* Then we convert the image to NumPy array format, transpose it make channels last, and reshape it into the original 96×96 dimensions.
Then we plot the image using Matplotlib.
* At lines 21 and 22, we reshape the predicted and original keypoints.
This will make them have 2 columns along with the respective number of rows.
* Starting from lines 23 till 27, we plot the predicted and original keypoints on the image of the face.
The predicted keypoints will be red dots while the original keypoints will be green dots.
We also plot the corresponding keypoint numbers using `plt.text()`.
* Finally, we save the image in the `outputs` folder.
-->
Now, we will move onto the next function for the `utils.py` file.
### 2.1.2 テスト用キーポイントを顔にプロットする関数
<!-- ### 2.1.2 Function to Plot the Test Keypoints on the Faces -->
ここでは、テスト時に予測するキーポイントをプロットするためのコードを書きます。
具体的には `test.csv` ファイルにピクセル値が入っている画像が対象となります。
<!--
Here, we will write the code for plotting the keypoints that we will predict during testing.
Specifically, this is for those images whose pixel values are in the test.csv file. -->
```
import torch
import cv2
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
resize = 96
def train_test_split(csv_path, split):
df_data = pd.read_csv(csv_path)
# drop all the rows with missing values
df_data = df_data.dropna()
len_data = len(df_data)
# calculate the validation data sample length
valid_split = int(len_data * split)
# calculate the training data samples length
train_split = int(len_data - valid_split)
training_samples = df_data.iloc[:train_split][:]
valid_samples = df_data.iloc[-valid_split:][:]
print(f"訓練データサンプル数: {len(training_samples)}")
print(f"検証データサンプル数: {len(valid_samples)}")
return training_samples, valid_samples
class FaceKeypointDataset(Dataset):
def __init__(self, samples):
self.data = samples
# get the image pixel column only
self.pixel_col = self.data.Image
self.image_pixels = []
#for i in tqdm(range(len(self.data))):
for i in range(len(self.data)):
img = self.pixel_col.iloc[i].split(' ')
self.image_pixels.append(img)
self.images = np.array(self.image_pixels, dtype=float)
def __len__(self):
return len(self.images)
def __getitem__(self, index):
# reshape the images into their original 96x96 dimensions
image = self.images[index].reshape(96, 96)
orig_w, orig_h = image.shape
# resize the image into `resize` defined above
image = cv2.resize(image, (resize, resize))
# again reshape to add grayscale channel format
image = image.reshape(resize, resize, 1)
image = image / 255.0
# transpose for getting the channel size to index 0
image = np.transpose(image, (2, 0, 1))
# get the keypoints
keypoints = self.data.iloc[index][:30]
keypoints = np.array(keypoints, dtype=float)
# reshape the keypoints
keypoints = keypoints.reshape(-1, 2)
# rescale keypoints according to image resize
keypoints = keypoints * [resize / orig_w, resize / orig_h]
return {
'image': torch.tensor(image, dtype=torch.float),
'keypoints': torch.tensor(keypoints, dtype=torch.float),
}
# get the training and validation data samples
training_samples, valid_samples = train_test_split(f"{ROOT_PATH}/training.csv", TEST_SPLIT)
# initialize the dataset - `FaceKeypointDataset()`
print('--- PREPARING DATA ---')
train_data = FaceKeypointDataset(training_samples)
valid_data = FaceKeypointDataset(valid_samples)
print('--- DATA PREPRATION DONE ---')
# prepare data loaders
train_loader = DataLoader(train_data,
batch_size=BATCH_SIZE,
shuffle=True)
valid_loader = DataLoader(valid_data,
batch_size=BATCH_SIZE,
shuffle=False)
# whether to show dataset keypoint plots
if SHOW_DATASET_PLOT:
dataset_keypoints_plot(valid_data)
#dataset_keypoints_plot(valid_data,figsize=(24,20))
#dataset_keypoints_plot(train_data,figsize=(24,20))
#df_data = pd.read_csv(f"{ROOT_PATH}/training/training.csv")
#df_data
#from model import FaceKeypointModel
import torch.nn as nn
import torch.nn.functional as F
class FaceKeypointModel(nn.Module):
def __init__(self):
super(FaceKeypointModel, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3)
self.fc1 = nn.Linear(128, 30)
self.pool = nn.MaxPool2d(2, 2)
self.dropout = nn.Dropout2d(p=0.2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool(x)
x = F.relu(self.conv2(x))
x = self.pool(x)
x = F.relu(self.conv3(x))
x = self.pool(x)
bs, _, _, _ = x.shape
x = F.adaptive_avg_pool2d(x, 1).reshape(bs, -1)
x = self.dropout(x)
out = self.fc1(x)
return out
```
`test_keypoints_plot()` 関数の入力パラメータは, `images_list` と `outputs_list` です。
これらは, 指定された数の入力画像と, プロットしたい予測キーポイントを含む 2 つのリストです。
この関数は非常にシンプルです。
* 7 行目からは,単純な for ループを実行し,2 つのリストに含まれる画像と予測されるキーポイントをループします。
* `valid_keypoints_plot()` 関数と同じ経路をたどります。
* しかし,今回は,すべての画像を 1 つのプロットにしたいので,Matplotlib の `subplot()` 関数を利用します。
9 枚の画像をプロットするので,`plt.subplot(3, 3, i+1)` を使用します.
* 最後に, プロットされた画像と予測されたキーポイントを,出力フォルダに保存します。
以上でこの関数の説明は終わりです。
### 2.1.3 入力データセットの顔画像とキーポイントをプロットする関数
ニューラルネットワークモデルにデータを入力する前に,データが正しいかどうかを確認します。
すべてのキーポイントが顔に正しく対応しているかどうかは,わからないかもしれません。
そのため,学習開始前に,顔画像とそれに対応するキーポイントを表示する関数を書きます。
`SHOW_DATASET_PLOT = True` になっている場合のみ行われます。
```
import torch
import torch.optim as optim
import matplotlib.pyplot as plt
import torch.nn as nn
import matplotlib
# model
model = FaceKeypointModel().to(DEVICE)
# optimizer
optimizer = optim.Adam(model.parameters(), lr=LR)
# we need a loss function which is good for regression like MSELoss
criterion = nn.MSELoss()
# training function
def train(model, dataloader, data):
#print('Training')
model.train()
train_running_loss = 0.0
counter = 0
# calculate the number of batches
num_batches = int(len(data)/dataloader.batch_size)
for i, data in enumerate(dataloader): #, total=num_batches):
counter += 1
image, keypoints = data['image'].to(DEVICE), data['keypoints'].to(DEVICE)
# flatten the keypoints
keypoints = keypoints.view(keypoints.size(0), -1)
optimizer.zero_grad()
outputs = model(image)
loss = criterion(outputs, keypoints)
train_running_loss += loss.item()
loss.backward()
optimizer.step()
train_loss = train_running_loss/counter
return train_loss
# validatioon function
def validate(model, dataloader, data, epoch, print_interval=3):
#print('Validating')
model.eval()
valid_running_loss = 0.0
counter = 0
# calculate the number of batches
num_batches = int(len(data)/dataloader.batch_size)
with torch.no_grad():
for i, data in enumerate(dataloader): #, total=num_batches):
counter += 1
image, keypoints = data['image'].to(DEVICE), data['keypoints'].to(DEVICE)
# flatten the keypoints
keypoints = keypoints.view(keypoints.size(0), -1)
outputs = model(image)
loss = criterion(outputs, keypoints)
valid_running_loss += loss.item()
# plot the predicted validation keypoints after every...
# ... print_interval epochs and from the first batch
if (epoch+1) % print_interval == 0 and i == 0:
valid_keypoints_plot(image, outputs, keypoints, epoch)
valid_loss = valid_running_loss/counter
return valid_loss
EPOCHS
EPOCHS = 64 # 時間の都合上 EPOCHS を少なくしています
interval = EPOCHS >> 3
train_loss = []
val_loss = []
for epoch in range(EPOCHS):
train_epoch_loss = train(model, train_loader, train_data)
val_epoch_loss = validate(model, valid_loader, valid_data, epoch, print_interval=2)
train_loss.append(train_epoch_loss)
val_loss.append(val_epoch_loss)
if ((epoch) % interval) == 0:
print(f"エポック {epoch+1:<4d}/{EPOCHS:<4d}", end="")
print(f"訓練損失: {train_epoch_loss:.3f}",
f'検証損失: {val_epoch_loss:.3f}')
# loss plots
plt.figure(figsize=(10, 7))
plt.plot(train_loss, color='blue', label='訓練損失')
plt.plot(val_loss, color='red', label='検証損失')
plt.xlabel('エポック')
plt.ylabel('損失値')
plt.legend()
plt.savefig(f"{OUTPUT_PATH}/loss.pdf")
plt.show()
# 結果の保存
torch.save({
'epoch': EPOCHS,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': criterion,
}, f"{OUTPUT_PATH}/model.pth")
```
## 結果の再読み込みと視覚化
保存した結果を再度読み込んで表示します
```
model = FaceKeypointModel().to(DEVICE)
# load the model checkpoint
checkpoint = torch.load(f"{OUTPUT_PATH}/model.pth")
# load model weights state_dict
model.load_state_dict(checkpoint['model_state_dict'])
model.eval()
```
## テストデータによる結果の視覚化
`test.csv` を読み込んで,結果を表示します
```
model.eval()
# `test.csv` ファイルの読み込み
csv_file = f"{ROOT_PATH}/test.csv"
data = pd.read_csv(csv_file)
pixel_col = data.Image
image_pixels = []
for i in range(len(pixel_col)):
img = pixel_col[i].split(' ')
image_pixels.append(img)
# NumPy 配列へ変換
images = np.array(image_pixels, dtype=float)
```
## キーポイント予測結果の視覚化
9 つのデータを視覚化します。
予測されたキーポイントを取得し, `outputs` に格納します。
各前向き処理後に, 画像と出力をそれぞれ `images_list` と `outputs_list` に追加します。
最後に,`test_keypoints_plot()` を呼び出し,予測キーポイントを顔の画像上にプロットします。
検証結果と比較すると、テスト結果は良好に見えます。
```
images_list, outputs_list = [], []
for i in range(9):
with torch.no_grad():
image = images[i]
image = image.reshape(96, 96, 1)
image = cv2.resize(image, (resize, resize))
image = image.reshape(resize, resize, 1)
orig_image = image.copy()
image = image / 255.0
image = np.transpose(image, (2, 0, 1))
image = torch.tensor(image, dtype=torch.float)
image = image.unsqueeze(0).to(DEVICE)
# forward pass through the model
outputs = model(image)
# append the current original image
images_list.append(orig_image)
# append the current outputs
outputs_list.append(outputs)
test_keypoints_plot(images_list, outputs_list, figsize=(14,14))
```
| github_jupyter |
# Revisión Solver de Markowitz
**Código revisado**
## Librerias necesarias
```
#Librerias necesarias
!curl https://colab.chainer.org/install | sh -
import cupy as cp
import numpy as np
import pandas as pd
import fix_yahoo_finance as yf
import datetime
import matplotlib.pyplot as plt
import seaborn as sns
import time
```
A continuación creamos un arreglo con las acciones que utilizaremos.
```
stocks = ['COP','AMT','LIN','LMT','AMZN','WMT','JNJ','VTI','MSFT','GOOG','XOM','CCI','BHP.AX','UNP',
'BABA','NSRGY','RHHBY','VOO','AAPL','FB','CVX','PLD','RIO.L','HON','HD','PG','UNH','BRK-A','V','0700.HK',
'RDSA.AS','0688.HK','AI.PA','RTX','MC.PA','KO','PFE','JPM','005930.KS','VZ','RELIANCE.NS','DLR','2010.SR',
'UPS','7203.T','PEP','MRK','1398.HK','MA','T']
def extraer_datos_yahoo(stocks):
'''
Funcion para extraer datos de los portafolios de yahoo finance de 2015-01-01 a 2020-04-30
'''
df_c = yf.download(stocks, start='2015-01-01', end='2020-04-30').Close
base = df_c['AAPL'].dropna().to_frame()
for i in range(0,50):
base = base.join(df_c.iloc[:,i].to_frame(), lsuffix='_caller', rsuffix='_other')
base = base.drop(columns=['AAPL_caller'])
base = base.rename(columns={"AAPL_other": "AAPL"})
base = base.fillna(method='ffill')
base = base.fillna(method='bfill')
return base
datos = extraer_datos_yahoo(stocks)
```
Revisamos los filas de los datos
```
datos
```
## Funciones auxiliares
```
def calcular_rendimiento_vector(x):
"""
Función para calcular el rendimiento esperado
params:
x vector de precios
return:
r_est rendimiento esperado diario
"""
# Definimos precios iniciales y finales como arreglo alojado en la gpu
x_o = cp.asarray(x)
x_f = x_o[1:]
# Calculamos los rendimientos diarios
r = cp.log(x_f/x_o[:-1])
return r
def calcular_rendimiento(X):
"""
Función para calcular el rendimiento esperado para un conjunto de acciones
params:
X matriz mxn de precios, donde:
m es el número de observaciones y
n el número de acciones
return:
r_est rvector de rendimientos esperados
"""
m,n = X.shape
r_est = cp.zeros(n)
X = cp.asarray(X)
for i in range(n):
r_est[i] = calcular_rendimiento_vector(X[:,i]).mean()
return 264*r_est
def calcular_varianza(X):
"""
Función para calcular el la matriz de varianzas y covarianzas para un conjunto de acciones
params:
X matriz mxn de precios, donde:
m es el número de observaciones y
n el número de acciones
return:
S matriz de varianzas y covarianzas
"""
m,n=X.shape
X = cp.asarray(X)
X_m = cp.zeros((m-1,n))
for i in range(n):
X_m[:,i] = calcular_rendimiento_vector(X[:,i]) - calcular_rendimiento_vector(X[:,i]).mean()
S = (cp.transpose(X_m)@X_m)/(m-2)
return S
```
## Solución del modelo de Markowitz
```
def formar_vectores(mu, Sigma):
'''
Calcula las cantidades u = \Sigma^{-1} \mu y v := \Sigma^{-1} \cdot 1 del problema de Markowitz
Args:
mu (cupy array, vector): valores medios esperados de activos (dimension n)
Sigma (cupy array, matriz): matriz de covarianzas asociada a activos (dimension n x n)
Return:
u (cupy array, escalar): vector dado por \cdot Sigma^-1 \cdot mu (dimension n)
v (cupy array, escalar): vector dado por Sigma^-1 \cdot 1 (dimension n)
'''
# Vector auxiliar con entradas igual a 1
n = Sigma.shape[0]
ones_vector = cp.ones(n)
# Formamos vector \cdot Sigma^-1 mu y Sigm^-1 1
# Nota:
# 1) u= Sigma^-1 \cdot mu se obtiene resolviendo Sigma u = mu
# 2) v= Sigma^-1 \cdot 1 se obtiene resolviendo Sigma v = 1
# Obtiene vectores de interes
u = cp.linalg.solve(Sigma, mu)
u = u.transpose() # correcion de expresion de array
v = cp.linalg.solve(Sigma, ones_vector)
return u , v
def formar_abc(mu, Sigma):
'''
Calcula las cantidades A, B y C del diagrama de flujo del problema de Markowitz
Args:
mu (cupy array, vector): valores medios esperados de activos (dimension n)
Sigma (cupy array, matriz): matriz de covarianzas asociada a activos (dimension n x n)
Return:
A (cupy array, escalar): escalar dado por mu^t \cdot Sigma^-1 \cdot mu
B (cupy array, escalar): escalar dado por 1^t \cdot Sigma^-1 \cdot 1
C (cupy array, escalar): escalar dado por 1^t \cdot Sigma^-1 \cdot mu
'''
# Vector auxiliar con entradas igual a 1
n = Sigma.shape[0]
ones_vector = cp.ones(n)
# Formamos vector \cdot Sigma^-1 mu y Sigm^-1 1
# Nota:
# 1) u= Sigma^-1 \cdot mu se obtiene resolviendo Sigma u = mu
# 2) v= Sigma^-1 \cdot 1 se obtiene resolviendo Sigma v = 1
u, v = formar_vectores(mu, Sigma)
# Obtiene escalares de interes
A = mu.transpose()@u
B = ones_vector.transpose()@v
C = ones_vector.transpose()@u
return A, B, C
def delta(A,B,C):
'''
Calcula las cantidad Delta = AB-C^2 del diagrama de flujo del problema de Markowitz
Args:
A (cupy array, escalar): escalar dado por mu^t \cdot Sigma^-1 \cdot mu
B (cupy array, escalar): escalar dado por 1^t \cdot Sigma^-1 \cdot 1
C (cupy array, escalar): escalar dado por 1^t \cdot Sigma^-1 \cdot mu
Return:
Delta (cupy array, escalar): escalar dado \mu^t \cdot \Sigma^{-1} \cdot \mu
'''
Delta = A*B-C**2
return Delta
def formar_omegas(r, mu, Sigma):
'''
Calcula las cantidades w_o y w_ del problema de Markowitz
Args:
mu (cupy array, vector): valores medios esperados de activos (dimension n)
Sigma (cupy array, matriz): matriz de covarianzas asociada a activos (dimension n x n)
Return:
w_0 (cupy array, matriz): matriz dada por
w_0 = \frac{1}{\Delta} (B \Sigma^{-1} \hat{\mu}- C\Sigma^{-1} 1)
w_1 (cupy array, vector): vector dado por
w_1 = \frac{1}{\Delta} (C \Sigma^{-1} \hat{\mu}- A\Sigma^{-1} 1)
'''
# Obtenemos u = Sigma^{-1} \hat{\mu}, v = \Sigma^{-1} 1
u, v = formar_vectores(mu, Sigma)
# Escalares relevantes
A, B, C = formar_abc(mu, Sigma)
Delta = delta(A,B,C)
# Formamos w_0 y w_1
w_0 = (1/Delta)*(r*B-C)
w_1 = (1/Delta)*(A-C*r)
return w_0, w_1
def markowitz(r, mu, Sigma):
'''
Calcula las cantidades w_o y w_ del problema de Markowitz
Args:
mu (cupy array, vector): valores medios esperados de activos (dimension n)
Sigma (cupy array, matriz): matriz de covarianzas asociada a activos (dimension n x n)
Return:
w_0 (cupy array, matriz): matriz dada por
w_0 = \frac{1}{\Delta} (B \Sigma^{-1} \hat{\mu}- C\Sigma^{-1} 1)
w_1 (cupy array, vector): vector dado por
w_1 = \frac{1}{\Delta} (C \Sigma^{-1} \hat{\mu}- A\Sigma^{-1} 1)
'''
# Obtenemos u = Sigma^{-1} \hat{\mu}, v = \Sigma^{-1} 1
u, v = formar_vectores(mu, Sigma)
# Formamos w_0 y w_1
w_0, w_1 = formar_omegas(r, mu, Sigma)
return w_0*u+w_1*v
```
## Revisón
**1. Documentación**
La Documentación expresa de manera clara, consica y breve lo que hace el código. De igual forma se explica de manera clara y concisa los argumentos de entrada y salida. La documentación es completa.
**2. Cumplimiento de objetivos del código**
La función cumple con el objetivo devolviendo una matriz y un vector de pesos w.
**3. Test**
Objetivo: verificar el desempeño del código con diferentes números de activos y rendimientos, y verificar que los pesos sumen 1.
```
datos_1 = cp.random.uniform(1,1000,10**3).reshape(10**2,10)
sigma_1 = calcular_varianza(datos_1)
mu_1 = calcular_rendimiento(datos_1)
r_11 = cp.mean(mu_1)**2
r_12 = max(mu_1)
w_11 = markowitz(r_11,mu_1,sigma_1)
w_12 = markowitz(r_12,mu_1,sigma_1)
```
Verificamos que la suma de las $\sum w's=1$ y el error absoluto
```
sum(w_11)
abs((sum(w_11)-1)/sum(w_11))
sum(w_12)
abs((sum(w_12)-1)/sum(w_12))
```
Verificamos el error absoluto de $w^{t}\mu = r$
```
error_11 = abs(r_11 - w_11@mu_1)/r_11
print(error_11)
error_12 = abs(r_12 - w_12@mu_1)/r_12
print(error_12)
w_11@mu_1
r_11
w_12@mu_1
r_12
```
Ahora probamos con una matriz de $10^4 \times 10^2$
```
datos_2 = cp.random.uniform(1,1000,10**6).reshape(10**4,10**2)
sigma_2 = calcular_varianza(datos_2)
mu_2 = calcular_rendimiento(datos_2)
r_21 = cp.mean(mu_2)**2
r_22 = max(mu_2)
w_21 = markowitz(r_21,mu_2,sigma_2)
w_22 = markowitz(r_22,mu_2,sigma_2)
```
Verificamos que la suma de las $\sum w's=1$ y el error absoluto
```
sum(w_21)
abs((sum(w_21)-1)/sum(w_21))
sum(w_22)
abs((sum(w_22)-1)/sum(w_22))
```
Verificamos el error absoluto de $w^{t}\mu = r$
```
w_21@mu_2
r_21
error_21 = abs(r_21 - w_21@mu_2)/r_21
print(error_21)
error_22 = abs(r_22 - w_22@mu_2)/r_22
print(error_22)
```
Ahora probamos con una matriz de $10^5 \times 10^3$
```
datos_3 = cp.random.uniform(1,1000,10**8).reshape(10**5,10**3)
sigma_3 = calcular_varianza(datos_3)
mu_3 = calcular_rendimiento(datos_3)
r_31 = cp.mean(mu_3)**2
r_32 = max(mu_3)
w_31 = markowitz(r_31,mu_3,sigma_3)
w_32 = markowitz(r_32,mu_3,sigma_3)
```
Verificamos que la suma de las $\sum w's=1$ y el error absoluto
```
sum(w_31)
abs(sum(w_31)-1)/sum(w_31)
sum(w_32)
```
Verificamos el error absoluto de $w^{t}\mu = r$
```
error_31 = abs(r_31 - w_31@mu_3)/r_31
print(error_31)
error_32 = abs(r_32 - w_32@mu_3)/r_32
print(error_32)
```
Ahora probamos con una matriz de $10^4 \times 10^4$
```
datos_4 = cp.random.uniform(100,1000,10**8).reshape(10**4,10**4)
sigma_4 = calcular_varianza(datos)
mu_4 = calcular_rendimiento(datos)
r_41 = cp.mean(mu_4)**2
r_42 = max(mu_4)
w_41 = markowitz(r_41,mu_4,sigma_4)
w_42 = markowitz(r_42,mu_4,sigma_4)
```
Verificamos que ∑w′s=1 y el error absoluto
```
sum(w_41)
abs(sum(w_41)-1)/sum(w_41)
sum(w_42)
abs(sum(w_42)-1)/sum(w_42)
```
Verificamos el error absoluto de $w^{t}\mu = r$
```
error_41 = abs(r_41 - w_41@mu_4)/r_41
print(error_41)
error_42 = abs(r_42 - w_42@mu_4)/r_42
print(error_42)
r_41
w_41@mu_4
r_42
w_42@mu_4
```
Ahora probamos con una matriz de $10^5 \times 10^4$
```
datos_5 = cp.random.uniform(1,1000,10**9).reshape(10**5,10**4)
sigma_5 = calcular_varianza(datos_5)
mu_5 = calcular_rendimiento(datos_5)
r_51 = cp.mean(mu_5)**2
r_52 = max(mu_5)
```
EL sistema no soporta generar matrices con 10**9 elementos.
Probamos con las acciones
```
sigma = calcular_varianza(datos)
mu = calcular_rendimiento(datos)
r1 = cp.mean(mu)**2
r2 = max(mu)
w_01 = markowitz(r1,mu,sigma)
w_02 = markowitz(r2,mu,sigma)
```
Verificamos que ∑w′s=1 y el error absoluto
```
sum(w_01)
abs(sum(w_01)-1)/sum(w_01)
sum(w_02)
abs(sum(w_02)-1)/sum(w_02)
```
Verificamos el error absoluto de $w^{t}\mu = r$
```
error_01 = abs(r1 - w_01@mu)/r1
print(error_01)
error_02 = abs(r2 - w_02@mu)/r2
print(error_02)
```
# Hallazgos
El código funciona de manera correcta para distintos tamaños de matrices y para el protafolio de acciones.
Las funciones generan unos valores con una exactitud de hasta 16 dígitos correctos.
**Nota**: Los tests fueron realizados en google colaboratory con GPU como entorno de ejecución
| github_jupyter |
# The art of using pipelines
Pipelines are a natural way to think about a machine learning system. Indeed with some practice a data scientist can visualise data "flowing" through a series of steps. The input is typically some raw data which has to be processed in some manner. The goal is to represent the data in such a way that is can be ingested by a machine learning algorithm. Along the way some steps will extract features, while others will normalize the data and remove undesirable elements. Pipelines are simple, and yet they are a powerful way of designing sophisticated machine learning systems.
Both [scikit-learn](https://stackoverflow.com/questions/33091376/python-what-is-exactly-sklearn-pipeline-pipeline) and [pandas](https://tomaugspurger.github.io/method-chaining) make it possible to use pipelines. However it's quite rare to see pipelines being used in practice (at least on Kaggle). Sometimes you get to see people using scikit-learn's `pipeline` module, however the `pipe` method from `pandas` is sadly underappreciated. A big reason why pipelines are not given much love is that it's easier to think of batch learning in terms of a script or a notebook. Indeed many people doing data science seem to prefer a procedural style to a declarative style. Moreover in practice pipelines can be a bit rigid if one wishes to do non-orthodox operations.
Although pipelines may be a bit of an odd fit for batch learning, they make complete sense when they are used for online learning. Indeed the UNIX philosophy has advocated the use of pipelines for data processing for many decades. If you can visualise data as a stream of observations then using pipelines should make a lot of sense to you. We'll attempt to convince you by writing a machine learning algorithm in a procedural way and then converting it to a declarative pipeline in small steps. Hopefully by the end you'll be convinced, or not!
In this notebook we'll manipulate data from the [Kaggle Recruit Restaurants Visitor Forecasting competition](https://www.kaggle.com/c/recruit-restaurant-visitor-forecasting). The data is directly available through `river`'s `datasets` module.
```
from pprint import pprint
from river import datasets
for x, y in datasets.Restaurants():
pprint(x)
pprint(y)
break
```
We'll start by building and running a model using a procedural coding style. The performance of the model doesn't matter, we're simply interested in the design of the model.
```
from river import feature_extraction
from river import linear_model
from river import metrics
from river import preprocessing
from river import stats
means = (
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7)),
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14)),
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(21))
)
scaler = preprocessing.StandardScaler()
lin_reg = linear_model.LinearRegression()
metric = metrics.MAE()
for x, y in datasets.Restaurants():
# Derive date features
x['weekday'] = x['date'].weekday()
x['is_weekend'] = x['date'].weekday() in (5, 6)
# Process the rolling means of the target
for mean in means:
x = {**x, **mean.transform_one(x)}
mean.learn_one(x, y)
# Remove the key/value pairs that aren't features
for key in ['store_id', 'date', 'genre_name', 'area_name', 'latitude', 'longitude']:
x.pop(key)
# Rescale the data
x = scaler.learn_one(x).transform_one(x)
# Fit the linear regression
y_pred = lin_reg.predict_one(x)
lin_reg.learn_one(x, y)
# Update the metric using the out-of-fold prediction
metric.update(y, y_pred)
print(metric)
```
We're not using many features. We can print the last `x` to get an idea of the features (don't forget they've been scaled!)
```
pprint(x)
```
The above chunk of code is quite explicit but it's a bit verbose. The whole point of libraries such as `river` is to make life easier for users. Moreover there's too much space for users to mess up the order in which things are done, which increases the chance of there being target leakage. We'll now rewrite our model in a declarative fashion using a pipeline *à la sklearn*.
```
from river import compose
def get_date_features(x):
weekday = x['date'].weekday()
return {'weekday': weekday, 'is_weekend': weekday in (5, 6)}
model = compose.Pipeline(
('features', compose.TransformerUnion(
('date_features', compose.FuncTransformer(get_date_features)),
('last_7_mean', feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7))),
('last_14_mean', feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14))),
('last_21_mean', feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(21)))
)),
('drop_non_features', compose.Discard('store_id', 'date', 'genre_name', 'area_name', 'latitude', 'longitude')),
('scale', preprocessing.StandardScaler()),
('lin_reg', linear_model.LinearRegression())
)
metric = metrics.MAE()
for x, y in datasets.Restaurants():
# Make a prediction without using the target
y_pred = model.predict_one(x)
# Update the model using the target
model.learn_one(x, y)
# Update the metric using the out-of-fold prediction
metric.update(y, y_pred)
print(metric)
```
We use a `Pipeline` to arrange each step in a sequential order. A `TransformerUnion` is used to merge multiple feature extractors into a single transformer. The `for` loop is now much shorter and is thus easier to grok: we get the out-of-fold prediction, we fit the model, and finally we update the metric. This way of evaluating a model is typical of online learning, and so we put it wrapped it inside a function called `progressive_val_score` part of the `evaluate` module. We can use it to replace the `for` loop.
```
from river import evaluate
model = compose.Pipeline(
('features', compose.TransformerUnion(
('date_features', compose.FuncTransformer(get_date_features)),
('last_7_mean', feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7))),
('last_14_mean', feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14))),
('last_21_mean', feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(21)))
)),
('drop_non_features', compose.Discard('store_id', 'date', 'genre_name', 'area_name', 'latitude', 'longitude')),
('scale', preprocessing.StandardScaler()),
('lin_reg', linear_model.LinearRegression())
)
evaluate.progressive_val_score(dataset=datasets.Restaurants(), model=model, metric=metrics.MAE())
```
Notice that you couldn't have used the `progressive_val_score` method if you wrote the model in a procedural manner.
Our code is getting shorter, but it's still a bit difficult on the eyes. Indeed there is a lot of boilerplate code associated with pipelines that can get tedious to write. However `river` has some special tricks up it's sleeve to save you from a lot of pain.
The first trick is that the name of each step in the pipeline can be omitted. If no name is given for a step then `river` automatically infers one.
```
model = compose.Pipeline(
compose.TransformerUnion(
compose.FuncTransformer(get_date_features),
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7)),
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14)),
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(21))
),
compose.Discard('store_id', 'date', 'genre_name', 'area_name', 'latitude', 'longitude'),
preprocessing.StandardScaler(),
linear_model.LinearRegression()
)
evaluate.progressive_val_score(datasets.Restaurants(), model, metrics.MAE())
```
Under the hood a `Pipeline` inherits from `collections.OrderedDict`. Indeed this makes sense because if you think about it a `Pipeline` is simply a sequence of steps where each step has a name. The reason we mention this is because it means you can manipulate a `Pipeline` the same way you would manipulate an ordinary `dict`. For instance we can print the name of each step by using the `keys` method.
```
for name in model.steps:
print(name)
```
The first step is a `FeatureUnion` and it's string representation contains the string representation of each of it's elements. Not having to write names saves up some time and space and is certainly less tedious.
The next trick is that we can use mathematical operators to compose our pipeline. For example we can use the `+` operator to merge `Transformer`s into a `TransformerUnion`.
```
model = compose.Pipeline(
compose.FuncTransformer(get_date_features) + \
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7)) + \
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14)) + \
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(21)),
compose.Discard('store_id', 'date', 'genre_name', 'area_name', 'latitude', 'longitude'),
preprocessing.StandardScaler(),
linear_model.LinearRegression()
)
evaluate.progressive_val_score(datasets.Restaurants(), model, metrics.MAE())
```
Likewhise we can use the `|` operator to assemble steps into a `Pipeline`.
```
model = (
compose.FuncTransformer(get_date_features) +
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7)) +
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14)) +
feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(21))
)
to_discard = ['store_id', 'date', 'genre_name', 'area_name', 'latitude', 'longitude']
model = model | compose.Discard(*to_discard) | preprocessing.StandardScaler()
model |= linear_model.LinearRegression()
evaluate.progressive_val_score(datasets.Restaurants(), model, metrics.MAE())
```
Hopefully you'll agree that this is a powerful way to express machine learning pipelines. For some people this should be quite remeniscent of the UNIX pipe operator. One final trick we want to mention is that functions are automatically wrapped with a `FuncTransformer`, which can be quite handy.
```
model = get_date_features
for n in [7, 14, 21]:
model += feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(n))
model |= compose.Discard(*to_discard)
model |= preprocessing.StandardScaler()
model |= linear_model.LinearRegression()
evaluate.progressive_val_score(datasets.Restaurants(), model, metrics.MAE())
```
Naturally some may prefer the procedural style we first used because they find it easier to work with. It all depends on your style and you should use what you feel comfortable with. However we encourage you to use operators because we believe that this will increase the readability of your code, which is very important. To each their own!
Before finishing we can take an interactive look at our pipeline.
```
model
```
| github_jupyter |
```
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Q3 API
from layers import dense
dataset = np.load('a1_dataset.npz')
dataset.files
# 80-10-10 split for train, validate and test images
train_till = int(.8 * dataset['x'].shape[0])
validate_till = int(.9 * dataset['x'].shape[0])
print(train_till, validate_till-train_till, dataset['x'].shape[0]-validate_till)
# training dataset
x_train = dataset['x'][:train_till]/255
y_train = np.eye(96)[dataset['y'][:train_till]]
# validation dataset
x_val = dataset['x'][train_till:validate_till]/255
y_val = np.eye(96)[dataset['y'][train_till:validate_till]]
# testing dataset
x_test = dataset['x'][validate_till:]/255
y_test = np.eye(96)[dataset['y'][validate_till:]]
n_classes = 96
n_features = 2352
batch_size = 50
epochs = 50
learning_rate = 0.1
# input
x_p = tf.placeholder(tf.float32, [None, n_features])
# output
y_p = tf.placeholder(tf.float32, [None, n_classes])
# define architecture
n_l1 = 256
n_l2 = 128
# set up layers
hidden1 = dense(x=x_p, in_length=n_features, neurons=n_l1, activation=tf.nn.relu, layer_name='Layer_1')
hidden2 = dense(x=hidden1, in_length=n_l1, neurons=n_l2, activation=tf.nn.relu, layer_name='Layer_2')
output = dense(x=hidden1, in_length=n_l1, neurons=n_classes, activation=tf.nn.softmax, layer_name='Layer_Output')
y_clipped = tf.clip_by_value(output, 1e-10, 0.9999999)
cross_entropy = -tf.reduce_mean(tf.reduce_sum(y_p * tf.log(y_clipped)+ (1 - y_p) * tf.log(1 - y_clipped), axis=1))
optimiser = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)
prediction_vector = tf.argmax(y_p, 1)
output_vector = tf.argmax(output, 1)
acc, acc_op = tf.metrics.accuracy(prediction_vector, output_vector)
conmat = tf.confusion_matrix(prediction_vector, output_vector)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
avg_loss = []
validate_accuracy = []
total_batches = x_train.shape[0] // batch_size
# Training
for e in range(epochs):
avg_loss.append(0.0)
for b in range(total_batches):
start = b*batch_size
end = (b+1)*batch_size
batch = sess.run([optimiser, cross_entropy],
feed_dict={x_p: x_train[start:end], y_p: y_train[start:end]})
avg_loss[e] += batch[1] / total_batches
# validation
accuracy = sess.run(acc_op,
feed_dict={x_p: x_val, y_p: y_val})
validate_accuracy.append(accuracy)
print("Epoch:","{:2d}".format(e+1), "train_loss =", "{:.4f}".format(avg_loss[e]), "validate_accuracy =", "{:.4f}".format(validate_accuracy[e]))
# Testing
test_accuracy, confusion_mat = sess.run([acc_op, conmat],
feed_dict={x_p:x_test, y_p:y_test})
print('Testing Accuracy:', test_accuracy)
print('Confusion Matrix:', confusion_mat)
tf.io.write_graph(sess.graph_def, 'graphs/', 'line-v3.pbtxt')
plt.xlabel('Epoch')
plt.ylabel('Cross Entropy Loss')
plt.plot(avg_loss[None:])
plt.show()
plt.xlabel('Epoch')
plt.ylabel('Validation Accuracy')
plt.plot(validate_accuracy)
plt.show()
True_positives = np.diag(confusion_mat)
False_positives = np.sum(confusion_mat, axis=1) - True_positives
False_negatives = np.sum(confusion_mat, axis=0) - True_positives
Precision = True_positives / (True_positives + False_positives)
print("Precision:", Precision)
Recall = True_positives / (True_positives + False_negatives)
print("\nRecall:", Recall)
F_scores = (2*Precision*Recall) / (Recall+Precision)
print("\nF_scores:", F_scores)
plt.plot(Precision, label='Precision')
plt.plot(Recall, label='Recall')
plt.plot(F_scores, label='F Scores')
plt.ylabel('Score')
plt.xlabel('Class')
plt.legend()
plt.show()
np.savez_compressed('linev3-conmat.npz', cmat=confusion_mat)
```
| github_jupyter |
# Explore the classification results
This notebook will guide you through different visualizations of the test set evaluation of any of the presented models.
In a first step you can select the result file of any of the models you want to explore.
```
model = 'vgg_results_sample.csv' #should be placed in the /eval/ folder
```
Then we will import some packages and setup some basic variables
```
import os
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from skimage.io import imread
from sklearn.metrics import accuracy_score, confusion_matrix
from utils import plot_confusion_matrix, class_names, plots
%matplotlib inline
# get the path of the data and eval folder
root_dir = os.path.abspath(os.path.join(sys.path[0], os.pardir))
eval_dir = os.path.join(root_dir, 'eval')
data_dir = os.path.join(root_dir, 'data')
```
**Next** we will load the evaluation results and compute different **accuracy** values.
1. The per-image accuracy. Should not be be confused with the per-fish accuracy. The per-image accuracy means how many of the samples (image + corresponding features) in the test set were predicted with the correct class.
2. The per-fish accuracy if the results of the different images of one fish are combine by the `mode` of the single image predictions
3. The per-fish accuracy if the final prediction is derived from the class with the highest overall probability if we sum up all class probabilities of the single images.
To get the different per-fish accuracies we can group the data by `video_name` and `label` because each combination of `video_name` and `label` stays for one individual fish.
The columns `prediction_max_prob` and `prediction_mode` contain the predicted class label for each individual fish derived through the above stated methods.
```
#load the evaluation data
df = pd.read_csv(os.path.join(eval_dir, model), sep=';')
#compute the per-image accuracy
acc_per_img = accuracy_score(df['label'], df['pred'])
# get the per-fish results by grouping the dataframe and taking first entry of each group as the columns for the
# per-fish prediction are the same for all images of one fish
fish = df.groupby(['video_name', 'label']).first().reset_index()
# calculate the per-fish accuracies
acc_fish_mode = accuracy_score(fish['label'], fish['prediction_mode'])
acc_fish_max_prob = accuracy_score(fish['label'], fish['prediction_max_prob'])
# print the results
print("From a total of %i images, %.2f percent of the images were classified correctly." %(len(df), acc_per_img*100))
print("If combined by the mode of %i fish individuals %.2f were classified correctly." %(len(fish), acc_fish_mode*100))
print("If derived from the max probability of the summed class probabilities, out of %i fish %.2f were classified correctly." %(len(fish), acc_fish_max_prob*100))
```
As we are interested in the per-fish accuracy, we can see that combining the classification results of many images of one fish can help to raise the overall prediction accuracy. From the two different methods, this can be best done through the `prediction_max_prob` method.
**Next** we will display the **confusion matrix**. The confusion matrix displays the true class vs. the predicted class. This might help to understand which classes the model can seperate and between which it makes the most mispredictions.
By changing the first line, you can select which confusion matrix should be displayed. You can chose between ['pre-img', 'mode', 'max_prob'] referring to the 3 different accuracies from above.
```
method = 'max_prob' # chose one of ['per-img', 'mode', 'max_prob']
#compute confusion matrix
if method == 'per-img':
cm = confusion_matrix(df['label'], df['pred'])
elif method == 'mode':
cm = confusion_matrix(fish['label'], fish['prediction_mode'])
elif method == 'max_prob':
cm = confusion_matrix(fish['label'], fish['prediction_max_prob'])
else:
raise ValueError("Select a valid method. Must be one of ['per-img', 'mode', 'max_prob']")
#plot confusion matrix
plot_confusion_matrix(cm, [n.split(',')[1] for n in class_names])
```
You will see for all of the combinations you can selected (4 models and 3 different methods) that the models make the most number of misclassifications between similar (at least somehow) looking fish species. For example you can see that most misclassifications of brown trouts were made with rainbow trouts (and vice versa) and the same for chub and common nase. Through this we can conclude that the models understand the content of the images/features they are confronted with.
**Next** we will look at some random images of each class the model was absolutely sure about it's prediction and the predicted class was indeed the true class.
```
#number of total classes and images per class we will plot
num_classes = 7
n_view = 4
#iterate over each class and find the images the model assigned the highest class probability to (to the true class)
for i in range(num_classes):
corrects = np.where((df['label'] == i) & (df['pred'] == i))
df_corrects = df.loc[corrects]
df_corrects.sort_values('score'+str(i), inplace = True, ascending = False)
#print number of correct images per class
print("Found %i correct %s" %(len(df_corrects), class_names[i]))
#plot images
plots(df_corrects, df_corrects.index[:n_view], data_dir)
```
To some degree, these images should make sense. Most of them show specific characteristics of each species that are enought to classify them correctly. Some might not make much sense for us as a human observer but might make sense to the model.
E.g. We had plenty of rainbow trouts in turbid water, so that the model seems to have learned that a salmonide looking fish in turbid water is more likely to be a rainbow than a brown trout.
Up **Next** we could visualize the opposite: We could look at the images of each class, for which the model was most uncertain about.
```
for i in range(num_classes):
fish = df.loc[df['label'] == i]
fish.is_copy = False
fish.sort_values('score'+str(i), inplace = True, ascending = True)
plots(fish, fish.index[:n_view], data_dir)
```
These results may let you wonder, why for some of these images the model predicted the wrong class, although the fish could be clearly seen. To be honest, I don't know the answer and could only guess for some of the cases. I think one key point could be the size of the dataset and one could expect that a bigger sample size per class could yield better results.
One the other hand, one could also see many images of bad quality, turbid water etc. where even for us humans it might be hard to classify the fish by this one single images.
Also note, that this are per-image prediction results. A lot of these single image misclassifications aren't influencing the per-fish predictions.
| github_jupyter |
#### Setup
```
# standard imports
import numpy as np
import torch
import matplotlib.pyplot as plt
from torch import optim
from ipdb import set_trace
from datetime import datetime
# jupyter setup
%matplotlib inline
%load_ext autoreload
%autoreload 2
# own modules
from dataloader import CAL_Dataset
from net import get_model
from dataloader import get_data, get_mini_data, load_json, save_json
from train import fit, custom_loss, validate
from metrics import calc_metrics
# paths
data_path = './dataset/'
```
uncomment the cell below if you want your experiments to yield always the same results
```
# manualSeed = 42
# np.random.seed(manualSeed)
# torch.manual_seed(manualSeed)
# # if you are using GPU
# torch.cuda.manual_seed(manualSeed)
# torch.cuda.manual_seed_all(manualSeed)
# torch.backends.cudnn.enabled = False
# torch.backends.cudnn.benchmark = False
# torch.backends.cudnn.deterministic = True
```
#### Training
Initialize the model. Possible Values for the task block type: MLP, LSTM, GRU, TempConv
```
params = {'name': 'tempconv', 'type_': 'TempConv', 'lr': 3e-4, 'n_h': 128, 'p':0.5, 'seq_len':5}
save_json(params, f"models/{params['name']}")
model, opt = get_model(params)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
```
get the data loader. get mini data gets only a subset of the training data, on which we can try if the model is able to overfit
```
train_dl, valid_dl = get_data(data_path, model.params.seq_len, batch_size=16)
# train_dl, valid_dl = get_mini_data(data_path, model.params.seq_len, batch_size=16, l=4000)
```
Train the model. We automatically save the model with the lowest val_loss. If you want to continue the training and keep the loss history, just pass it as an additional argument as shown below.
```
model, val_hist = fit(1, model, custom_loss, opt, train_dl, valid_dl)
# model, val_hist = fit(1, model, custom_loss, opt, train_dl, valid_dl, val_hist=val_hist)
```
uncomment the following two cells if the feature extractor should also be trained
```
# for name,param in model.named_parameters():
# param.requires_grad = True
# opt = optim.Adam(model.parameters())
# model, val_hist = fit(1, model, custom_loss, opt, train_dl, valid_dl)
plt.plot(val_hist)
```
#### evalute the model
reload model
```
name = 'gru'
params = load_json(f"models/{name}")
model, _ = get_model(params)
model.load_state_dict(torch.load(f"./models/{name}.pth"));
model.eval().to(device);
_, valid_dl = get_data(data_path, model.params.seq_len, batch_size=16)
```
run evaluation on full val set
```
_, all_preds, all_labels = validate(model, valid_dl, custom_loss)
calc_metrics(all_preds, all_labels)
```
#### plot results
```
# for convience, we can pass an integer instead of the full string
int2key = {0: 'red_light', 1:'hazard_stop', 2:'speed_sign',
3:'relative_angle', 4: 'center_distance', 5: 'veh_distance'}
def plot_preds(k, all_preds, all_labels, start=0, delta=1000):
if isinstance(k, int): k = int2key[k]
# get preds and labels
class_labels = ['red_light', 'hazard_stop', 'speed_sign']
pred = np.argmax(all_preds[k], axis=1) if k in class_labels else all_preds[k]
label = all_labels[k][:, 1] if k in class_labels else all_labels[k]
plt.plot(pred[start:start+delta], 'r--', label='Prediction', linewidth=2.0)
plt.plot(label[start:start+delta], 'g', label='Ground Truth', linewidth=2.0)
plt.legend()
plt.grid()
plt.show()
plot_preds(5, all_preds, all_labels, start=0, delta=4000)
```
#### param search
```
from numpy.random import choice
np.random.seed()
params = {'name': 'tempconv', 'type_': 'TempConv', 'lr': 3e-4, 'n_h': 128, 'p':0.5, 'seq_len':5}
def get_random_NN_parameters():
params = {}
params['type_'] = choice(['MLP', 'GRU', 'LSTM', 'TempConv'])
params['name'] = datetime.now().strftime("%Y_%m_%d_%H_%M")
params['lr'] = np.random.uniform(1e-5, 1e-2)
params['n_h'] = np.random.randint(5, 200)
params['p'] = np.random.uniform(0.25, 0.75)
params['seq_len'] = np.random.randint(1, 15)
return params
while True:
params = get_random_NN_parameters()
print('PARAMS: {}'.format(params))
# instantiate the model
model, opt = get_model(params)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
save_json(params, f"models/{params['name']}")
# get the data loaders
train_dl, valid_dl = get_data(data_path, model.params.seq_len, batch_size=16)
# start the training
model, val_hist = fit(5, model, custom_loss, opt, train_dl, valid_dl)
for name,param in model.named_parameters():
param.requires_grad = True
opt = optim.Adam(model.parameters())
model, val_hist = fit(5, model, custom_loss, opt, train_dl, valid_dl, val_hist=val_hist)
```
| github_jupyter |
```
import pickle
import warnings
warnings.filterwarnings('ignore')
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
import pandas as pd
from pandas.plotting import scatter_matrix
import numpy as np
import matplotlib.pyplot as pl
from matplotlib import rcParams
from seaborn import PairGrid, heatmap, kdeplot
import cmocean.cm as cmo
% matplotlib inline
rcParams['axes.titlesize'] = 18
rcParams['xtick.labelsize'] = 16
rcParams['ytick.labelsize'] = 16
rcParams['axes.labelsize'] = 16
rcParams['font.size'] = 16
df_pc = pd.read_pickle('./pickleJar/DevelopmentalDataSets/df_5_APHY_pc.pkl')
df_sat = pd.read_pickle('./pickleJar/DevelopmentalDataSets/df_5_APHY_sat')
df_pc.info()
df_sat.info()
df_pc = df_pc.loc[((df_pc.aphy411>0) & (df_pc.aphy443>0) & (df_pc.aphy489)
& (df_pc.aphy510>0) & (df_pc.aphy555>0) & (df_pc.aphy670))
]
df_sat = df_sat.loc[((df_sat.aphy411>0) & (df_sat.aphy443>0) & (df_sat.aphy489)
& (df_sat.aphy510>0) & (df_sat.aphy555>0) & (df_sat.aphy670))
]
df_sat = df_sat.loc[((df_sat.sat_rho_rc412>0) & (df_sat.sat_rho_rc443>0) &
(df_sat.sat_rho_rc490>0) & (df_sat.sat_rho_rc510>0) &
(df_sat.sat_rho_rc555>0) & (df_sat.sat_rho_rc670>0))
]
df_pc.loc[172:175].T
df_sat.loc[172:175].T
df_pc.dropna(inplace=True)
df_sat.dropna(inplace=True)
df_pc.info()
sat_cols = df_sat.columns.tolist()
sat_cols_new = [col for col in sat_cols if not col.startswith('aphy')] +\
[col for col in sat_cols if col.startswith('aphy')]
df_sat = df_sat[sat_cols_new]
df_sat.info()
df_pc.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_PC.pkl')
df_sat.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_SAT.pkl')
sc_pc = StandardScaler()
sc_sat = StandardScaler()
X_s_pc = sc_pc.fit_transform(df_pc.loc[:, :'PC6'].values)
X_s_sat = sc_sat.fit_transform(df_sat.loc[:, :'z'].values)
X_s_pc.shape, X_s_sat.shape
feat_cols_pc = df_pc.loc[:,:'PC6'].columns.tolist()
feat_cols_sat = df_sat.loc[:, :'z'].columns.tolist()
df_pc_s = pd.DataFrame(X_s_pc, columns=['%s_s' % col for col in feat_cols_pc],
index=df_pc.index)
df_sat_s = pd.DataFrame(X_s_sat, columns=['%s_s' % col for col in feat_cols_sat],
index=df_sat.index)
df_pc_s.head()
df_pc_s.shape, df_sat_s.shape
df_pc_s = pd.concat((df_pc_s, df_pc.filter(regex='aphy', axis=1)), axis=1)
df_pc_s.info()
df_sat_s = pd.concat((df_sat_s, df_sat.filter(regex='aphy', axis=1)), axis=1)
pf_pc = PolynomialFeatures(interaction_only=True, include_bias=False)
pf_sat = PolynomialFeatures(interaction_only=True, include_bias=False)
Xsp_pc = pf_pc.fit_transform(X_s_pc)
Xsp_sat = pf_sat.fit_transform(X_s_sat)
y_aphy = df_pc.filter(regex='aphy', axis=1)
y_aphy.shape
poly_feat_nams_pc = pf_pc.get_feature_names(input_features=df_pc_s.loc[:,:'PC6_s'].columns)
poly_df_cols_pc = poly_feat_nams_pc + y_aphy.columns.tolist()
poly_feat_nams_sat = pf_pc.get_feature_names(input_features=df_sat_s.loc[:,:'z_s'].columns)
poly_df_cols_sat = poly_feat_nams_sat + y_aphy.columns.tolist()
df_sp_pc = pd.DataFrame(np.c_[Xsp_pc, y_aphy], columns=poly_df_cols_pc,
index=df_pc_s.index)
df_sp_sat = pd.DataFrame(np.c_[Xsp_sat, y_aphy], columns=poly_df_cols_sat,
index=df_sat_s.index)
df_sp_pc.shape, df_sp_sat.shape
df_pc_s.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_Standardized_PC.pkl')
df_sp_pc.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_Standardized_PolyFeatures_PC.pkl')
df_sat_s.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_Standardized_SAT.pkl')
df_sp_sat.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_Standardized_PolyFeatures_SAT.pkl')
aphys = ['aphy411', 'aphy443', 'aphy489', 'aphy510', 'aphy555', 'aphy670']
df_s_SWF_pc = pd.concat((df_pc_s.loc[:, :'PC6_s'], df_pc_s[aphys]), axis=1)
df_s_SWF_sat = pd.concat((df_sat_s.loc[:, :'z_s'], df_sat_s[aphys]), axis=1)
df_sp_sat.head().T
df_sp_SWF_pc = pd.concat((df_sp_pc.loc[:, :'PC5_s PC6_s'], df_sp_pc[aphys]), axis=1)
df_sp_SWF_sat = pd.concat((df_sp_sat.loc[:, :'y_s z_s'], df_sp_sat[aphys]), axis=1)
df_s_SWF_pc.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_Standardized_SWF_PC.pkl')
df_s_SWF_sat.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_Standardized_SWF_SAT.pkl')
df_sp_SWF_pc.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_Standardized_PolyFeatures_SWF_PC.pkl')
df_sp_SWF_sat.to_pickle('./pickleJar/OperationalDataSets/df_6_APHY_Standardized_PolyFeatures_SWF_SAT.pkl')
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
sp500 = pd.read_csv("https://raw.githubusercontent.com/labs13-quake-viewer/ds-data/master/S%26P%20500.csv")
sp500.shape
sp500.describe()
(sp500 == 0).sum()
sp500.info()
sp500.head(12)
dates=[]
for i in sp500['Date']:
dd = datetime.datetime.strptime(i,'%m/%d/%y')
if dd.year > 2019:
dd = dd.replace(year=dd.year-100)
dates.append(dd.strftime( '%Y-%m-%d' ))
sp500['Date'] = dates
sp500.plot(x="Date", y="Close", figsize=(20, 10));
df_sp500 = sp500.set_index('Date')
df_sp500.info()
df_sp500.head(12)
quakes = pd.read_csv("https://raw.githubusercontent.com/labs13-quake-viewer/ds-data/master/Earthquakes%205.5%201900-present.csv")
quakes.shape
quakes.describe()
quakes.info()
quakes.sample(12)
pd.options.mode.chained_assignment = None # default='warn'
df_quakes = quakes[['time', 'mag', 'latitude', 'longitude']]
df_quakes.time = df_quakes.time.str[:10]
df_quakes = df_quakes.sort_values(by=['time'])
df_quakes.info()
df = df_quakes[df_quakes['time'] >= "1950-01-03"]
df_quakes = df[df['mag'] >= 6.7]
df_quakes = df_quakes.reset_index(drop=True)
df_quakes.info()
df_quakes.head(12)
df_quakes.plot(x="time", y="mag", figsize=(20, 10));
def get_next_trading_day(date_in):
t1 = date_in
dayz = 1
while t1 not in df_sp500.index:
t1 = pd.to_datetime(date_in).date() + datetime.timedelta(days=dayz)
t1 = t1.strftime('%Y-%m-%d')
dayz += 1
return t1
import datetime
i = -1
data = []
for _, row in df_quakes.iterrows():
i += 1
if row.time > "2019-04-15":
continue
t0 = get_next_trading_day(row.time)
t1 = pd.to_datetime(row.time).date() + datetime.timedelta(days=7)
t1 = t1.strftime('%Y-%m-%d')
t1 = get_next_trading_day(t1)
t2 = pd.to_datetime(row.time).date() + datetime.timedelta(days=14)
t2 = t2.strftime('%Y-%m-%d')
t2 = get_next_trading_day(t2)
t3 = pd.to_datetime(row.time).date() + datetime.timedelta(days=30)
t3 = t3.strftime('%Y-%m-%d')
t3 = get_next_trading_day(t3)
x = (row.time, row.mag, df_sp500.loc[t0].Close, df_sp500.loc[t1].Close,
df_sp500.loc[t2].Close, df_sp500.loc[t3].Close)
data.append(x)
df_quake_sp500 = pd.DataFrame(data=data, columns=['Date', 'Mag', 'Price_Day_0', 'Price_Day_7', 'Price_Day_14', 'Price_Day_30'])
df_quake_sp500["Appr_Day_7"] = 100 * (df_quake_sp500["Price_Day_7"] - df_quake_sp500["Price_Day_0"]) / df_quake_sp500["Price_Day_0"]
df_quake_sp500["Appr_Day_14"] = 100 * (df_quake_sp500["Price_Day_14"] - df_quake_sp500["Price_Day_0"]) / df_quake_sp500["Price_Day_0"]
df_quake_sp500["Appr_Day_30"] = 100 * (df_quake_sp500["Price_Day_30"] - df_quake_sp500["Price_Day_0"]) / df_quake_sp500["Price_Day_0"]
df_quake_sp500.describe()
df = df_quake_sp500.groupby(['Mag'])['Appr_Day_30'].mean()
df.plot.bar(figsize=(20, 10));
df_quake_sp500.Mag.value_counts().sort_index()
df_quakes_usa = df_quakes.query('32.5 <= latitude < 48.75').query('-123 <= longitude < -69')
df_quakes_usa.info()
df_quakes_usa
i = -1
data = []
for _, row in df_quakes_usa.iterrows():
i += 1
if row.time > "2019-04-15":
continue
t0 = get_next_trading_day(row.time)
t1 = pd.to_datetime(row.time).date() + datetime.timedelta(days=7)
t1 = t1.strftime('%Y-%m-%d')
t1 = get_next_trading_day(t1)
t2 = pd.to_datetime(row.time).date() + datetime.timedelta(days=14)
t2 = t2.strftime('%Y-%m-%d')
t2 = get_next_trading_day(t2)
t3 = pd.to_datetime(row.time).date() + datetime.timedelta(days=30)
t3 = t3.strftime('%Y-%m-%d')
t3 = get_next_trading_day(t3)
x = (row.time, row.mag, df_sp500.loc[t0].Close, df_sp500.loc[t1].Close,
df_sp500.loc[t2].Close, df_sp500.loc[t3].Close)
data.append(x)
df_quake_sp500_usa = pd.DataFrame(data=data, columns=['Date', 'Mag', 'Price_Day_0', 'Price_Day_7', 'Price_Day_14', 'Price_Day_30'])
df_quake_sp500_usa["Appr_Day_7"] = 100 * (df_quake_sp500_usa["Price_Day_7"] - df_quake_sp500_usa["Price_Day_0"]) / df_quake_sp500_usa["Price_Day_0"]
df_quake_sp500_usa["Appr_Day_14"] = 100 * (df_quake_sp500_usa["Price_Day_14"] - df_quake_sp500_usa["Price_Day_0"]) / df_quake_sp500_usa["Price_Day_0"]
df_quake_sp500_usa["Appr_Day_30"] = 100 * (df_quake_sp500_usa["Price_Day_30"] - df_quake_sp500_usa["Price_Day_0"]) / df_quake_sp500_usa["Price_Day_0"]
df = df_quake_sp500_usa.groupby(['Mag'])['Appr_Day_30'].mean()
df.plot.bar(figsize=(20, 10));
```
| github_jupyter |
# Getting Started with TensorFlow Hub
[TensorFlow Hub](https://tfhub.dev/) is a repository of reusable TensorFlow machine learning modules. A module is a self-contained piece of a TensorFlow graph, along with its weights and assets, that can be reused across different tasks. These modules can be reused to solve new tasks with less training data, diminishing training time.
In this notebook we will go over some basic examples to help you get started with TensorFlow Hub. In particular, we will cover the following topics:
* Loading TensorFlow Hub Modules and Performing Inference.
* Using TensorFlow Hub Modules with Keras.
* Using Feature Vectors with Keras for Transfer Learning.
* Saving and Running a TensorFlow Hub Module Locally.
* Changing the Download Location of TensorFlow Hub Modules.
## Setup
```
try:
%tensorflow_version 2.x
except:
pass
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_hub as hub
from PIL import Image
print("\u2022 Using TensorFlow Version:", tf.__version__)
```
## Download Test Image
We will download the image of a puppy to test our TensorFlow Hub modules.
```
!wget -O dog.jpeg https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_960_720.jpg
original_image = Image.open('./dog.jpeg')
```
Let's take a look at the image we just downloaded.
```
plt.figure(figsize=(6,6))
plt.imshow(original_image)
plt.show()
```
## Format Image
We will now resize and normalize our image so that is compatible with the module we are going to use. In this notebook we will use the [MobileNet](https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4) model which was trained in ImageNet. For this module, the input images are expected to have color values in the range `[0,1]` and to have an input size of `(224,224)`.
```
IMAGE_SIZE = (224, 224)
img = original_image.resize(IMAGE_SIZE)
img = np.array(img) / 255.0
```
Let's now plot the reformatted image, to see what it looks like.
```
plt.figure(figsize=(5,5))
plt.imshow(img)
plt.title('New Image Size: {}'.format(img.shape), fontdict={'size': 16}, color='green')
plt.show()
```
## Get ImageNet Labels
We will now get the labels for all the 1001 classes in the ImageNet dataset.
```
!wget -O labels.txt --quiet https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt
with open('labels.txt', 'r') as f:
labels = [l.strip() for l in f.readlines()]
# get number of labels
num_classes = len(labels)
print('There are a total of {0} labels representing {0} classes.\n'.format(num_classes))
```
Let's take a look at the first 5 labels.
```
for label in labels[0:5]:
print(label)
```
## Loading a TensorFlow Hub Module
To load a module, we use its unique **module handle**, which is just a URL string. To obtain the module handle, we have to browse through the catalog of modules in the [TensorFlow Hub](https://tfhub.dev/) website.
For example, in this case, we will be using the complete **MobileNet** model. If we go to [MobileNet's webpage](https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4) in the TensorFlow Hub website, we will see that the module handle for this module is:
```
'https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4'
```
Finally, we'll make use of TensorFlow Hub's, `load` API to load the module into memory.
```
MODULE_HANDLE = 'https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4'
module = hub.load(MODULE_HANDLE)
```
## Performing Inference
Once we have loaded the module, we can then start running inference on it. Note however, that the module generates the final layer's logits without any activations. Therefore, we have to apply the `softmax` activation to the module's output. The result will be a Tensor of shape `(1, 1001)`, where the first dimension refers to the batch size. In this case it is just `1` because we only passed 1 image.
In the cell below, we will pass the image of the puppy and get the top 5 predictions from our model along with their probability scores.
```
predictions = tf.nn.softmax(module([img]))[0]
top_k_pred_values, top_k_indices = tf.math.top_k(predictions, k=5)
top_k_pred_values = top_k_pred_values.numpy()
top_k_indices = top_k_indices.numpy()
for value, i in zip(top_k_pred_values, top_k_indices):
print('{}: {:.3}'.format(labels[i], value))
```
## Using a TensorFlow Hub Module with Keras
We can also integrate TensorFlow Hub modules into the high level Keras API. In this case, we make use of the `hub.KerasLayer` API to load it. We can add the `hub.KerasLayer` to a Keras `sequential` model along with an activation layer. Once the model is built, all the Keras model methods can be accessed like you would normally do in Keras.
```
model = tf.keras.Sequential([
hub.KerasLayer(MODULE_HANDLE, input_shape=IMAGE_SIZE + (3,)),
tf.keras.layers.Activation('softmax')
])
```
## Performing Inference
To perform inference with the Keras model, we have to add a dimension to our image to account for the batch size. Remember that our Keras model expects the input to have shape `(batch_size, image_size)`, where the `image_size` includes the number of color channels.
```
# Add batch dimension
img_arr = np.expand_dims(img, axis=0)
```
As we did previously, in the cell below we will pass the image of the puppy and get the top 5 predictions from our Keras model along with their probability scores.
```
predictions = model.predict(img_arr)[0]
top_k_pred_values, top_k_indices = tf.math.top_k(predictions, k=5)
top_k_pred_values = top_k_pred_values.numpy()
top_k_indices = top_k_indices.numpy()
for value, i in zip(top_k_pred_values, top_k_indices):
print('{}: {:.3}'.format(labels[i], value))
```
# Using Feature Vectors with Keras
While we can use complete models as we did in the previous section, perhaps, the most important part of TensorFlow Hub is in how it provides **Feature Vectors** that allows us to take advantage of transfer learning. Feature vectors are just complete modules that had their final classification head removed.
In the cell below we show an example of how a feature vector can be added to a Keras `sequential` model.
```
MODULE_HANDLE ="https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
# Number of classes in the new dataset
NUM_CLASSES = 20
model = tf.keras.Sequential([
hub.KerasLayer(MODULE_HANDLE, input_shape=IMAGE_SIZE + (3,)),
tf.keras.layers.Dense(NUM_CLASSES, activation='softmax')
])
```
Now that the model is built, the next step in transfer learning will be to train the model on a new dataset with the new classifier (i.e. the last layer of the model). Remember that the number of output units in the last layer will correspond to the number of classes in your new dataset. After the model has been trained, we can perform inference in the same way as with any Keras model (see previous section).
# Saving a TensorFlow Hub Module for Local Use
We can download TensorFlow Hub modules, by explicitly downloading the module as a **SavedModel** archived as a tarball. This is useful if we want to work with the module offline.
To do this, we first have to download the Hub module by appending a query parameter to the module handled URL string. This is done by setting the TF Hub format query parameter as shown below. For now, only the compressed option is defined.
```
MODULE_HANDLE = 'https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4?tf-hub-format=compressed'
!wget -O ./saved_model.tar.gz $MODULE_HANDLE
```
Next, we need to decompress the tarball.
```
# Untar the tarball
!mkdir -p ./saved_model
!tar xvzf ./saved_model.tar.gz -C ./saved_model
```
# Running a TensorFlow Hub Module Locally
We can load the SavedModel containing the saved TensorFlow Hub module by using `hub.load`.
```
module = hub.load('./saved_model')
```
After the TensorFlow Hub module is loaded, we can start making inferences as shown below. As before, we will pass the image of the puppy and get the top 5 predictions from our model along with their probability scores.
```
predictions = tf.nn.softmax(module([img]))[0]
top_k_pred_values, top_k_indices = tf.math.top_k(predictions, k=5)
top_k_pred_values = top_k_pred_values.numpy()
top_k_indices = top_k_indices.numpy()
for value, i in zip(top_k_pred_values, top_k_indices):
print('{}: {:.3}'.format(labels[i], value))
```
## Changing the Download Location of TensorFlow Hub Modules.
Finally, we can change the download location of TensorFlow Hub modules to a more permanent location. We can do this by setting the environment variable `'TFHUB_CACHE_DIR'` to the directory we want our modules to be saved in.
In Python, we can set this environment variable in the environment dictionary that's present in the Pythons `os` module as you can see below.
```
hub_cache_dir = './hub_cache_dir'
os.environ['TFHUB_CACHE_DIR'] = hub_cache_dir
```
Once we set the new location of the TF Hub cache directory environment variable, all the subsequent modules that we request will get downloaded to that location.
```
MODULE_HANDLE = 'https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4'
module = hub.load(MODULE_HANDLE)
```
We can take a look the contents of the new directory and all its subdirectories by using the `-R` option.
```
!ls -R {hub_cache_dir}
```
| github_jupyter |
```
%matplotlib widget
import os
import sys
sys.path.insert(0, os.getenv('HOME')+'/pycode/MscThesis/')
import pandas as pd
from amftrack.util import get_dates_datetime, get_dirname, get_plate_number, get_postion_number
import ast
from amftrack.plotutil import plot_t_tp1
from scipy import sparse
from datetime import datetime
from amftrack.pipeline.functions.node_id import orient
import pickle
import scipy.io as sio
from pymatreader import read_mat
from matplotlib import colors
import cv2
import imageio
import matplotlib.pyplot as plt
import numpy as np
from skimage.filters import frangi
from skimage import filters
from random import choice
import scipy.sparse
import os
from amftrack.pipeline.functions.extract_graph import from_sparse_to_graph, generate_nx_graph, sparse_to_doc
from skimage.feature import hessian_matrix_det
from amftrack.pipeline.functions.experiment_class_surf import Experiment
from amftrack.pipeline.paths.directory import run_parallel, find_state, directory_scratch, directory_project, path_code
from amftrack.notebooks.analysis.data_info import *
import matplotlib.patches as mpatches
from statsmodels.stats import weightstats as stests
window=800
results={}
for treatment in treatments.keys():
insts = treatments[treatment]
for inst in insts:
results[inst] = pickle.load(open(f'{path_code}/MscThesis/Results/straight_{window}_{inst}.pick', "rb"))
column_names = ["plate","inst", "treatment", "angle", "curvature","density","growth","speed","straightness","t","hyph"]
infos = pd.DataFrame(columns=column_names)
for treatment in treatments.keys():
insts = treatments[treatment]
for inst in insts:
angles, curvatures, densities,growths,speeds,tortuosities,ts,hyphs = results[inst]
for i,angle in enumerate(angles):
new_line = pd.DataFrame(
{ "plate": [plate_number[inst]],
"inst": [inst],
"treatment": [treatment],
"angle": [angle],
"curvature": [curvatures[i]],
"density": [densities[i]],
"growth": [growths[i]],
"speed": [speeds[i]],
"straightness": [tortuosities[i]],
"t": [ts[i]],
"hyph": [hyphs[i]],
}
) # index 0 for
# mothers need to be modified to resolve multi mother issue
infos = infos.append(new_line, ignore_index=True)
corrected = infos.loc[infos["straightness"] <= 1]
corrected
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(9, 4))
bplot1 = corrected.boxplot(column = ['speed'],by="plate",figsize =(9,8),ax =ax,patch_artist=True, showfliers=False)
colors = ['lightblue']+ ['pink'] +['lightgreen']
for i,(artist, col) in enumerate(zip(ax.artists, colors)):
artist.set_edgecolor(col)
artist.set_facecolor(col)
ax.set_xlabel('Plate')
ax.set_ylabel('Speed')
ax.set_ylim(0.9)
plt.show()
max_speeds = []
total_growth = []
for treatment in treatments.keys():
insts = treatments[treatment]
for inst in insts:
inst_tab = corrected.loc[corrected["inst"]==inst]
for hyph in set(inst_tab['hyph']):
max_speeds.append(np.max(inst_tab.loc[inst_tab['hyph']==hyph]['speed']))
total_growth.append(np.sum(inst_tab.loc[inst_tab['hyph']==hyph]['growth']))
len(max_speeds)
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(9, 4))
ax.scatter(np.log(total_growth),max_speeds)
# ax.set_xlim(100,300)
```
| github_jupyter |
```
import pandas as pd
from glob import glob
from pypcleaner import convert_excel_time
df = pd.read_hdf('big_multi_index.h5')
scans = pd.read_pickle('scans.p')
imaging_id_codes = pd.read_pickle('imaging_id_codes.p')
id_codes = imaging_id_codes.loc[scans.index,'prefix']
scan_id_df = df.loc[scans.index]
scan_id_df.drop('day_0', axis='columns', level=0, inplace = True)
drop_these = ['bp_three_hr','bp_three_hr_systolic','bp_three_hr_diastolic','bp_three_hr_datetime',
'bp_seven_hr','bp_seven_hr_systolic','bp_seven_hr_diastolic','bp_seven_hr_datetime',
'bp_other_hr','bp_other_hr_systolic','bp_other_hr_diastolic','bp_other_hr_datetime',
'hrt_seven_hr','hrt_seven_hr_rate','hrt_seven_hr_datetime','hrt_other_hr',
'hrt_other_hr_rate','hrt_other_hr_datetime','surgical_intervention',
'surgical_intervention_detail','invasive_intervention','invasive_intervention_detail',
'imaging_intervention','imaging_intervention_detail',
'other_intervention','other_intervention_detail','medication_given','medication_comment']
scan_id_df.drop([('day_baseline','recent_medical_history',c) for c in drop_these], axis = 'columns',inplace = True)
scan_id_df[('day_baseline','recent_medical_history','tpa_datetime')] = \
scan_id_df[('day_baseline','recent_medical_history','tpa_datetime')].apply(convert_excel_time).dt.round('5min')
remove_tests = \
[('day_baseline','physical_examination'),
('day_baseline', 'past_medical_history'),
('day_baseline', 'CCMI'),
('day_baseline', 'further_stroke_event_part'),
('day_baseline', 'bloods'),
('day_baseline', 'laboratory_tests'),
('day_baseline', 'radiological_scans'),
('day_baseline', 'concomitant_medications'),
('day_baseline', 'pre-stroke_mRS'),
('day_7', 'bloods') ,
('day_7', 'history_of_depression'),
('day_7', 'physical_risk_factors'),
('day_7', 'diet_q'),
('day_7', 'laboratory_tests'),
('day_7', 'concomitant_medications'),
('day_7', 'concomitant_medications_plus'),
('day_90', 'bloods'),
('day_90', 'physical_examination'),
('day_90', 'physical_risk_factors'),
('day_90', 'diet_q'),
('day_90', 'laboratory_tests'),
('day_90', 'further_stroke_event_part'),
('day_90', 'history_of_depression'),
('day_90', 'concomitant_medications'),
('day_365', 'bloods'),
('day_365', 'physical_examination'),
('day_365', 'physical_risk_factors'),
('day_365', 'diet_q'),
('day_365', 'laboratory_tests'),
('day_365', 'further_stroke_event_part'),
('day_365', 'history_of_depression'),
('day_365', 'concomitant_medications'),
('day_1', 'vital_signs'),
('day_1', 'bloods'),
('day_1', 'laboratory_tests'),
('day_1', 'serious_adverse_event')]
scan_id_df.drop(remove_tests, axis = 'columns',inplace = True)
demographics = pd.read_pickle('base_df_data.p')
stroke_onset = demographics.loc[scans.index,['identity_stroke_onset']]
multi_NIHSS = scan_id_df[('day_baseline','NIHSS_multiple')]
multi_with_stroke_onset = stroke_onset.join(multi_NIHSS)
for c in ['nihss_three_hr_datetime', 'nihss_seven_hr_datetime',
'nihss_eighteen_hr_datetime', 'nihss_other_hr_datetime']:
hrs = multi_with_stroke_onset[c] - multi_with_stroke_onset['identity_stroke_onset']
multi_with_stroke_onset[c] = hrs.dt.round('5min')
scan_id_df[('day_baseline','NIHSS_multiple')] = multi_with_stroke_onset
bit_1_cols = demographics.loc[:,'identity_gender':'identity_age_at_stroke_in_years'].columns
bit_2_cols = demographics.loc[:,'demographics_ancestry_1':].columns
useful_columns = bit_1_cols.append(bit_2_cols)
demographics = demographics.loc[scans.index,useful_columns]
demographics['identity_gender'] = demographics['identity_gender'].map({1:'female',0:'male'})
id_codes = pd.read_pickle('imaging_id_codes.p').loc[scans.index,['prefix']].join(scan_id_df[('day_1','infarct_type')])
#infarct_type = scan_id_df[('day_1','infarct_type')]
id_codes.columns = pd.MultiIndex.from_product([['day_90'],['lesion_location_confirmed'], id_codes.columns])
new_bit = scan_id_df['day_90']['lesion_location_confirmed'].copy()
new_bit.columns = pd.MultiIndex.from_product([['day_90'],['lesion_location_confirmed'],
new_bit.columns])
#scan_id_df['day_90']['lesion_location_confirmed'] = \
new_bit = new_bit.join(id_codes)
scan_id_df.drop(('day_90',
'lesion_location_confirmed',
'lesion location confirmed by imaging at 3 months (BC report)'), axis = 'columns',inplace = True)
scan_id_df = scan_id_df.join(new_bit)
scan_id_df['day_90']['lesion_location_confirmed']
```
This doesn't work! Sort out. Probably need to create multi index for ones to join
```
scan_id_df[('day_90','lesion_location_confirmed')]
infarct_type.index
scan_id_df[('day_90','lesion_location_confirmed')].join([id_codes,infarct_type]).columns
scan_id_df[('day_90','lesion_location_confirmed')].columns
```
### Do it!
delete the individual columns and keep the calculated average
```
scan_id_df[('day_90','TUGT_average','correct_average')] = \
scan_id_df['day_90']['TUGT_average'][['time1', 'time2', 'time3']].mean(axis = 'columns').round(1)
scan_id_df[('day_365','TUGT','correct_average')] = \
scan_id_df['day_365']['TUGT'][['time1', 'time2', 'time3']].mean(axis='columns').round(1)
bad = \
[('day_90', 'TUGT', 'time_taken'),
('day_90', 'TUGT_average', 'time1'),
('day_90', 'TUGT_average', 'time2'),
('day_90', 'TUGT_average', 'time3'),
('day_90', 'TUGT_average', 'TUGT_average'),
('day_365', 'TUGT', 'time1'),
('day_365', 'TUGT', 'time2'),
('day_365', 'TUGT', 'time3'),
('day_365', 'TUGT', 'average')]
scan_id_df.drop(bad,axis='columns',inplace=True)
# drop mri
mri_drop = scan_id_df.filter(regex='MRI').columns.tolist()
scan_id_df.drop(mri_drop,axis='columns',inplace=True)
response_drop = \
[('day_7', 'RAPA', 'resp'),
('day_7', 'RAPA', 'resp_other'),
('day_7', 'RAPA', 'resp_date'),
('day_90', 'mRS', 'resp'),
('day_90', 'mRS', 'resp_other'),
('day_90', 'BI', 'resp.1'),
('day_90', 'BI', 'resp_other.1'),
('day_90', 'SIS', 'resp.2'),
('day_90', 'SIS', 'resp_other.2'),
('day_90', 'RAPA', 'resp'),
('day_90', 'RAPA', 'resp_other'),
('day_90', 'RAPA', 'resp_date'),
('day_90', 'WSAS', 'resp.5'),
('day_90', 'WSAS', 'resp_other.5'),
('day_90', 'WSAS', 'resp_date.2'),
('day_365', 'mRS', 'resp'),
('day_365', 'mRS', 'resp_other'),
('day_365', 'BI', 'resp.1'),
('day_365', 'BI', 'resp_other.1'),
('day_365', 'SIS', 'resp.2'),
('day_365', 'SIS', 'resp_other.2'),
('day_365', 'RAPA', 'resp'),
('day_365', 'RAPA', 'resp_other'),
('day_365', 'RAPA', 'resp_date'),
('day_365', 'WSAS', 'resp.5'),
('day_365', 'WSAS', 'resp_other.5'),
('day_365', 'WSAS', 'resp_date.2')]
scan_id_df.drop(response_drop,axis='columns',inplace=True)
scan_id_df.columns = scan_id_df.columns.remove_unused_levels()
drop_nihss_multiple = [('day_baseline','NIHSS_multiple',c) for c in ['nihss_three_hr',
'nihss_seven_hr',
'nihss_eighteen_hr',
'nihss_other_hr']]
scan_id_df.drop(drop_nihss_multiple,axis = 'columns',inplace= True)
# RAVENs had no data
orig_df = pd.read_excel('data/extract/START 12 months (20161121).xlsx')
ravens = orig_df.iloc[scans.index,689:762]
ravens.rename(columns = {'RAVENS_total_score_12mth':'score'}, inplace = True)
scan_id_df[('day_365','RAVENs')] = ravens
scan_id_df.columns = scan_id_df.columns.remove_unused_levels()
scan_id_df
```
| github_jupyter |
```
import json
import requests
import pandas as pd
from tqdm import tqdm
from collections import Counter
import re
import Levenshtein
from cleanco import cleanco
import spacy
from spacy import displacy
nlp = spacy.load('en_core_web_lg')
doj_data = pd.read_json('combined.json', lines=True)
stock_ticker_data = requests.get('https://quantquote.com/docs/symbol_map_comnam.csv').content
stock_ticker_df = stock_ticker_data.decode('utf-8').split('\r\n')[3:]
stock_ticker_df = pd.DataFrame([i.split(',') for i in stock_ticker_df])
stock_ticker_df.columns = stock_ticker_df.iloc[0]
stock_ticker_df = stock_ticker_df[1:]
stock_ticker_df = stock_ticker_df.dropna(subset=['COMPANY NAME'])
```
## Tagging Organizations with Spacy
```
parsed_doj_contents = [set([w.text for w in nlp(c).ents if w.label_=='ORG'])
for c in tqdm_notebook(doj_data.contents.values)]
parsed_doj_titles = [set([w.text for w in nlp(c).ents if w.label_=='ORG'])
for c in tqdm(doj_data.title.values)]
doj_data['organizations'] = parsed_doj_contents
doj_data['organizations_titles'] = parsed_doj_titles
doj_data['all_orgs'] = doj_data['organizations'].apply(list) + doj_data['organizations_titles'].apply(list)
all_orgs = [o.lower() for i in doj_data.all_orgs for o in i]
all_companies = [i.lower() for i in stock_ticker_df['COMPANY NAME']]
# doj_data.to_json('doj_data_with_orgs.json')
```
## Simpler Tagging :(
```
def process_name(nm):
name = cleanco(nm).clean_name()
name = re.sub(r"[[:punct:]]+", "", name)
return name.lower()
clean_org_set_v2 = set([process_name(o) for i in tqdm(doj_data.all_orgs) for o in i])
clean_co_set_v2 = set([process_name(i) for i in tqdm(stock_ticker_df['COMPANY NAME']) ])
clean_co_to_symbol_dict = {}
symbol_to_full_nm_dict = {}
for _,symbol,_,name in stock_ticker_df[~stock_ticker_df['QUANTQUOTE PERMTICK'].str.contains(r'\d')].itertuples():
if len(name.strip())>0:
clean_co_to_symbol_dict[process_name(name)] = symbol
symbol_to_full_nm_dict[symbol] = name
doj_data['clean_orgs'] = doj_data.all_orgs.apply(lambda st: [process_name(o) for o in st])
doj_data['tagged_symbols'] = doj_data.clean_orgs.apply(lambda st: [clean_co_to_symbol_dict[o] for o in st if o in clean_co_to_symbol_dict])
doj_data_final = doj_data[doj_data.tagged_symbols.apply(lambda x: len(x)>0)].copy()
doj_data_final['tagged_companies'] = doj_data_final['tagged_symbols'].apply(lambda li: [symbol_to_full_nm_dict[i] for i in li])
# doj_data_final.to_json('doj_data_with_tags.json')
```
## Industry Tagging
```
nyse = pd.read_csv('nyse_company_list.csv')
nasdaq = pd.read_csv('nasdaq_company_list.csv')
nyse_symbol_set = set([i.lower() for i in nyse.Symbol.values])
nasdaq_symbol_set = set([i.lower() for i in nasdaq.Symbol.values])
nyse_symbol_sector_dict = {sym.lower():sector for sym,sector in zip(nyse.Symbol,nyse.Sector)}
nasdaq_symbol_sector_dict = {sym.lower():sector for sym,sector in zip(nasdaq.Symbol,nasdaq.Sector)}
nyse_symbol_industry_dict = {sym.lower():industry for sym,industry in zip(nyse.Symbol,nyse.Industry)}
nasdaq_symbol_industry_dict = {sym.lower():industry for sym,industry in zip(nasdaq.Symbol,nasdaq.Industry)}
doj_data_final['sectors'] = doj_data_final.tagged_symbols.apply(
lambda li:
[nyse_symbol_sector_dict.get(i,nasdaq_symbol_sector_dict.get(i))
for i in li if (i in nyse_symbol_sector_dict) or (i in nasdaq_symbol_sector_dict)])
doj_data_final['industries'] = doj_data_final.tagged_symbols.apply(
lambda li:
[nyse_symbol_industry_dict.get(i,nasdaq_symbol_industry_dict.get(i))
for i in li if i in nyse_symbol_industry_dict or i in nasdaq_symbol_industry_dict])
doj_data_final.to_json('doj_data_with_tags_and_industries.json')
```
| github_jupyter |
<a href="https://colab.research.google.com/github/wisrovi/pyimagesearch-buy/blob/main/visual_logging_example.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# Visual-logging, my new favorite tool for debugging OpenCV and Python apps
### by [PyImageSearch.com](http://www.pyimagesearch.com)
## Welcome to **[PyImageSearch Plus](http://pyimg.co/plus)** Jupyter Notebooks!
This notebook is associated with the [Visual-logging, my new favorite tool for debugging OpenCV and Python apps](https://www.pyimagesearch.com/2014/12/22/visual-logging-new-favorite-tool-debugging-opencv-python-apps/) blog post published on 2014-12-22.
Only the code for the blog post is here. Most codeblocks have a 1:1 relationship with what you find in the blog post with two exceptions: (1) Python classes are not separate files as they are typically organized with PyImageSearch projects, and (2) Command Line Argument parsing is replaced with an `args` dictionary that you can manipulate as needed.
We recommend that you execute (press ▶️) the code block-by-block, as-is, before adjusting parameters and `args` inputs. Once you've verified that the code is working, you are welcome to hack with it and learn from manipulating inputs, settings, and parameters. For more information on using Jupyter and Colab, please refer to these resources:
* [Jupyter Notebook User Interface](https://jupyter-notebook.readthedocs.io/en/stable/notebook.html#notebook-user-interface)
* [Overview of Google Colaboratory Features](https://colab.research.google.com/notebooks/basic_features_overview.ipynb)
As a reminder, these PyImageSearch Plus Jupyter Notebooks are not for sharing; please refer to the **Copyright** directly below and **Code License Agreement** in the last cell of this notebook.
Happy hacking!
*Adrian*
<hr>
***Copyright:*** *The contents of this Jupyter Notebook, unless otherwise indicated, are Copyright 2020 Adrian Rosebrock, PyimageSearch.com. All rights reserved. Content like this is made possible by the time invested by the authors. If you received this Jupyter Notebook and did not purchase it, please consider making future content possible by joining PyImageSearch Plus at http://pyimg.co/plus/ today.*
### Install the necessary packages
```
!pip install visual-logging
```
### Download the code zip file
```
!wget https://www.pyimagesearch.com/wp-content/uploads/2014/12/visual-logging-example.zip
!unzip -qq visual-logging-example.zip
%cd visual-logging-example
```
## Blog Post Code
### Import Packages
```
# import the necessary packages
from matplotlib import pyplot as plt
from logging import FileHandler
from vlogging import VisualRecord
import logging
import cv2
```
### visual-logging, my new favorite tool for debugging OpenCV and Python apps
```
# open the logging file
logger = logging.getLogger("visual_logging_example")
fh = FileHandler("demo.html", mode = "w")
# set the logger attributes
logger.setLevel(logging.DEBUG)
logger.addHandler(fh)
# load our example image and convert it to grayscale
image = cv2.imread("lex.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# loop over some varying sigma sizes
for s in range(3, 11, 2):
# blur the image and detect edges
blurred = cv2.GaussianBlur(image, (s, s), 0)
edged = cv2.Canny(blurred, 75, 200)
logger.debug(VisualRecord(("Detected edges using sigma = %d" % (s)),
[blurred, edged], fmt = "png"))
#@title Display `demo.html`
import IPython
IPython.display.HTML(filename="demo.html")
```
For a detailed walkthrough of the concepts and code, be sure to refer to the full tutorial, [*Visual-logging, my new favorite tool for debugging OpenCV and Python apps*](https://www.pyimagesearch.com/2014/12/22/visual-logging-new-favorite-tool-debugging-opencv-python-apps/) published on 2014-12-22.
# Code License Agreement
```
Copyright (c) 2020 PyImageSearch.com
SIMPLE VERSION
Feel free to use this code for your own projects, whether they are
purely educational, for fun, or for profit. THE EXCEPTION BEING if
you are developing a course, book, or other educational product.
Under *NO CIRCUMSTANCE* may you use this code for your own paid
educational or self-promotional ventures without written consent
from Adrian Rosebrock and PyImageSearch.com.
LONGER, FORMAL VERSION
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.
Notwithstanding the foregoing, you may not use, copy, modify, merge,
publish, distribute, sublicense, create a derivative work, and/or
sell copies of the Software in any work that is designed, intended,
or marketed for pedagogical or instructional purposes related to
programming, coding, application development, or information
technology. Permission for such use, copying, modification, and
merger, publication, distribution, sub-licensing, creation of
derivative works, or sale is expressly withheld.
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.
```
| github_jupyter |
```
!pip install transformers
import torch
from transformers import BertForQuestionAnswering, BertTokenizer
model = BertForQuestionAnswering.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')
tokenizer = BertTokenizer.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')
```
### Design the question and reference text
```
question = "What does NUS mean?"
answer_text = "The National University of Singapore (NUS) is the national research university of Singapore. \
Founded in 1905 as the Straits Settlements and Federated Malay States Government Medical School, NUS is the oldest higher education institution in Singapore. \
It is consistently ranked within the top 20 universities in the world and is considered to be the best university in the Asia-Pacific. \
NUS is a comprehensive research university, \
offering a wide range of disciplines, including the sciences, medicine and dentistry, design and environment, law, arts and social sciences, engineering, business, computing and music \
at both the undergraduate and postgraduate levels."
# Apply the tokenizer to the input text, treating them as a text-pair.
input_ids = tokenizer.encode(question, answer_text)
print('The input has a total of {:} tokens.'.format(len(input_ids)))
# BERT only needs the token IDs, but for the purpose of inspecting the
# tokenizer's behavior, let's also get the token strings and display them.
tokens = tokenizer.convert_ids_to_tokens(input_ids)
# For each token and its id...
for token, id in zip(tokens, input_ids):
# If this is the [SEP] token, add some space around it to make it stand out.
if id == tokenizer.sep_token_id:
print('')
# Print the token string and its ID in two columns.
print('{:<12} {:>6,}'.format(token, id))
if id == tokenizer.sep_token_id:
print('')
```
#### Split question and reference text
```
# Search the input_ids for the first instance of the `[SEP]` token.
sep_index = input_ids.index(tokenizer.sep_token_id)
# The number of segment A tokens includes the [SEP] token istelf.
num_seg_a = sep_index + 1
# The remainder are segment B.
num_seg_b = len(input_ids) - num_seg_a
# Construct the list of 0s and 1s.
segment_ids = [0]*num_seg_a + [1]*num_seg_b
# There should be a segment_id for every input token.
assert len(segment_ids) == len(input_ids)
start_scores, end_scores = model(torch.tensor([input_ids]), # The tokens representing our input text.
token_type_ids=torch.tensor([segment_ids])) # The segment IDs to differentiate question from answer_text
```
#### Run the BERT Model
```
# Find the tokens with the highest `start` and `end` scores.
answer_start = torch.argmax(start_scores)
answer_end = torch.argmax(end_scores)
```
#### Combine the tokens in the answer and print it out.
```
# Start with the first token.
answer = tokens[answer_start]
# Select the remaining answer tokens and join them with whitespace.
for i in range(answer_start + 1, answer_end + 1):
# If it's a subword token, then recombine it with the previous token.
if tokens[i][0:2] == '##':
answer += tokens[i][2:]
# Otherwise, add a space then the token.
else:
answer += ' ' + tokens[i]
print('Answer: "' + answer + '"')
```
| github_jupyter |
# Tune 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 train a classification model with two hyperparameters, but the principles apply to any kind of model you can train with Azure Machine Learning.
## Connect to your workspace
To get started, connect to your workspace.
> **Note**: If you haven't already established an authenticated session with your Azure subscription, you'll be prompted to authenticate by clicking a link, entering an authentication code, and signing into Azure.
```
import azureml.core
from azureml.core import Workspace
# Load the workspace from the saved config file
ws = Workspace.from_config()
print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
```
## Prepare data
In this lab, you'll use a dataset containing details of diabetes patients. Run the cell below to create this dataset (if it already exists, the existing version will be used)
```
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
Now let's create a folder for the training script you'll use to train the 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. In this example, you'll use a *Gradient Boosting* algorithm to train a classification model. The script must include:
- An argument for each hyperparameter you want to optimize (in this case, the learning rate and number of estimators for the Gradient Boosting algorithm)
- 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 argparse, joblib, os
from azureml.core import Run
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import roc_auc_score, roc_curve
# Get the experiment run context
run = Run.get_context()
# Get script arguments
parser = argparse.ArgumentParser()
# Input dataset
parser.add_argument("--input-data", type=str, dest='input_data', help='training dataset')
# Hyperparameters
parser.add_argument('--learning_rate', type=float, dest='learning_rate', default=0.1, help='learning rate')
parser.add_argument('--n_estimators', type=int, dest='n_estimators', default=100, help='number of estimators')
# Add arguments to args collection
args = parser.parse_args()
# Log Hyperparameter values
run.log('learning_rate', np.float(args.learning_rate))
run.log('n_estimators', np.int(args.n_estimators))
# load the diabetes dataset
print("Loading Data...")
diabetes = run.input_datasets['training_data'].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 Gradient Boosting classification model with the specified hyperparameters
print('Training a classification model')
model = GradientBoostingClassifier(learning_rate=args.learning_rate,
n_estimators=args.n_estimators).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))
# Save the model in the run outputs
os.makedirs('outputs', exist_ok=True)
joblib.dump(value=model, filename='outputs/diabetes_model.pkl')
run.complete()
```
## Create compute
Hyperparameter tuning involves running multiple training iterations with different hyperparameter values and comparing the performance metrics of the resulting models. To do this efficiently, we'll take advantage of on-demand cloud compute and create a cluster - this will allow multiple training iterations to be run concurrently.
Use the following code to specify an Azure Machine Learning compute cluster (it will be created if it doesn't already exist).
> **Important**: Change *your-compute-cluster* to the name of 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 = "aizatcluster"
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)
```
> **Note**: Compute instances and clusters are based on standard Azure virtual machine images. For this exercise, the *Standard_DS11_v2* image is recommended to achieve the optimal balance of cost and performance. If your subscription has a quota that does not include this image, choose an alternative image; but bear in mind that a larger image may incur higher cost and a smaller image may not be sufficient to complete the tasks. Alternatively, ask your Azure administrator to extend your quota.
You'll need a Python environment to be hosted on the compute, so let's define that as Conda configuration file.
```
%%writefile $experiment_folder/hyperdrive_env.yml
name: batch_environment
dependencies:
- python=3.6.2
- scikit-learn
- pandas
- numpy
- pip
- pip:
- azureml-defaults
```
## Run a hyperparameter tuning 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.
> **Note**: In this example, we aren't specifying an early stopping policy. Such a policy is only relevant if the training script performs multiple training iterations, logging the primary metric for each iteration. This approach is typically employed when training deep neural network models over multiple *epochs*.
```
from azureml.core import Experiment, ScriptRunConfig, Environment
from azureml.train.hyperdrive import GridParameterSampling, HyperDriveConfig, PrimaryMetricGoal, choice
from azureml.widgets import RunDetails
# Create a Python environment for the experiment
hyper_env = Environment.from_conda_specification("experiment_env", experiment_folder + "/hyperdrive_env.yml")
# Get the training dataset
diabetes_ds = ws.datasets.get("diabetes dataset")
# Create a script config
script_config = ScriptRunConfig(source_directory=experiment_folder,
script='diabetes_training.py',
# Add non-hyperparameter arguments -in this case, the training dataset
arguments = ['--input-data', diabetes_ds.as_named_input('training_data')],
environment=hyper_env,
compute_target = training_cluster)
# Sample a range of parameter values
params = GridParameterSampling(
{
# Hyperdrive will try 6 combinations, adding these as script arguments
'--learning_rate': choice(0.01, 0.1, 1.0),
'--n_estimators' : choice(10, 100)
}
)
# Configure hyperdrive settings
hyperdrive = HyperDriveConfig(run_config=script_config,
hyperparameter_sampling=params,
policy=None, # No early stopping policy
primary_metric_name='AUC', # Find the highest AUC metric
primary_metric_goal=PrimaryMetricGoal.MAXIMIZE,
max_total_runs=6, # Restict the experiment to 6 iterations
max_concurrent_runs=2) # Run up to 2 iterations in parallel
# Run the experiment
experiment = Experiment(workspace=ws, name='mslearn-diabetes-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**: If a message indicating that a non-numeric can't be visualized is displayed, you can ignore it.
## 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).
```
# Print all child runs, sorted by the primary metric
for child_run in run.get_children_sorted_by_primary_metric():
print(child_run)
# Get the best run, and its metrics and arguments
best_run = run.get_best_run_by_primary_metric()
best_run_metrics = best_run.get_metrics()
script_arguments = 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(' -Arguments:',script_arguments)
```
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 |
# 插值
```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
设置 **`Numpy`** 浮点数显示格式:
```
np.set_printoptions(precision=2, suppress=True)
```
从文本中读入数据,数据来自 http://kinetics.nist.gov/janaf/html/C-067.txt ,保存为结构体数组:
```
data = np.genfromtxt("JANAF_CH4.txt",
delimiter="\t", # TAB 分隔
skiprows=1, # 忽略首行
names=True, # 读入属性
missing_values="INFINITE", # 缺失值
filling_values=np.inf) # 填充缺失值
```
显示部分数据:
```
for row in data[:7]:
print "{}\t{}".format(row['TK'], row['Cp'])
print "...\t..."
```
绘图:
```
p = plt.plot(data['TK'], data['Cp'], 'kx')
t = plt.title("JANAF data for Methane $CH_4$")
a = plt.axis([0, 6000, 30, 120])
x = plt.xlabel("Temperature (K)")
y = plt.ylabel(r"$C_p$ ($\frac{kJ}{kg K}$)")
```
## 插值
假设我们要对这组数据进行插值。
先导入一维插值函数 `interp1d`:
interp1d(x, y)
```
from scipy.interpolate import interp1d
ch4_cp = interp1d(data['TK'], data['Cp'])
```
`interp1d` 的返回值可以像函数一样接受输入,并返回插值的结果。
单个输入值,注意返回的是数组:
```
ch4_cp(382.2)
```
输入数组,返回的是对应的数组:
```
ch4_cp([32.2,323.2])
```
默认情况下,输入值要在插值允许的范围内,否则插值会报错:
```
ch4_cp(8752)
```
但我们可以通过参数设置允许超出范围的值存在:
```
ch4_cp = interp1d(data['TK'], data['Cp'],
bounds_error=False)
```
不过由于超出范围,所以插值的输出是非法值:
```
ch4_cp(8752)
```
可以使用指定值替代这些非法值:
```
ch4_cp = interp1d(data['TK'], data['Cp'],
bounds_error=False, fill_value=-999.25)
ch4_cp(8752)
```
### 线性插值
`interp1d` 默认的插值方法是线性,关于线性插值的定义,请参见:
- 维基百科-线性插值: https://zh.wikipedia.org/wiki/%E7%BA%BF%E6%80%A7%E6%8F%92%E5%80%BC
- 百度百科-线性插值: http://baike.baidu.com/view/4685624.htm
其基本思想是,已知相邻两点 $x_1,x_2$ 对应的值 $y_1,y_2$ ,那么对于 $(x_1,x_2)$ 之间的某一点 $x$ ,线性插值对应的值 $y$ 满足:点 $(x,y)$ 在 $(x_1,y_1),(x_2,y_2)$ 所形成的线段上。
应用线性插值:
```
T = np.arange(100,355,5)
plt.plot(T, ch4_cp(T), "+k")
p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8)
```
其中红色的圆点为原来的数据点,黑色的十字点为对应的插值点,可以明显看到,相邻的数据点的插值在一条直线上。
### 多项式插值
我们可以通过 `kind` 参数来调节使用的插值方法,来得到不同的结果:
- `nearest` 最近邻插值
- `zero` 0阶插值
- `linear` 线性插值
- `quadratic` 二次插值
- `cubic` 三次插值
- `4,5,6,7` 更高阶插值
最近邻插值:
```
cp_ch4 = interp1d(data['TK'], data['Cp'], kind="nearest")
p = plt.plot(T, cp_ch4(T), "k+")
p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8)
```
0阶插值:
```
cp_ch4 = interp1d(data['TK'], data['Cp'], kind="zero")
p = plt.plot(T, cp_ch4(T), "k+")
p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8)
```
二次插值:
```
cp_ch4 = interp1d(data['TK'], data['Cp'], kind="quadratic")
p = plt.plot(T, cp_ch4(T), "k+")
p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8)
```
三次插值:
```
cp_ch4 = interp1d(data['TK'], data['Cp'], kind="cubic")
p = plt.plot(T, cp_ch4(T), "k+")
p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8)
```
事实上,我们可以使用更高阶的多项式插值,只要将 `kind` 设为对应的数字即可:
四次多项式插值:
```
cp_ch4 = interp1d(data['TK'], data['Cp'], kind=4)
p = plt.plot(T, cp_ch4(T), "k+")
p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8)
```
可以参见:
- 维基百科-多项式插值:https://zh.wikipedia.org/wiki/%E5%A4%9A%E9%A1%B9%E5%BC%8F%E6%8F%92%E5%80%BC
- 百度百科-插值法:http://baike.baidu.com/view/754506.htm
对于二维乃至更高维度的多项式插值:
```
from scipy.interpolate import interp2d, interpnd
```
其使用方法与一维类似。
### 径向基函数
关于径向基函数,可以参阅:
- 维基百科-Radial basis fucntion:https://en.wikipedia.org/wiki/Radial_basis_function
径向基函数,简单来说就是点 $x$ 处的函数值只依赖于 $x$ 与某点 $c$ 的距离:
$$\Phi(x,c) = \Phi(\|x-c\|)$$
```
x = np.linspace(-3,3,100)
```
常用的径向基(`RBF`)函数有:
高斯函数:
```
plt.plot(x, np.exp(-1 * x **2))
t = plt.title("Gaussian")
```
`Multiquadric` 函数:
```
plt.plot(x, np.sqrt(1 + x **2))
t = plt.title("Multiquadric")
```
`Inverse Multiquadric` 函数:
```
plt.plot(x, 1. / np.sqrt(1 + x **2))
t = plt.title("Inverse Multiquadric")
```
### 径向基函数插值
对于径向基函数,其插值的公式为:
$$
f(x) = \sum_j n_j \Phi(\|x-x_j\|)
$$
我们通过数据点 $x_j$ 来计算出 $n_j$ 的值,来计算 $x$ 处的插值结果。
```
from scipy.interpolate.rbf import Rbf
```
使用 `multiquadric` 核的:
```
cp_rbf = Rbf(data['TK'], data['Cp'], function = "multiquadric")
plt.plot(data['TK'], data['Cp'], 'k+')
p = plt.plot(data['TK'], cp_rbf(data['TK']), 'r-')
```
使用 `gaussian` 核:
```
cp_rbf = Rbf(data['TK'], data['Cp'], function = "gaussian")
plt.plot(data['TK'], data['Cp'], 'k+')
p = plt.plot(data['TK'], cp_rbf(data['TK']), 'r-')
```
使用 `nverse_multiquadric` 核:
```
cp_rbf = Rbf(data['TK'], data['Cp'], function = "inverse_multiquadric")
plt.plot(data['TK'], data['Cp'], 'k+')
p = plt.plot(data['TK'], cp_rbf(data['TK']), 'r-')
```
不同的 `RBF` 核的结果也不同。
### 高维 `RBF` 插值
```
from mpl_toolkits.mplot3d import Axes3D
```
三维数据点:
```
x, y = np.mgrid[-np.pi/2:np.pi/2:5j, -np.pi/2:np.pi/2:5j]
z = np.cos(np.sqrt(x**2 + y**2))
fig = plt.figure(figsize=(12,6))
ax = fig.gca(projection="3d")
ax.scatter(x,y,z)
```
3维 `RBF` 插值:
```
zz = Rbf(x, y, z)
xx, yy = np.mgrid[-np.pi/2:np.pi/2:50j, -np.pi/2:np.pi/2:50j]
fig = plt.figure(figsize=(12,6))
ax = fig.gca(projection="3d")
ax.plot_surface(xx,yy,zz(xx,yy),rstride=1, cstride=1, cmap=plt.cm.jet)
```
| github_jupyter |
```
import tensorflow as tf
import numpy as np
import math
import scipy
goal_size = 4
batch_size = 10
example_goal = np.random.rand(batch_size, goal_size)
np.random.shuffle(example_goal)
print(example_goal)
arg_max = tf.argmax(example_goal, axis=1, output_type=tf.int32)
print(arg_max)
one_hot = tf.one_hot(arg_max, depth=1)
print(one_hot)
# # example_goal[0][0] = 1
# np.random.shuffle(example_goal)
# print(example_goal, '\n', tf.argmax(example_goal))
# # np.random.shuffle(example_goal)
# example_goal = tf.convert_to_tensor(example_goal)
# print(tf.argmax(example_goal, 1), tf.reduce_max(example_goal))
# highest_vals_per_col = tf.argmax(example_goal, 1)
# print(highest_vals_per_col, highest_vals_per_col.shape)
# # max_value = max(example_goal)
# # max_index = my_list.index(max_value)
place_h = []
# for i in range(goal_size):
# print(i, example_goal.shape)
# a = highest_vals_per_col.data[i]
# print[a]
# place_h[i] = [example_goal[0][a]]
one_hot_idx = tf.argmax(place_h)
print(one_hot_idx)
one_hot = tf.one_hot(tf.argmax(example_goal), depth=4, dtype=float, on_value=1.0, off_value=0.0)
print(one_hot)
one_hot = tf.squeeze(one_hot)
print(one_hot)
x,y = 17,17
a = np.ones((7,7))
# a[1][1] = 1
map_ = np.zeros((18,18))
shape_total = map_.shape
shape_loc = a.shape
np.random.shuffle(a)
nfz = int((shape_loc[0]-1)/2)
print(a, "\n", nfz)
pad_left = x
pad_right = shape_total[0] - x -1# - shape_loc[0] + nfz
pad_up = y # - nfz
pad_down = shape_total[0] - y - 1# - shape_loc[0] + nfz
print(pad_left, pad_right, pad_up, pad_down)
padded = np.pad(a, ((pad_up, pad_down), (pad_left, pad_right)))
print(padded, "\n", padded.shape)
padded = padded[nfz:(padded.shape[0]-nfz), nfz:(padded[1]-nfz)]
print(padded, padded.shape)
# def pad_centered(state, map_in, pad_value):
map_in = np.zeros((10,10))
print(map_in.shape)
padding_rows = math.ceil(map_in.shape[0] / 2.0)
padding_cols = math.ceil(map_in.shape[1] / 2.0)
position_x, position_y = 0,0
map_in[position_x][position_y] = 1
pad_value = 1
# print("pos", position_x, position_y)
position_row_offset = padding_rows - position_y
position_col_offset = padding_cols - position_x
res = np.pad(map_in,
pad_width=[[padding_rows + position_row_offset - 1, padding_rows - position_row_offset],
[padding_cols + position_col_offset - 1, padding_cols - position_col_offset],
# [0, 0]
],
mode='constant',
constant_values=pad_value)
print(res,"\n", res.shape)
a = np.zeros((6,6))
b = np.zeros((6,6))
for i in range(5):
a[i][i]=1
np.random.shuffle(a)
b[0][0]=1
print(a, "\n", bool(b.any))
# a = not bool(a)
a = np.ones((6,6))
a = np.logical_not(a).astype(int)
b = b.astype(int)
print(a, "\n", b)
c = b*a
print(c)
# c = np.logical_not(c).astype(int)
print(c)
print(not np.all(c == 0))
lm_size = (17,17)
NT_size = (9,9)
print(17**2)
print(9**2)
print(17**2-9**2)
a = np.zeros(lm_size)
print(a)
# NT_size[0]:(lm_size[0]-NT_size[0]), NT_size[0]:(lm_size[0]-NT_size[0])
a[9-5:17-4,9-5:17-4] = 1
print(a)
l1 = [10.3, 22.3, 1.1, 2.34, 0]
l2 = [1.3, 2.3, 10.1, 20.34, 330]
def pad_lm_to_total_size(h_target, position):
"""
pads input of shape local_map to output of total_map_size
"""
shape_map = (32,32)
shape_htarget = h_target.shape
# print(shape_htarget, shape_map)
x, y = position
pad_left = x
pad_right = shape_map[0] - x - 1
pad_up = y
pad_down = shape_map[1] - y - 1
padded = np.pad(h_target, ((pad_up, pad_down), (pad_left, pad_right)))
lm_as_tm_size = padded[int((shape_htarget[0] - 1) / 2):int(padded.shape[0] - (shape_htarget[0] - 1) / 2),
int((shape_htarget[1] - 1) / 2):int(padded.shape[1] - (shape_htarget[1] - 1) / 2)]
return lm_as_tm_size.astype(bool)
position = (31,31)
h_target = np.zeros((15,15))
h_target[7][7] = 1
pht = pad_lm_to_total_size(h_target, position)
print(pht, pht.shape)
print(pht.any()==True)
a = np.zeros((10,5))
a[9,3]=1
print(a)
a = np.zeros((10,10))
a[0,1]=1
print(a)
#Input
input_img = Input(shape=(128, 128, 3))#Encoder
y = Conv2D(32, (3, 3), padding='same',strides =(2,2))(input_img)
y = LeakyReLU()(y)
y = Conv2D(64, (3, 3), padding='same',strides =(2,2))(y)
y = LeakyReLU()(y)
y1 = Conv2D(128, (3, 3), padding='same',strides =(2,2))(y) # skip-1
y = LeakyReLU()(y1)
y = Conv2D(256, (3, 3), padding='same',strides =(2,2))(y)
y = LeakyReLU()(y)
y2 = Conv2D(256, (3, 3), padding='same',strides =(2,2))(y)# skip-2
y = LeakyReLU()(y2)
y = Conv2D(512, (3, 3), padding='same',strides =(2,2))(y)
y = LeakyReLU()(y)
y = Conv2D(1024, (3, 3), padding='same',strides =(2,2))(y)
y = LeakyReLU()(y)#Flattening for the bottleneck
vol = y.shape
x = Flatten()(y)
latent = Dense(128, activation='relu')(x)
# Helper function to apply activation and batch normalization to the # output added with output of residual connection from the encoderdef lrelu_bn(inputs):
lrelu = LeakyReLU()(inputs)
bn = BatchNormalization()(lrelu)
return bn#Decoder
y = Dense(np.prod(vol[1:]), activation='relu')(latent)
y = Reshape((vol[1], vol[2], vol[3]))(y)
y = Conv2DTranspose(1024, (3,3), padding='same')(y)
y = LeakyReLU()(y)
y = Conv2DTranspose(512, (3,3), padding='same',strides=(2,2))(y)
y = LeakyReLU()(y)
y = Conv2DTranspose(256, (3,3), padding='same',strides=(2,2))(y)
y= Add()([y2, y]) # second skip connection added here
y = lrelu_bn(y)
y = Conv2DTranspose(256, (3,3), padding='same',strides=(2,2))(y)
y = LeakyReLU()(y)
y = Conv2DTranspose(128, (3,3), padding='same',strides=(2,2))(y)
y= Add()([y1, y]) # first skip connection added here
y = lrelu_bn(y)
y = Conv2DTranspose(64, (3,3), padding='same',strides=(2,2))(y)
y = LeakyReLU()(y)
y = Conv2DTranspose(32, (3,3), padding='same',strides=(2,2))(y)
y = LeakyReLU()(y)
y = Conv2DTranspose(3, (3,3), activation='sigmoid', padding='same',strides=(2,2))(y)
def lrelu(inputs):
lrelu = LeakyReLU()(inputs)
bn = BatchNormalization()(lrelu)
return bn
conv_layers = 2
mb = 25
current_mb = 15
hidden_layer_size = 256
name = 'hl_model_'
lm = np.random.rand(17,17,4)
gm = np.random.rand(21,21,4)
states_proc = np.array(current_mb/mb)
def build_hl_model(local_map, global_map, states_proc): #local:17,17,4; global:21:21,4
# local map processing layers
# for k in range(conv_layers):
local_map_input = tf.keras.layers.Input(shape=local_map.shape)
global_map_input = tf.keras.layers.Input(shape=global_map.shape)
states_proc_input = tf.keras.layers.Input(shape=states_proc.shape)
local_map_1 = tf.keras.layers.Conv2D(4, 3, activation='elu',
strides=(1, 1),
name=name + 'local_conv_' + str(0 + 1))(local_map_input) #out:(None, 1, 15, 15, 4) 1156->
local_map_2 = tf.keras.layers.Conv2D(8, 3, activation='elu',
strides=(1, 1),
name=name + 'local_conv_' + str(1 + 1))(local_map_1) #out:(None, 1, 13, 13, 8)
local_map_3 = tf.keras.layers.Conv2D(16, 3, activation='elu',
strides=(1, 1),
name=name + 'local_conv_' + str(2 + 1))(local_map_2) #out:(None, 1, 11, 11, 16)
local_map_4 = tf.keras.layers.Conv2D(16, 3, activation='elu',
strides=(1, 1),
name=name + 'local_conv_' + str(3 + 1))(local_map_3) #out:(None, 1, 9, 9, 16)
flatten_local = tf.keras.layers.Flatten(name=name + 'local_flatten')(local_map_4)
# global map processing layers
global_map_1 = tf.keras.layers.Conv2D(4, 5, activation='elu',
strides=(1, 1),
name=name + 'global_conv_' + str(0 + 1))(global_map_input) #out:17
global_map_2 = tf.keras.layers.Conv2D(8, 5, activation='elu',
strides=(1, 1),
name=name + 'global_map_' + str(1 + 1))(global_map_1) #out:13
global_map_3 = tf.keras.layers.Conv2D(16, 5, activation='elu',
strides=(1, 1),
name=name + 'global_map_' + str(2 + 1))(global_map_2)#out:9
flatten_global = tf.keras.layers.Flatten(name=name + 'global_flatten')(global_map_3)
print(flatten_local.shape, flatten_global.shape)
flatten_map = tf.keras.layers.Concatenate(name=name + 'concat_flatten')([flatten_global, flatten_local])
layer = tf.keras.layers.Concatenate(name=name + 'concat')([flatten_map, states_proc_input])
layer_1 = tf.keras.layers.Dense(256, activation='elu', name=name + 'hidden_layer_all_hl_' + str(0))(
layer)
layer_2 = tf.keras.layers.Dense(512, activation='elu', name=name + 'hidden_layer_all_hl_' + str(1))(
layer_1)
layer_3 = tf.keras.layers.Dense(256, activation='elu', name=name + 'hidden_layer_all_hl_' + str(2))(
layer_2)
output = tf.keras.layers.Dense(units=300, activation='linear', name=name + 'last_dense_layer_hl')(
layer)
reshape = tf.keras.layers.Reshape((5,5,12), name=name + 'last_dense_layer')(output)
landing = tf.keras.layers.Dense(units=128, activation='elu', name=name + 'landing_preproc_layer_hl')(
layer_3)
landing = tf.keras.layers.Dense(units=1, activation='elu', name=name + 'landing_layer_hl')(landing)
# deconvolutional part aiming at 17x17
deconv_1 = tf.keras.layers.Conv2DTranspose(filters=16, kernel_size=5, activation='elu', name=name + 'deconv_' + str(1))(reshape)
skip_1 = tf.keras.layers.Concatenate(name=name + '1st_skip_connection_concat', axis=3)([deconv_1, tf.squeeze(local_map_4, axis=1)])
deconv_2 = tf.keras.layers.Conv2DTranspose(filters=8, kernel_size=3, activation='elu', name=name + 'deconv_' + str(2))(skip_1)
skip_2 = tf.keras.layers.Concatenate(name=name + '2nd_skip_connection_concat', axis=3)([deconv_2, tf.squeeze(local_map_3, axis=1)])
deconv_2_1 = tf.keras.layers.Conv2DTranspose(filters=8, kernel_size=3, activation='elu', name=name + 'deconv_' + str(2.1))(skip_2)
skip_3 = tf.keras.layers.Concatenate(name=name + '3rd_skip_connection_concat', axis=3)([deconv_2_1, tf.squeeze(local_map_2, axis=1)])
deconv_3 = tf.keras.layers.Conv2DTranspose(filters=4, kernel_size=5, activation='elu', name=name + 'deconv_' + str(3))(skip_3)
deconv_4 = tf.keras.layers.Conv2DTranspose(filters=1, kernel_size=1, activation='elu', name=name + 'deconv_' + str(4))(deconv_3)
flatten_deconv = tf.keras.layers.Flatten(name=name + 'deconv_flatten')(deconv_4)
concat_final = tf.keras.layers.Concatenate(name=name + 'concat_final')([flatten_deconv, landing])
return tf.keras.Model(inputs=[local_map_input, global_map_input, states_proc_input], outputs=concat_final)
model = build_hl_model(lm[tf.newaxis, ...], gm[tf.newaxis, ...], states_proc[tf.newaxis, ...]) #lm, gm, states_proc)
model.compile(optimizer='adam', loss='mse')
# model.build()
model.summary()
a = np.arange(10)
print(a)
a = a.reshape(2,5)
print(a)
a = tf.keras.layers.Flatten()(tf.convert_to_tensor(a))
print(a)
a, b, c = tf.stop_gradient([1,2,3])
print( a,b,c
)
local_map_in = np.zeros((4,5))
global_map_in = np.ones_like(local_map_in)
scalars_in = 1
# local_map_in[0][4]=np.float('nan')
if np.any(np.isnan(local_map_in)) or np.any(np.isnan(global_map_in)) or np.any(np.isnan(scalars_in)) :
print(f'###################### Nan in act input: {np.isnan(local_map_in)}')
size = (40)
p = np.zeros(size)
p[1] = 1
a = np.random.choice(range(40), size=1, p=p)
a = tf.one_hot((1000), depth=size).numpy().reshape(5,8)
print(a)
a = tf.keras.layers.Flatten()(a)
print(a)
a = a.numpy().reshape(5,8)
print(a)
b = np.array([1, 1, 0, 0, 1])
b = tf.math.is_nan(tf.convert_to_tensor(b))
a = tf.reduce_any(b)
print(a)
sz = 11
a = np.random.rand(sz,sz)
b = 3
c = int((sz-1)/2 - (b-1)/2)
print(c)
for i in range(b):
for j in range(b):
# a[i+c][j+c]=-math.inf
a[i+c][j+c]=0
print(a)
a = tf.keras.layers.Flatten()(a[tf.newaxis, ...]).numpy()
a = np.squeeze(a)
print(a)
a = scipy.special.softmax(a)
print(a)
a = np.zeros((17,17))
v = np.zeros((11,11))
b = np.random.rand(11,11)
dv = int((a.shape[0]-b.shape[0])/2)
print(dv)
for i in range(b.shape[0]):
for j in range(b.shape[1]):
a[i+dv][j+dv]=b[i][j]
print(a)
# v = np.zeros((11,11,4))
print(v)
dv = int((a.shape[0]-v.shape[0])/2)
print(dv)
for i in range(v.shape[0]):
for j in range(v.shape[1]):
v[i][j]=a[i+dv][j+dv] # [3]
print(v)
```
| github_jupyter |
# The Python ecosystem
## Why Python?
### Python in a nutshell
[Python](https://www.python.org) is a multi-purpose programming language created in 1989 by [Guido van Rossum](https://en.wikipedia.org/wiki/Guido_van_Rossum) and developed under a open source license.
It has the following characteristics:
- multi-paradigms (procedural, fonctional, object-oriented);
- dynamic types;
- automatic memory management;
- and much more!
### The Python syntax
For more examples, see the [Python cheatsheet](../tools/python_cheatsheet).
```
def hello(name):
print(f"Hello, {name}")
friends = ["Lou", "David", "Iggy"]
for friend in friends:
hello(friend)
```
### Introduction to Data Science
- Main objective: extract insight from data.
- Expression born in 1997 in the statistician community.
- "A Data Scientist is a statistician that lives in San Francisco".
- 2012 : "Sexiest job of the 21st century" (Harvard Business Review).
- [Controversy](https://en.wikipedia.org/wiki/Data_science#Relationship_to_statistics) on the expression's real usefulness.
[](https://en.wikipedia.org/wiki/Data_science)
[](http://drewconway.com/zia/2013/3/26/the-data-science-venn-diagram)
[](http://drewconway.com/zia/2013/3/26/the-data-science-venn-diagram)
### Python, a standard for ML and Data Science
- Language qualities (ease of use, simplicity, versatility).
- Involvement of the scientific and academical communities.
- Rich ecosystem of dedicated open source libraries.
## Essential Python tools
### Anaconda
[Anaconda](https://www.anaconda.com/distribution/) is a scientific distribution including Python and many (1500+) specialized packages. it is the easiest way to setup a work environment for ML and Data Science with Python.
[](https://www.anaconda.com/distribution/)
### Jupyter Notebook
The Jupyter Notebook is an open-source web application that allows to manage documents (_.ipynb_ files) that may contain live code, equations, visualizations and text.
It has become the *de facto* standard for sharing research results in numerical fields.
[](https://jupyter.org/)
### Google Colaboratory
Cloud environment for executing Jupyter notebooks through CPU, GPU or TPU.
[](https://colab.research.google.com)
### NumPy
[NumPy](https://numpy.org/) is a Python library providing support for multi-dimensional arrays, along with a large collection of mathematical functions to operate on these arrays.
It is the fundamental package for scientific computing in Python.
```
# Import the NumPy package under the alias "np"
import numpy as np
x = np.array([1, 4, 2, 5, 3])
print(x[:2])
print(x[2:])
print(np.sort(x))
```
### pandas
[pandas](https://pandas.pydata.org/) is a Python library providing high-performance, easy-to-use data structures and data analysis tools.
The primary data structures in **pandas** are implemented as two classes:
- **DataFrame**, which you can imagine as a relational data table, with rows and named columns.
- **Series**, which is a single column. A DataFrame contains one or more Series and a name for each Series.
The DataFrame is a commonly used abstraction for data manipulation.
```
import pandas as pd
# Create a DataFrame object contraining two Series
pop = pd.Series({"CAL": 38332521, "TEX": 26448193, "NY": 19651127})
area = pd.Series({"CAL": 423967, "TEX": 695662, "NY": 141297})
pd.DataFrame({"population": pop, "area": area})
```
### Matplotlib and Seaborn
[Matplotlib](https://matplotlib.org/) is a Python library for 2D plotting. [Seaborn](https://seaborn.pydata.org) is another visualization library that improves presentation of matplotlib-generated graphics.
```
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Setup plots (should be done on a separate cell for better results)
%matplotlib inline
plt.rcParams["figure.figsize"] = 10, 8
%config InlineBackend.figure_format = "retina"
sns.set()
# Plot a single function
x = np.linspace(0, 10, 30)
plt.plot(x, np.cos(x), label="cosinus")
plt.plot(x, np.sin(x), '-ok', label="sinus")
plt.legend()
plt.show()
```
### scikit-learn
[scikit-learn](https://scikit-learn.org) is a multi-purpose library built over Numpy and Matplotlib and providing dozens of built-in ML algorithms and models.
It is the Swiss army knife of Machine Learning.
Fun fact: scikit-learn was originally created by [INRIA](https://www.inria.fr).
### Keras
[Keras](https://keras.io/) is a high-level, user-friendly API for creating and training neural nets.
Once compatible with many back-end tools (Caffe, Theano, CNTK...), Keras is now the official high-level API of [TensorFlow](https://www.tensorflow.org/), Google's Machine Learning platform.
The [2.3.0 release](https://github.com/keras-team/keras/releases/tag/2.3.0) (Sept. 2019) was the last major release of multi-backend Keras.
See [this notebook](https://colab.research.google.com/drive/1UCJt8EYjlzCs1H1d1X0iDGYJsHKwu-NO) for a introduction to TF+Keras.
### PyTorch
[PyTorch](https://pytorch.org) is a Machine Learning platform supported by Facebook and competing with [TensorFlow](https://www.tensorflow.org/) for the hearts and minds of ML practitioners worldwide. It provides:
- a array manipulation API similar to NumPy;
- an autodifferentiation engine for computing gradients;
- a neural network API.
It is based on previous work, notably [Torch](http://torch.ch/) and [Chainer](https://chainer.org/).
| github_jupyter |
# Catboost Regression No. 2 (With GPU)
```
# Import the required libraries.
import pandas as pd
import numpy as np
# Read the train data.
data_train = pd.read_csv('train.csv')
# Read the first lines of the train data.
data_train.head()
# Print the shape of the train data.
data_train.shape
# Count the number of null values.
data_train.isnull().sum()
# Calculate the sum of the null values.
data_train.isnull().sum().sum()
# Show information about the train data.
data_train.describe()
# Show additional information about the train data.
data_train.info()
# Read the test data.
data_test = pd.read_csv('test.csv')
# Read the first lines of the test data.
data_test.head()
# Print the shape of the test data.
data_test.shape
# Count the number of null values.
data_test.isnull().sum()
# Calculate the sum of the null values.
data_test.isnull().sum().sum()
# Show information about the test data.
data_test.describe()
# Show additional information about the test data.
data_test.info()
# Data_train has an extra column, namely 'loss' column.
# This is the column which contains the target values.
# Let's look at it.
data_train.iloc[:, -1]
# For data visualization, import matplotlib and seaborn.
import matplotlib.pyplot as plt
import seaborn as sns
# Plot the 'loss' column.
plt.figure(figsize=(20, 12))
sns.distplot(data_train['loss'])
# Plot the 'loss' column logarithmic.
plt.figure(figsize=(20, 12))
sns.distplot(np.log(data_train['loss']))
# This is not a necessary step.
# Adding a column to data_train and attribute a 'true' value to it.
data_train['is_train'] = True
# This is not a necessary step.
# Adding a column to data_test and attribute a 'false' value to it.
data_test['is_train'] = False
# Read the first lines of the new train data.
data_train.head()
# Read the first lines of the new test data.
data_test.head()
# This is not a necessary step.
# Concat the two data sets into one data set.
data_train_test = pd.concat([data_train, data_test], axis=0)
# Read the first lines of the new data set.
data_train_test.head()
# Prepare the train data for regression using catboost.
# We need to execute some modification concerning column names.
# Let's look at the column names.
data_train.columns
# As it was shown, generally we have two type of column:
# 1) cat, that is an abbreviation of 'categorical',
# 2) cont, that is an abbreviation of 'continuous'.
# So the data set's values have two general types: categorical and continouos.
# In order to give our data to catboost algorithm, we should seperate them.
# Furthermore, we must only give the column indexes to this algorithm.
# Considering this goal, we should use 'Regular Experssion (re)' pattern matching.
import re
# Specify our pattern for categorical column names.
cat_pattern = re.compile("^cat([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$")
# Specify our pattern for continuous column names.
cont_pattern = re.compile("^cont([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$")
# Devide the categorical column names.
cat_column = [cat for cat in data_train.columns if 'cat' in cat]
# Print the categorical column names.
cat_column
# Although the categorical column names are sorted, we should force it to be sorted.
cat_column = sorted(cat_column, key=lambda s: int(s[3:]))
# Print the categorical column names.
cat_column
# list the index of the categorical column names using the regual expression pattern matching the we previously compiled.
cat_index = [i for i in range(0, len(data_train.columns)) if cat_pattern.match(data_train.columns[i])]
cat_index
# Devide the continuous column names.
cont_column = [cont for cont in data_train.columns if 'cont' in cont]
# Print the continuous column names.
cont_column
# Although the continuous column names are sorted, we should force it to be sorted.
cont_column = sorted(cont_column, key=lambda s: int(s[4:]))
# Print the continuous column names.
cont_column
# list the index of the continuous column names using the regual expression pattern matching the we previously compiled.
cont_index = [i for i in range(0, len(data_train.columns)) if cont_pattern.match(data_train.columns[i])]
cont_index
# Prepare train and test datasets.
# In order to do that, we can use a specific package in Sci-Kit library.
from sklearn.model_selection import train_test_split
# Specify the inputs (X) and the target (y).
# The input data is the data set whithout these specific columns: 'id', 'loss', 'isTrain'.
# the target data is the logarithm of the 'loss' column.
X = data_train.drop(['id', 'loss', 'is_train'], axis=1)
y = np.log(data_train['loss'])
# Specify the train and test inputs and targets.
# Note that we specify the random state.
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=25)
# Use catboost algorithm for regression.
from catboost import CatBoostRegressor
# Create a new catboost.
catboost_regressor_gpu = CatBoostRegressor(iterations=200, learning_rate=0.05, depth=6, eval_metric='MAE', verbose=10, task_type='GPU', save_snapshot=True, snapshot_file='faraz', snapshot_interval=10)
# For sake of the RAM capacity, we should delete the unncessary data sets from RAM.
del X
del y
del data_train
del data_test
del data_train_test
# Learn from the data.
# Specify the categorical columns with the following command:
# np.asarray(cat_index) - 1.
# In addition, we declare the test data with setting the 'eval_set' parameter.
catboost_regressor_gpu.fit(X_train, y_train, np.asarray(cat_index) - 1, eval_set=(X_test, y_test))
# For further usage and reducing RAM occupation, Save the medel into the Hard Disk.
# In order to achive this goal, use 'pickle'.
import pickle
# Use'Write Byte (wr)'' mode.
# First open a file named catboost_regression,
# Then pickle dumps the model, i.e. catboost_regressor, into it.
with open('catboost_regression_gpu', 'wb') as file:
pickle.dump(catboost_regressor_gpu, file)
```
| github_jupyter |
# **Python Basics**
**Values**
* A value is the fundamental thing that a program manipulates
* Values can be ‘Hello Python’, 1 , True
Values have types.
# **Variable**
1. One of the most basic and powerful concepts is
that of a variable.
2. A variable assigns a name to a value.
Variables are nothing more than reserved memory locations that store values.
3. Python variables does not need explicit declaration to reserve memory.
4.Unlike C/C++ and Java, variables can change types
```
message = 'Hello Python!'
n = 10
e = 2.71
print(message)
print(message, 'n==', n, 'e==', e)
```
# **Modules**
1. module is a file containing Python definitions and statements
2. not all functionality available comes automatically when starting Python
1. extra functionality can be added by importing modules
1. objects in the module can be accessed by prefixing them with the module name
```
import math
math.pow(2, 3)
import random
random.randint(1, 100)
from pathlib import Path
```
Comments Start with a `#`
```
# This is a comment
```
**Putting All things together**
---
Now we will write a program to calculate Simple Intrest
```
rate = 10
principle = 1000
time = 3
intrest = (rate * principle * time)/100
print('Intrest is ', intrest)
```
# **Data Types**
### 1. Numeric Types
* Integer Types: 92, 12, 0, 1
* Floats (Floating point numbers): 3.1415
* Complex Numbers: a + b*i (composed of real and imaginary component, both of which are floats a + b*i)
* Booleans: True/False are a subtype of integers (0 is false, 1 is true)
2. Strings
* ‘Hello Python’
* 'India'
3. Sequence types:
* Lists : [1,2,3,4,5]
* Tuples: (1, 2)
* Ranges:
# **Indentation**
1. In Python, blocks of code are defined using indentation
1. The indentation within the block needs to be consistent
1. The first line with less indentation is outside of the block
1. The first line with more indentation starts a nested block
1. Often a colon appears at the start of a new block
```
x = 9
if x<10:
print('x is less than 10')
print('Hello')
print('Outside the If')
```
# **Strings**
* Strings are text values like ‘Hello Anaconda’
* Strings can be enclosed in single quote ‘ ..’ or double quotes “…”
```
'spam eggs'
'doesn\'t' # use \' to escape the single quote...
"doesn't" # ...or use double quotes instead
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
3 * 'un' + 'ium'
```
Strings can be *indexed* (subscripted), with the first character having index 0.
```
word = 'Python'
word[0]
word[5]
```
indices may also be negative numbers, to start counting from the right.
```
word[-1] # last character
word[-2] # second-last character
```
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:
```
word[0:2] # characters from position 0 (included) to 2 (excluded)
word[2:5] # characters from position 2 (included) to 5 (excluded)
text = 'Put several strings within parentheses '+\
'to have them joined together.'
text
```
# **Lists**
1. ordered sequence of information, accessible by index
1. a list is denoted by square brackets, [ ]
1. a list contains usually homogenous elements
1. list elements can be changed so a list is mutable
```
squares = [1, 4, 9, 16, 25]
squares
squares[0]
squares[-1]
squares[-3:]
squares + [36, 49, 64, 81, 100]
cubes = [1, 8, 27, 65, 125]
cubes
```
Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content
```
cubes[3] = 64
cubes
```
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely
```
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[2:5] = ['C', 'D', 'E']
letters
letters[:] = []
letters
```
# **Tuple**
1. tuple consists of a number of values separated by commas
1. cannot change element values, immutable
1. tuples always enclosed in parenthesis
1. used to return more than one value from a function
```
t = 12345, 54321, 'hello!'
t[0]
u = t, (1, 2, 3, 4, 5) # Tuples may be nested:
u
t[0] = 88888 # Tuples are immutable:
x, y, z = t
print(x)
print(y)
print(z)
```
# **Sets**
1. A set is an unordered collection with no duplicate elements
1. set objects also support mathematical operations like union, intersection, difference, and symmetric difference
```
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)# show that duplicates have been removed
'orange' in basket # fast membership testing
'crabgrass' in basket
a = set('abracadabra')
b = set('alacazam')
a - b
```
# **Dictionary**
1. dictionary is a set of key:value pairs
1. dictionaries are indexed by keys, which can be any immutable type
1. dictionary stores a value with some key and extracts the value given the key
```
telephone = {'jack': 4098, 'sape': 4139,'alpha':1099,'beta':1000}
telephone
telephone['jack']
telephone['king'] = 4127
telephone
del telephone['sape']
'king' in telephone
```
# **Control flow**
Control flow is the concept of changing this order of code execution. Similar to the way you might use sale prices to decide which which car to buy or seeing the colour of signal decide to start or stop.
```
traffic_light = 'green'
if traffic_light == 'green':
print('Light is Green')
print('Go Ahead ')
else:
print('Light is Not Green')
print(' Stop ')
traffic_light = 'red'
if traffic_light == 'green':
print('Light is Green')
elif traffic_light=='yellow':
print('Light is Yellow')
elif traffic_light=='red':
print('Light is Red')
else:
print('Unknown Traffic Light')
```
# **While Loop**
A while statement executes a block of code as long as a condition is `True`.This continues until the condition is `False`.
```
n = 0
while n<10:
print('Value of n is',n)
n=n+1
```
# **For statements**
Python’s for statement iterates over the items of any sequence.
```
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w,len(w))
```
### To iterate over a sequence of numbers, the built-in function range() comes in handy.
```
for i in range(5):
print(i,end=',')
for i in range(5,10):
print(i,end=',')
for i in range(5,10,2):
print(i,end=',')
```
# **break and continue Statements**
1. break statement breaks out of innermost enclosing for or while loop.
1. continue statement continues with the next iteration of the loop skipping remaining statements.
```
for i in range(5):
if i==4:
break
print(i)
for i in range(5):
if i==2:
continue
print(i)
```
# **Write and call/invoke a function**
If its find that the same bits of code is reused over and over, you can create your own function and call that instead of repeating the same code.
```
def check_odd_even(i):
if i%2==0:
print(i,'is even number')
else:
print(i,'is odd number')
check_odd_even(10)
check_odd_even(11)
```
# **Default Value Argument**
```
def calc_intrest(principal,rates=5,duration=5):
intrest=(principal*rates*duration)/100
amount=intrest+principal
print('Principal Amount=',principal)
print('Rate=',rates)
print('Duration=',duration)
print('Total Amount=',amount)
calc_intrest(10)
calc_intrest(10,rates=10)
calc_intrest(10,rates=10,duration=20)
```
# Reading File
```
f = open('workfile.txt','r')
lines=f.read() # Entire file is read
print(lines)
f.close()
f = open('workfile.txt','r')
for line in f:
print(line,end='')
f.close()
with open('workfile.txt','r')as f:
for line in f:
print(line,end='')
```
# Writing to file
```
value = ('the answer is ', 42)
with open('workfile2.txt','w') as f:
s=str(value)
f.write(s)
```
| github_jupyter |
```
#coding:utf-8
import sys
import numpy as np
sys.path.append("..")
import argparse
from train_models.mtcnn_model import P_Net, R_Net, O_Net
from prepare_data.loader import TestLoader
from Detection.detector import Detector
from Detection.fcn_detector import FcnDetector
from Detection.MtcnnDetector import MtcnnDetector
import cv2
import os
data_dir = '../../DATA/WIDER_val/images'
anno_file = 'wider_face_val.txt'
def read_gt_bbox(raw_list):
list_len = len(raw_list)
bbox_num = (list_len-1)//4
idx = 1
bboxes = np.zeros((bbox_num,4),dtype=int)
for i in range(4):
for j in range(bbox_num):
bboxes[j][i] = int(raw_list[idx])
idx += 1
return bboxes
def get_image_info(anno_file):
f = open(anno_file,'r')
image_info = []
for line in f:
ct_list = line.strip().split(' ')
path = ct_list[0]
path_list = path.split('\\')
event = path_list[0]
name = path_list [1]
#print(event, name )
bboxes = read_gt_bbox(ct_list)
image_info.append([event,name,bboxes])
print('total number of images in validation set: ', len(image_info))
return image_info
test_mode = "ONet"
thresh = [0.6,0.5,0.4]
min_face_size = 24
stride = 2
slide_window = False
shuffle = False
vis = False
detectors = [None, None, None]
prefix = ['../data/MTCNN_model/PNet_landmark/PNet', '../data/MTCNN_model/RNet_landmark/RNet', '../data/MTCNN_model/ONet_landmark/ONet']
epoch = [18, 14, 16]
batch_size = [2048, 256, 16]
model_path = ['%s-%s' % (x, y) for x, y in zip(prefix, epoch)]
if slide_window:
PNet = Detector(P_Net, 12, batch_size[0], model_path[0])
else:
PNet = FcnDetector(P_Net, model_path[0])
detectors[0] = PNet
# load rnet model
if test_mode in ["RNet", "ONet"]:
RNet = Detector(R_Net, 24, batch_size[1], model_path[1])
detectors[1] = RNet
# load onet model
if test_mode == "ONet":
ONet = Detector(O_Net, 48, batch_size[2], model_path[2])
detectors[2] = ONet
mtcnn_detector = MtcnnDetector(detectors=detectors, min_face_size=min_face_size,
stride=stride, threshold=thresh, slide_window=slide_window)
image_info = get_image_info(anno_file)
str1='aaa'
str2 = 'bbb'
str3 = 'aaa'
print(str1 != str2)
print (str1 == str3)
a ='asdfasdf.jpg'
a.split('.jpg')
current_event = ''
save_path = ''
for item in image_info:
image_file_name = os.path.join(data_dir,item[0],item[1])
if current_event != item[0]:
current_event = item[0]
save_path = os.path.join('../../DATA',item[0])
if not os.path.exists(save_path):
os.mkdir(save_path)
f_name= item[1].split('.jpg')[0]
dets_file_name = os.path.join(save_path,f_name + '.txt')
img = cv2.imread(image_file_name)
all_boxes,_ = mtcnn_detector.detect_single_image(img)
```
| github_jupyter |
# Coronagraph Basics
This set of exercises guides the user through a step-by-step process of simulating NIRCam coronagraphic observations of the HR 8799 exoplanetary system. The goal is to familiarize the user with basic `pynrc` classes and functions relevant to coronagraphy.
```
# If running Python 2.x, makes print and division act like Python 3
from __future__ import print_function, division
# Import the usual libraries
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# Enable inline plotting at lower left
%matplotlib inline
from IPython.display import display, Latex, clear_output
```
We will start by first importing `pynrc` along with the `obs_hci` (High Contrast Imaging) class, which lives in the `pynrc.obs_nircam` module.
```
import pynrc
from pynrc import nrc_utils # Variety of useful functions and classes
from pynrc.obs_nircam import obs_hci # High-contrast imaging observation class
# Disable informational messages and only include warnings and higher
pynrc.setup_logging(level='WARN')
```
## Source Definitions
The `obs_hci` class first requires two arguments describing the spectra of the science and reference sources (`sp_sci` and `sp_ref`, respectively. Each argument should be a Pysynphot spectrum already normalized to some known flux. `pynrc` includes built-in functions for generating spectra. The user may use either of these or should feel free to supply their own as long as it meets the requirements.
1. The `pynrc.stellar_spectrum` function provides the simplest way to define a new spectrum:
```python
bp_k = pynrc.bp_2mass('k') # Define bandpass to normalize spectrum
sp_sci = pynrc.stellar_spectrum('F0V', 5.24, 'vegamag', bp_k)
```
You can also be more specific about the stellar properties with `Teff`, `metallicity`, and `log_g` keywords.
```python
sp_sci = pynrc.stellar_spectrum('F0V', 5.24, 'vegamag', bp_k,
Teff=7430, metallicity=-0.47, log_g=4.35)
```
2. Alternatively, the `pynrc.source_spectrum` class ingests spectral information of a given target and generates a model fit to the known photometric SED. Two model routines can be fit. The first is a very simple scale factor that is applied to the input spectrum, while the second takes the input spectrum and adds an IR excess modeled as a modified blackbody function. The user can find the relevant photometric data at http://vizier.u-strasbg.fr/vizier/sed/ and click download data as a VOTable.
```
# Define 2MASS Ks bandpass and source information
bp_k = pynrc.bp_2mass('k')
# Science source, dist, age, sptype, Teff, [Fe/H], log_g, mag, band
args_sources = [('HR 8799', 39.0, 30, 'F0V', 7430, -0.47, 4.35, 5.24, bp_k)]
# References source, sptype, Teff, [Fe/H], log_g, mag, band
ref_sources = [('HD 220657', 'F8III', 5888, -0.01, 3.22, 3.04, bp_k)]
name_sci, dist_sci, age, spt_sci, Teff_sci, feh_sci, logg_sci, mag_sci, bp_sci = args_sources[0]
name_ref, spt_ref, Teff_ref, feh_ref, logg_ref, mag_ref, bp_ref = ref_sources[0]
# For the purposes of simplicity, we will use pynrc.stellar_spectrum()
sp_sci = pynrc.stellar_spectrum(spt_sci, mag_sci, 'vegamag', bp_sci,
Teff=Teff_sci, metallicity=feh_sci, log_g=logg_sci)
sp_sci.name = name_sci
# And the refernece source
sp_ref = pynrc.stellar_spectrum(spt_ref, mag_ref, 'vegamag', bp_ref,
Teff=Teff_ref, metallicity=feh_ref, log_g=logg_ref)
sp_ref.name = name_ref
# Plot the two spectra
fig, ax = plt.subplots(1,1, figsize=(8,5))
xr = [2.5,5.5]
for sp in [sp_sci, sp_ref]:
w = sp.wave / 1e4
ind = (w>=xr[0]) & (w<=xr[1])
sp.convert('Jy')
f = sp.flux / np.interp(4.0, w, sp.flux)
ax.semilogy(w[ind], f[ind], lw=1.5, label=sp.name)
ax.set_ylabel('Flux (Jy) normalized at 4 $\mu m$')
sp.convert('flam')
ax.set_xlim(xr)
ax.set_xlabel(r'Wavelength ($\mu m$)')
ax.set_title('Spectral Sources')
# Overplot Filter Bandpass
bp = pynrc.read_filter('F444W', 'CIRCLYOT', 'MASK430R')
ax2 = ax.twinx()
ax2.plot(bp.wave/1e4, bp.throughput, color='C2', label=bp.name+' Bandpass')
ax2.set_ylim([0,0.8])
ax2.set_xlim(xr)
ax2.set_ylabel('Bandpass Throughput')
ax.legend(loc='upper left')
ax2.legend(loc='upper right')
fig.tight_layout()
```
## Initialize Observation
Now we will initialize the high-contrast imaging class `pynrc.obs_hci` using the spectral objects and various other settings. The `obs_hci` object is a subclass of the more generalized `NIRCam` class. It implements new settings and functions specific to high-contrast imaging observations for corongraphy and direct imaging.
For this tutorial, we want to observe these targets using the `MASK430R` coronagraph in the `F444W` filter. All circular coronagraphic masks such as the `430R` (R=round) should be paired with the `CIRCLYOT` pupil element, whereas wedge/bar masks are paired with `WEDGELYOT` pupil. Observations in the LW channel are most commonly observed in `WINDOW` mode with a 320x320 detector subarray size. Full detector sizes are also available.
The PSF simulation size (`fov_pix` keyword) should also be of similar size as the subarray window (recommend avoiding anything above `fov_pix=1024` due to computation time and memory usage). Use odd numbers to center the PSF in the middle of the pixel. If `fov_pix` is specified as even, then PSFs get centered at the corners. This distinction really only matter for unocculted observations, (ie., where the PSF flux is concentrated in a tight central core).
We also need to specify a WFE drift value (`wfe_ref_drift` parameter), which defines the anticipated drift in nm between the science and reference sources. For the moment, let's intialize with a value of 0nm. This prevents an initially long process by which `pynrc` calculates changes made to the PSF over a wide range of drift values.
Extended disk models can also be specified upon initialization using the `disk_hdu` keyword.
```
filt, mask, pupil = ('F444W', 'MASK430R', 'CIRCLYOT')
wind_mode, subsize = ('WINDOW', 320)
fov_pix, oversample = (320, 2)
wfe_ref_drift = 0
obs = pynrc.obs_hci(sp_sci, sp_ref, dist_sci, filter=filt, mask=mask, pupil=pupil,
wfe_ref_drift=wfe_ref_drift, fov_pix=fov_pix, oversample=oversample,
wind_mode=wind_mode, xpix=subsize, ypix=subsize, verbose=True)
```
All information for the reference observation is stored in the attribute `obs.nrc_ref`, which is simply it's own isolated `NIRCam` (`nrc_hci`) class. After initialization, any updates made to the primary `obs` instrument configuration (e.g., filters, detector size, etc.) must also be made inside the `obs.nrc_ref` class as well. That is to say, it does not automatically propogate. In many ways, it's best to think of these as two separate classes,
```python
obs_sci = obs
obs_ref = obs.nrc_ref
```
with some linked references between the two.
Now that we've succesffully initialized the obs_hci observations, let's specify the `wfe_ref_drift`. If this is your first time, then the `nrc_utils.wfed_coeff` function is called to determine a relationship between PSFs in the presense of WFE drift. This relationship is saved to disk in the `PYNRC_DATA` directory as a set of polynomial coefficients. Future calculations utilize these coefficients to quickly generate a new PSF for any arbitary drift value.
```
# WFE drift amount between rolls
# This only gets called during gen_roll_image()
# and temporarily updates obs.wfe_drift to create
# a new PSF.
obs.wfe_roll_drift = 2
# Drift amount between Roll 1 and reference
# This is simply a link to obs.nrc_ref.wfe_drift
obs.wfe_ref_drift = 10
```
## Exposure Settings
Optimization of exposure settings are demonstrated in another tutorial, so we will not repeat that process here. We can assume the optimization process was performed elsewhere to choose the `DEEP8` pattern with 16 groups and 5 total integrations. These settings apply to each roll position of the science observation as well as the for the reference observation.
```
# Update both the science and reference observations
obs.update_detectors(read_mode='DEEP8', ngroup=16, nint=5, verbose=True)
obs.nrc_ref.update_detectors(read_mode='DEEP8', ngroup=16, nint=5)
```
## Add Planets
There are four known giant planets orbiting HR 8799 at various locations. Ideally, we would like to position them at their predicted locations on the anticipated observation date. For this case, we choose a plausible observation date of November 1, 2019. To convert between $(x,y)$ and $(r,\theta)$, use the `nrc_utils.xy_to_rtheta` and `nrc_utils.rtheta_to_xy` functions.
When adding the planets, it doesn't matter too much which exoplanet model spectrum we decide to use since the spectra are still fairly unconstrained at these wavelengths. We do know roughly the planets' luminosities, so we can simply choose some reasonable model and renormalize it to the appropriate filter brightness. Currently, the only exoplanet spectral models available to `pynrc` are those from Spiegel & Burrows (2012).
```
# Projected locations for date 11/01/2019
# These are prelimary positions, but within constrained orbital parameters
loc_list = [(-1.57, 0.64), (0.42, 0.87), (0.5, -0.45), (0.35, 0.20)]
# Estimated magnitudes within F444W filter
pmags = [16.0, 15.0, 14.6, 14.7]
# Add planet information to observation class.
# These are stored in obs.planets.
# Can be cleared using obs.kill_planets().
obs.kill_planets()
for i, loc in enumerate(loc_list):
obs.add_planet(mass=10, entropy=13, age=age, xy=loc, runits='arcsec',
renorm_args=(pmags[i], 'vegamag', obs.bandpass))
# Generate and plot a noiseless slope image to make sure things look right
PA1 = 85
im_planets = obs.gen_planets_image(PA_offset=PA1)
from matplotlib.patches import Circle
from pynrc.nrc_utils import (coron_ap_locs, build_mask_detid, fshift, pad_or_cut_to_size)
fig, ax = plt.subplots(figsize=(6,6))
xasec = obs.det_info['xpix'] * obs.pix_scale
yasec = obs.det_info['ypix'] * obs.pix_scale
extent = [-xasec/2, xasec/2, -yasec/2, yasec/2]
xylim = 4
vmin = 0
vmax = 0.5*im_planets.max()
ax.imshow(im_planets, extent=extent, vmin=vmin, vmax=vmax)
# Overlay the coronagraphic mask
detid = obs.Detectors[0].detid
im_mask = obs.mask_images[detid]
# Do some masked transparency overlays
masked = np.ma.masked_where(im_mask>0.99, im_mask)
#ax.imshow(1-masked, extent=extent, alpha=0.5)
ax.imshow(1-masked, extent=extent, alpha=0.3, cmap='Greys_r', vmin=-0.5)
xc_off = obs.bar_offset
for loc in loc_list:
xc, yc = loc
xc, yc = nrc_utils.xy_rot(xc, yc, PA1)
xc += xc_off
circle = Circle((xc,yc), radius=xylim/15., alpha=0.7, lw=1, edgecolor='red', facecolor='none')
ax.add_artist(circle)
xlim = ylim = np.array([-1,1])*xylim
xlim = xlim + xc_off
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax.set_xlabel('Arcsec')
ax.set_ylabel('Arcsec')
ax.set_title('{} planets -- {} {}'.format(sp_sci.name, obs.filter, obs.mask))
color = 'grey'
ax.tick_params(axis='both', color=color, which='both')
for k in ax.spines.keys():
ax.spines[k].set_color(color)
nrc_utils.plotAxes(ax, width=1, headwidth=5, alength=0.15, angle=PA1,
position=(0.25,0.9), label1='E', label2='N')
fig.tight_layout()
```
As we can see, even with "perfect PSF subtraction" and no noise, it's difficult to make out planet e. This is primarily due to its location relative to the occulting mask reducing throughput along with confusion of bright diffraction spots from nearby sources.
## Estimated Performance
Now we are ready to determine contrast performance and sensitivites as a function of distance from the star.
### 1. Roll-Subtracted Images
First, we will create a quick simulated roll-subtracted image using the in `gen_roll_image` method. For the selected observation date of 11/1/2019, APT shows a PA range of 84$^{\circ}$ to 96$^{\circ}$. So, we'll assume Roll 1 has PA1=85, while Roll 2 has PA2=95. In this case, "roll subtraction" simply creates two science images observed at different parallactic angles, then subtracts the same reference observation from each. The two results are then de-rotated to a common PA=0 and averaged.
There is also the option to create ADI images, where the other roll position becomes the reference star by setting `no_ref=True`.
```
# Cycle through a few WFE drift values
wfe_list = [0,5,10]
# PA values for each roll
PA1, PA2 = (85, 95)
# A dictionary of HDULists
hdul_dict = {}
for i, wfe_drift in enumerate(wfe_list):
print(wfe_drift)
# Upate WFE reference drift value
obs.wfe_ref_drift = wfe_drift
# Set the final output image to be oversampled
hdulist = obs.gen_roll_image(PA1=PA1, PA2=PA2)
hdul_dict[wfe_drift] = hdulist
from pynrc.obs_nircam import plot_hdulist
from matplotlib.patches import Circle
fig, axes = plt.subplots(1,3, figsize=(14,4.3))
xylim = 2.5
xlim = ylim = np.array([-1,1])*xylim
for j, wfe_drift in enumerate(wfe_list):
ax = axes[j]
hdul = hdul_dict[wfe_drift]
plot_hdulist(hdul, xr=xlim, yr=ylim, ax=ax, vmin=0, vmax=8)
# Location of planet
for loc in loc_list:
circle = Circle(loc, radius=xylim/15., lw=1, edgecolor='red', facecolor='none')
ax.add_artist(circle)
ax.set_title('$\Delta$WFE = {:.0f} nm'.format(wfe_drift))
nrc_utils.plotAxes(ax, width=1, headwidth=5, alength=0.15, position=(0.9,0.7), label1='E', label2='N')
fig.suptitle('{} -- {} {}'.format(name_sci, obs.filter, obs.mask), fontsize=14)
fig.tight_layout()
fig.subplots_adjust(top=0.85)
```
**Note:** At first glance, it appears as if the innermost Planet e is getting brighter with increased WFE drift, which would be understandably confusing. However, upon further investigation, there just happens to be a bright residual speckle that lines up well with Planet e when observed at this specific parallactic angle. This was verified by adjusting the observed PA as well as removing the planets from the simulations.
### 2. Contrast Curves
Next, we will cycle through a few WFE drift values to get an idea of potential predicted sensitivity curves. The `calc_contrast` method returns a tuple of three arrays:
1. The radius in arcsec.
2. The n-sigma contrast.
3. The n-sigma magnitude sensitivity limit (vega mag).
```
# Cycle through varying levels of WFE drift and calculate contrasts
wfe_list = [0,5,10]
nsig = 5
# PA values for each roll
PA1, PA2 = (85, 95)
roll_angle = np.abs(PA2 - PA1)
curves = []
for i, wfe_drift in enumerate(wfe_list):
print(wfe_drift)
# Generate series of observations for each filter
obs.wfe_ref_drift = wfe_drift
# Generate contrast curves
result = obs.calc_contrast(roll_angle=roll_angle, nsig=nsig)
curves.append(result)
from pynrc.obs_nircam import plot_contrasts, plot_planet_patches, plot_contrasts_mjup
import matplotlib.patches as mpatches
# fig, ax = plt.subplots(figsize=(8,5))
fig, axes = plt.subplots(1,2, figsize=(14,4.5))
xr=[0,5]
yr=[24,8]
# 1a. Plot contrast curves and set x/y limits
ax = axes[0]
ax, ax2, ax3 = plot_contrasts(curves, nsig, wfe_list, obs=obs,
xr=xr, yr=yr, ax=ax, return_axes=True)
# 1b. Plot the locations of exoplanet companions
label = 'Companions ({})'.format(filt)
planet_dist = [np.sqrt(x**2+y**2) for x,y in loc_list]
ax.plot(planet_dist, pmags, marker='o', ls='None', label=label, color='k', zorder=10)
# 1c. Plot Spiegel & Burrows (2012) exoplanet fluxes (Hot Start)
plot_planet_patches(ax, obs, age=age, entropy=13, av_vals=None)
ax.legend(ncol=2)
# 2. Plot in terms of MJup using COND models
ax = axes[1]
plot_contrasts_mjup(curves, nsig, wfe_list, obs=obs, age=age,
ax=ax, twin_ax=True, xr=xr, yr=None)
ax.set_yscale('log')
ax.set_ylim([0.08,100])
ax.legend(loc='upper right', title='COND ({:.0f} Myr)'.format(age))
fig.suptitle('{} ({} + {})'.format(name_sci, obs.filter, obs.mask), fontsize=16)
fig.tight_layout()
fig.subplots_adjust(top=0.85, bottom=0.1 , left=0.05, right=0.97)
```
The innermost Planet e is right on the edge of the detection threshold as suggested by the simulated images.
### 3. Saturation Levels
Create an image showing level of saturation for each pixel. For NIRCam, saturation is important to track for purposes of accurate slope fits and persistence correction. In this case, we will plot the saturation levels both at `NGROUP=2` and `NGROUP=obs.det_info['ngroup']`. Saturation is defined at 80% well level, but can be modified using the `well_fill` keyword.
We want to perform this analysis for both science and reference targets.
```
# Saturation limits
ng_max = obs.det_info['ngroup']
sp_flat = pynrc.stellar_spectrum('flat')
print('NGROUP=2')
_ = obs.sat_limits(sp=sp_flat,ngroup=2,verbose=True)
print('')
print('NGROUP={}'.format(ng_max))
_ = obs.sat_limits(sp=sp_flat,ngroup=ng_max,verbose=True)
mag_sci = obs.star_flux('vegamag')
mag_ref = obs.star_flux('vegamag', sp=obs.sp_ref)
print('')
print('{} flux at {}: {:0.2f} mags'.format(obs.sp_sci.name, obs.filter, mag_sci))
print('{} flux at {}: {:0.2f} mags'.format(obs.sp_ref.name, obs.filter, mag_ref))
```
In this case, we don't expect HR 8799 to saturated. However, the reference source should have some saturated pixels before the end of an integration.
```
# Well level of each pixel for science source
sci_levels1 = obs.saturation_levels(ngroup=2)
sci_levels2 = obs.saturation_levels(ngroup=ng_max)
# Which pixels are saturated?
sci_mask1 = sci_levels1 > 0.8
sci_mask2 = sci_levels2 > 0.8
# Well level of each pixel for reference source
ref_levels1 = obs.saturation_levels(ngroup=2, do_ref=True)
ref_levels2 = obs.saturation_levels(ngroup=ng_max, do_ref=True)
# Which pixels are saturated?
ref_mask1 = ref_levels1 > 0.8
ref_mask2 = ref_levels2 > 0.8
# How many saturated pixels?
nsat1_sci = len(sci_levels1[sci_mask1])
nsat2_sci = len(sci_levels2[sci_mask2])
print(obs.sp_sci.name)
print('{} saturated pixel at NGROUP=2'.format(nsat1_sci))
print('{} saturated pixel at NGROUP={}'.format(nsat2_sci,ng_max))
# How many saturated pixels?
nsat1_ref = len(ref_levels1[ref_mask1])
nsat2_ref = len(ref_levels2[ref_mask2])
print('')
print(obs.sp_ref.name)
print('{} saturated pixel at NGROUP=2'.format(nsat1_ref))
print('{} saturated pixel at NGROUP={}'.format(nsat2_ref,ng_max))
# Saturation Mask for science target
nsat1, nsat2 = (nsat1_sci, nsat2_sci)
sat_mask1, sat_mask2 = (sci_mask1, sci_mask2)
sp = obs.sp_sci
nrc = obs
# Only display saturation masks if there are saturated pixels
if nsat2 > 0:
fig, axes = plt.subplots(1,2, figsize=(10,5))
xasec = nrc.det_info['xpix'] * nrc.pix_scale
yasec = nrc.det_info['ypix'] * nrc.pix_scale
extent = [-xasec/2, xasec/2, -yasec/2, yasec/2]
axes[0].imshow(sat_mask1, extent=extent)
axes[1].imshow(sat_mask2, extent=extent)
axes[0].set_title('{} Saturation (NGROUP=2)'.format(sp.name))
axes[1].set_title('{} Saturation (NGROUP={})'.format(sp.name,ng_max))
for ax in axes:
ax.set_xlabel('Arcsec')
ax.set_ylabel('Arcsec')
ax.tick_params(axis='both', color='white', which='both')
for k in ax.spines.keys():
ax.spines[k].set_color('white')
fig.tight_layout()
else:
print('No saturation detected.')
# Saturation Mask for reference
nsat1, nsat2 = (nsat1_ref, nsat2_ref)
sat_mask1, sat_mask2 = (ref_mask1, ref_mask2)
sp = obs.sp_ref
nrc = obs.nrc_ref
# Only display saturation masks if there are saturated pixels
if nsat2 > 0:
fig, axes = plt.subplots(1,2, figsize=(10,5))
xasec = nrc.det_info['xpix'] * nrc.pix_scale
yasec = nrc.det_info['ypix'] * nrc.pix_scale
extent = [-xasec/2, xasec/2, -yasec/2, yasec/2]
axes[0].imshow(sat_mask1, extent=extent)
axes[1].imshow(sat_mask2, extent=extent)
axes[0].set_title('{} Saturation (NGROUP=2)'.format(sp.name))
axes[1].set_title('{} Saturation (NGROUP={})'.format(sp.name,ng_max))
for ax in axes:
ax.set_xlabel('Arcsec')
ax.set_ylabel('Arcsec')
ax.tick_params(axis='both', color='white', which='both')
for k in ax.spines.keys():
ax.spines[k].set_color('white')
fig.tight_layout()
else:
print('No saturation detected.')
```
| github_jupyter |
```
# ignore this
%matplotlib inline
%load_ext music21.ipython21
```
# User's Guide, Chapter 15: Keys and KeySignatures
Music21 has two main objects for working with keys: the :class:`~music21.key.KeySignature` object, which handles the spelling of key signatures and the :class:`~music21.key.Key` object which does everything a KeySignature object does but also knows more advanced aspects of tonal harmony. We'll go through the basics of each one here.
We start, like always, by importing music21:
```
from music21 import *
```
Now let's get a couple of different key signatures, representing different numbers of sharps:
```
ks2 = key.KeySignature(2)
ks2.sharps
ks7 = key.KeySignature(7)
ks7
```
We can get a list of which pitches (as :class:`~music21.pitch.Pitch` objects) are altered by the key signature with the `.alteredPitches` property:
```
ks2.alteredPitches
```
There's also a method that lets us see what the accidental is for any given step:
```
ks2.accidentalByStep('C')
ks2.accidentalByStep('E') is None
```
Notice that we give a string of just a letter name from C-B. This won't work:
```
ks2.accidentalByStep('C#')
```
We can create key signatures with absurd numbers of sharps and get strange accidentals:
```
ks12 = key.KeySignature(12)
ks12.accidentalByStep('F')
```
These absurd key signatures display in some programs (such as Lilypond) and are exported into MusicXML but do not display in most MusicXML readers.
Key Signatures transpose like Pitches and Notes, taking each of the notes and moving it:
```
ks4 = ks2.transpose('M2')
ks4
```
And the number of sharps can be changed after the fact:
```
ks4.sharps = 0
ks4
```
We can get the Major or Minor scale corresponding to the Key Signature:
```
ks2.getScale('major')
ks2.getScale('minor')
```
We'll see what we can do with scales in a bit.
If we put a KeySignature into a Stream, we can see it:
```
m = stream.Measure()
m.insert(0, meter.TimeSignature('3/4'))
m.insert(0, ks2)
d = note.Note('D')
c = note.Note('C')
fis = note.Note('F#') # German name
m.append([d, c, fis])
m.show()
```
Note that the Note 'C' is treated as C-natural and thus needs the natural sign in front of it. The Note F# however does not need a natural sign to be displayed. The process of calling `.show()` on the stream made a copy of the notes and set the `.pitch.accidental.displayStatus` on the F# to `False` and created an accidental for the C note with a natural and a displayStatus of True. Then the copies were discarded, so we don't see them here:
```
fis.pitch.accidental.displayStatus
```
But we could instead call `.makeNotation(inPlace=True)` or `.makeAccidentals(inPlace=True)` on the Measure to do this manually:
```
m.makeAccidentals(inPlace=True)
fis.pitch.accidental.displayStatus
c.pitch.accidental, c.pitch.accidental.displayStatus
```
If we have a `Measure` (not just any `Stream`) we can also set the KeySignature for the beginning of the measure with the Measure object's `.keySignature` property:
```
m.keySignature = key.KeySignature(4)
m.show()
```
Of course life isn't all about sharps; it'd be a pretty terrible KeySignature object if we couldn't have flats. To do it, just specify the number of flats as a negative number. So -1 = one flat, -2 = two flats. Or if you have the number as a positive already, just multiply by -1.
```
eroicaFlats = 3
ksEroica = key.KeySignature(-1 * eroicaFlats)
ksEroica
ksEroica.sharps
```
There is no `.flats` routine:
```
ksEroica.flats
```
## Example: Adjusting notes to fit the Key Signature
Here's a nice study, suppose you had a score like this:
```
m1 = stream.Measure()
m1.timeSignature = meter.TimeSignature('2/4')
m1.keySignature = key.KeySignature(-5)
m1.append([note.Note('D'), note.Note('A')])
m2 = stream.Measure()
m2.append([note.Note('B-'), note.Note('G#')])
p = stream.Part()
p.append([m1, m2])
p.show()
```
Let's pretend that this was played by a young oboe player who was having trouble with the strange key signature. She got the B-flat right, and remembered to play some accidental on the G, but didn't do very well overall. Let's fix these notes so that they fit with the key signature.
Now we could simply do something like this for each note:
```
m1.notes[0].pitch.accidental = pitch.Accidental('flat')
```
But that wouldn't be as great as getting the notes from the Key itself. Let's do that with the accidentalByStep routine:
```
ks = m1.keySignature
for n in p.recurse().notes: # we need to recurse because the notes are in measures...
nStep = n.pitch.step
rightAccidental = ks.accidentalByStep(nStep)
n.pitch.accidental = rightAccidental
p.show()
```
Yep, now our student is ready to play the concert! Though wouldn't this be an easier key?
```
p.transpose(1).show()
```
## Key objects
A Key is a lot like a KeySignature, but much more powerful. Unlike a KeySignature, which we initialize with the number of sharps and flats, we initialize a Key with a tonic string or Pitch:
```
kD = key.Key('D')
kD
bFlat = pitch.Pitch('B-')
kBflat = key.Key(bFlat)
kBflat
```
By default, keys are major, but we can make minor keys by specifying 'minor' as the second argument:
```
kd = key.Key('D', 'minor')
kd
```
Note that the key is represented as lowercase ('d minor' as opposed to 'D minor'). This is a clue as to a shortcut for making minor keys:
```
kg = key.Key('g')
kg
```
We can also take KeySignatures and turn them into Keys by using the `asKey(mode)` method on them:
```
(ksEroica.asKey('major'), ksEroica.asKey('minor'))
```
(In the latter case we should probably have called the variable ksFifthSymphony...)
We can also make church modes:
```
amixy = key.Key('a', 'mixolydian')
amixy
```
If you've forgotten how many sharps or flats are in the key of A mixolydian, you'll be happy to know that all the properties and methods of KeySignatures are also available to Keys:
```
amixy.sharps
amixy.alteredPitches
amixy.transpose('M3')
aDarkKey = key.Key('B--', 'locrian')
aDarkKey.alteredPitches
```
(as a music historian and someone who specializes in history of music theory, I am contractually obliged to mention that "locrian" is not a historic mode and doesn't really exist in actual music before the 20th c. But it's fun to play with).
Keys know their `.mode`:
```
kg.mode, amixy.mode
```
They also know their tonic pitches:
```
kg.tonic, amixy.tonic
```
For major and minor keys, we can get the relative (minor or major) and parallel (minor or major) keys simply:
```
kg.relative
kg.parallel
```
And because two keys are equal if their modes and tonics are the same, this is true:
```
kg.relative.relative == kg
```
This is pretty helpful from time to time:
```
kg.tonicPitchNameWithCase
kg.parallel.tonicPitchNameWithCase
```
Some analysis routines produce keys:
```
bach = corpus.parse('bwv66.6')
bach.id = 'bach66'
bach.analyze('key')
```
The keys from these routines have two extra cool features. They have a certainty measure:
```
fis = bach.analyze('key')
fis.correlationCoefficient
fis.tonalCertainty()
```
Here are some of the other keys that the Bach piece could have been in:
```
fis.alternateInterpretations[0:4]
```
And the least likely:
```
fis.alternateInterpretations[-3:]
c = bach.measures(1, 4).chordify()
for ch in c.recurse().getElementsByClass('Chord'):
ch.closedPosition(inPlace=True, forceOctave=4)
c.show()
```
Yeah, that passes the smell test to me!
So, how does it know what the key is? The key analysis routines are a variation of the famous (well at least in the small world of computational music theory) algorithm developed by Carol Krumhansl and Mark A. Schmuckler called probe-tone key finding. The distribution of pitches used in the piece are compared to sample distributions of pitches for major and minor keys and the closest matches are reported. (see http://rnhart.net/articles/key-finding/ for more details). `Music21` can be asked to use the sample distributions of several authors, including Krumhansl and Schmuckler's original weights:
```
bach.analyze('key.krumhanslschmuckler')
```
Though the `key` returned by `.analyze('key')` and `.analyze('key.krumhanslschmuckler')` are the same, the correlationCoefficient is somewhat different. `fis` is the analysis from `.analyze('key')`.
```
fisNew = bach.analyze('key.krumhanslschmuckler')
fisCC = round(fis.correlationCoefficient, 3)
fisNewCC = round(fisNew.correlationCoefficient, 3)
(fisCC, fisNewCC)
```
Calling `.analyze()` on a Stream calls :func:`music21.analysis.discrete.analyzeStream` which then calls an appropriate Class there.
There is another way of looking at the key of a piece and that is looking at differently sized windows of analysis on the piece and seeing what happens every quarter note, every half note, every measure, every two measures, etc. to the top. This plot was created by Jared Sadoian and is explained in the `analysis.windowed` module:
```
bach.flatten().plot('pianoroll')
```
A Key object is derived from a KeySignature object and also a Scale object, which we will explain more about later.
```
k = key.Key('E-')
k.classes
```
But for now, a few methods that are present on scales that might end up being useful for Keys as well include:
```
k.pitchFromDegree(2)
```
(octaves in 4 and 5 are chosen just to give some ordering to the pitches)
```
k.solfeg('G')
```
## Key Context and Note Spelling
`Key` and `KeySignature` objects affect how notes are spelled in some situations. Let's set up a simple situation of a F-natural whole note in D major and then B-flat minor.
```
s = stream.Stream()
s.append(key.Key('D'))
s.append(note.Note('F', type='whole'))
s.append(key.Key('b-', 'minor'))
s.append(note.Note('F', type='whole'))
s2 = s.makeNotation()
s2.show()
```
When we transpose each note up a half step (`n.transpose(1)`), music21 understands that the first F-natural should become F-sharp, while the second one will fit better as a G-flat.
```
for n in s2.recurse().notes:
n.transpose(1, inPlace=True)
s2.show()
```
## Example: Prepare a vocal exercise in all major keys, ascending by step.
Let's create a simple exercise in playing or singing thirds. I think I remember this from the [First Division Band Method](https://www.google.com/search?q=First+Division+Band+Method&tbm=isch) "Blue Book":
```
pitchStream = stream.Part()
pitchStream.insert(0, meter.TimeSignature('4/4'))
for step in ('c', 'e', 'd', 'f', 'e', 'g', 'f', 'a',
'g', 'e', 'f', 'd', 'c', 'e', 'c'):
n = note.Note(step, type='eighth')
n.pitch.octave = 4
pitchStream.append(n)
pitchStream.notes[-1].duration.type = 'quarter'
pitchStream.makeMeasures(inPlace=True)
pitchStream.show()
```
This melody does not have a key associated with it. Let's put a Key of C Major at the beginning of the piece:
```
k = key.Key('C')
pitchStream.measure(1).insert(0, k)
pitchStream.show()
```
Note that putting the key of C into the Stream doesn't change what it looks like when we show the Stream, since there are no sharps or flats. But what makes the difference between an instrumental and a vocal exercise is the act of transposition. When we transpose the `Key` object up 1 semitone, to D-flat major, it will show up:
```
k.transpose(1, inPlace=True)
pitchStream.show()
```
Now the key signature is D-flat, but the notes are still in C-major, so we should transpose them also:
```
for n in pitchStream.recurse().notes:
n.transpose(1, inPlace=True)
pitchStream.show()
```
Notice that we choose a semitone transposition and not a diatonic transposition such as minor second (`"m2"`); minor second would work just as good in this case, but then to do another half-step up, we would need to remember to transpose by an augmented unison (`"A1"`) so that D-flat became D-natural and not E-double-flat. The semitone transposition is smart enough to make sure that the `Key` object remains between six-flats and six-sharps. Not only that, but the notes will match the best spelling for the current key signature.
```
k.transpose(1, inPlace=True)
for n in pitchStream.recurse().notes:
n.transpose(1, inPlace=True)
pitchStream.show()
k.transpose(1, inPlace=True)
for n in pitchStream.recurse().notes:
n.transpose(1, inPlace=True)
pitchStream.show()
```
So, we can make a nice, ascending vocal exercise by varying the transposition amount from 0 to 7 (or however high you can sing) and putting each of the two-measure excerpts together into one Part.
We will introduce the tinyNotation format here, which will be described in the next chapter:
```
out = stream.Part()
for i in range(0, 8):
pitchStream = converter.parse("tinyNotation: 4/4 c8 e d f e g f a g e f d c e c4")
if i != 0:
# remove redundant clefs and time signature
trebleClef = pitchStream.recurse().getElementsByClass('Clef')[0]
fourFour = pitchStream.recurse().getElementsByClass('TimeSignature')[0]
pitchStream.remove(trebleClef, recurse=True)
pitchStream.remove(fourFour, recurse=True)
if i % 2 == 0:
# add a line break at the beginning of every other line:
pitchStream.measure(1).insert(0, layout.SystemLayout(isNew=True))
k = key.Key('C')
pitchStream.measure(1).insert(0, k)
k.transpose(i, inPlace=True)
for n in pitchStream.recurse().notes:
n.transpose(i, inPlace=True)
for el in pitchStream:
out.append(el)
out.show()
```
And we can listen to it as well:
```
out.show('midi')
```
That's enough about keys for now, let's move on to a fast way of getting small amounts of music into music21, with :ref:`Chapter 16, Tiny Notation <usersGuide_16_tinyNotation>`
| github_jupyter |
CER002 - Download existing Root CA certificate
==============================================
Use this notebook to download a generated Root CA certificate from a
cluster that installed one using:
- [CER001 - Generate a Root CA
certificate](../cert-management/cer001-create-root-ca.ipynb)
And then to upload the generated Root CA to another cluster use:
- [CER003 - Upload existing Root CA
certificate](../cert-management/cer003-upload-existing-root-ca.ipynb)
If needed, use these notebooks to view and set the Kubernetes
configuration context appropriately to enable downloading the Root CA
from a Big Data Cluster in one Kubernetes cluster, and to upload it to a
Big Data Cluster in another Kubernetes cluster.
- [TSG010 - Get configuration
contexts](../monitor-k8s/tsg010-get-kubernetes-contexts.ipynb)
- [SOP011 - Set kubernetes configuration
context](../common/sop011-set-kubernetes-context.ipynb)
Steps
-----
### Parameters
```
local_folder_name = "mssql-cluster-root-ca"
test_cert_store_root = "/var/opt/secrets/test-certificates"
```
### Common functions
Define helper functions used in this notebook.
```
# Define `run` function for transient fault handling, suggestions on error, and scrolling updates on Windows
import sys
import os
import re
import json
import platform
import shlex
import shutil
import datetime
from subprocess import Popen, PIPE
from IPython.display import Markdown
retry_hints = {} # Output in stderr known to be transient, therefore automatically retry
error_hints = {} # Output in stderr where a known SOP/TSG exists which will be HINTed for further help
install_hint = {} # The SOP to help install the executable if it cannot be found
first_run = True
rules = None
debug_logging = False
def run(cmd, return_output=False, no_output=False, retry_count=0):
"""Run shell command, stream stdout, print stderr and optionally return output
NOTES:
1. Commands that need this kind of ' quoting on Windows e.g.:
kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='data-pool')].metadata.name}
Need to actually pass in as '"':
kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='"'data-pool'"')].metadata.name}
The ' quote approach, although correct when pasting into Windows cmd, will hang at the line:
`iter(p.stdout.readline, b'')`
The shlex.split call does the right thing for each platform, just use the '"' pattern for a '
"""
MAX_RETRIES = 5
output = ""
retry = False
global first_run
global rules
if first_run:
first_run = False
rules = load_rules()
# When running `azdata sql query` on Windows, replace any \n in """ strings, with " ", otherwise we see:
#
# ('HY090', '[HY090] [Microsoft][ODBC Driver Manager] Invalid string or buffer length (0) (SQLExecDirectW)')
#
if platform.system() == "Windows" and cmd.startswith("azdata sql query"):
cmd = cmd.replace("\n", " ")
# shlex.split is required on bash and for Windows paths with spaces
#
cmd_actual = shlex.split(cmd)
# Store this (i.e. kubectl, python etc.) to support binary context aware error_hints and retries
#
user_provided_exe_name = cmd_actual[0].lower()
# When running python, use the python in the ADS sandbox ({sys.executable})
#
if cmd.startswith("python "):
cmd_actual[0] = cmd_actual[0].replace("python", sys.executable)
# On Mac, when ADS is not launched from terminal, LC_ALL may not be set, which causes pip installs to fail
# with:
#
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 4969: ordinal not in range(128)
#
# Setting it to a default value of "en_US.UTF-8" enables pip install to complete
#
if platform.system() == "Darwin" and "LC_ALL" not in os.environ:
os.environ["LC_ALL"] = "en_US.UTF-8"
# When running `kubectl`, if AZDATA_OPENSHIFT is set, use `oc`
#
if cmd.startswith("kubectl ") and "AZDATA_OPENSHIFT" in os.environ:
cmd_actual[0] = cmd_actual[0].replace("kubectl", "oc")
# To aid supportabilty, determine which binary file will actually be executed on the machine
#
which_binary = None
# Special case for CURL on Windows. The version of CURL in Windows System32 does not work to
# get JWT tokens, it returns "(56) Failure when receiving data from the peer". If another instance
# of CURL exists on the machine use that one. (Unfortunately the curl.exe in System32 is almost
# always the first curl.exe in the path, and it can't be uninstalled from System32, so here we
# look for the 2nd installation of CURL in the path)
if platform.system() == "Windows" and cmd.startswith("curl "):
path = os.getenv('PATH')
for p in path.split(os.path.pathsep):
p = os.path.join(p, "curl.exe")
if os.path.exists(p) and os.access(p, os.X_OK):
if p.lower().find("system32") == -1:
cmd_actual[0] = p
which_binary = p
break
# Find the path based location (shutil.which) of the executable that will be run (and display it to aid supportability), this
# seems to be required for .msi installs of azdata.cmd/az.cmd. (otherwise Popen returns FileNotFound)
#
# NOTE: Bash needs cmd to be the list of the space separated values hence shlex.split.
#
if which_binary == None:
which_binary = shutil.which(cmd_actual[0])
if which_binary == None:
if user_provided_exe_name in install_hint and install_hint[user_provided_exe_name] is not None:
display(Markdown(f'HINT: Use [{install_hint[user_provided_exe_name][0]}]({install_hint[user_provided_exe_name][1]}) to resolve this issue.'))
raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)")
else:
cmd_actual[0] = which_binary
start_time = datetime.datetime.now().replace(microsecond=0)
print(f"START: {cmd} @ {start_time} ({datetime.datetime.utcnow().replace(microsecond=0)} UTC)")
print(f" using: {which_binary} ({platform.system()} {platform.release()} on {platform.machine()})")
print(f" cwd: {os.getcwd()}")
# Command-line tools such as CURL and AZDATA HDFS commands output
# scrolling progress bars, which causes Jupyter to hang forever, to
# workaround this, use no_output=True
#
# Work around a infinite hang when a notebook generates a non-zero return code, break out, and do not wait
#
wait = True
try:
if no_output:
p = Popen(cmd_actual)
else:
p = Popen(cmd_actual, stdout=PIPE, stderr=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
line = line.decode()
if return_output:
output = output + line
else:
if cmd.startswith("azdata notebook run"): # Hyperlink the .ipynb file
regex = re.compile(' "(.*)"\: "(.*)"')
match = regex.match(line)
if match:
if match.group(1).find("HTML") != -1:
display(Markdown(f' - "{match.group(1)}": "{match.group(2)}"'))
else:
display(Markdown(f' - "{match.group(1)}": "[{match.group(2)}]({match.group(2)})"'))
wait = False
break # otherwise infinite hang, have not worked out why yet.
else:
print(line, end='')
if rules is not None:
apply_expert_rules(line)
if wait:
p.wait()
except FileNotFoundError as e:
if install_hint is not None:
display(Markdown(f'HINT: Use {install_hint} to resolve this issue.'))
raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)") from e
exit_code_workaround = 0 # WORKAROUND: azdata hangs on exception from notebook on p.wait()
if not no_output:
for line in iter(p.stderr.readline, b''):
try:
line_decoded = line.decode()
except UnicodeDecodeError:
# NOTE: Sometimes we get characters back that cannot be decoded(), e.g.
#
# \xa0
#
# For example see this in the response from `az group create`:
#
# ERROR: Get Token request returned http error: 400 and server
# response: {"error":"invalid_grant",# "error_description":"AADSTS700082:
# The refresh token has expired due to inactivity.\xa0The token was
# issued on 2018-10-25T23:35:11.9832872Z
#
# which generates the exception:
#
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 179: invalid start byte
#
print("WARNING: Unable to decode stderr line, printing raw bytes:")
print(line)
line_decoded = ""
pass
else:
# azdata emits a single empty line to stderr when doing an hdfs cp, don't
# print this empty "ERR:" as it confuses.
#
if line_decoded == "":
continue
print(f"STDERR: {line_decoded}", end='')
if line_decoded.startswith("An exception has occurred") or line_decoded.startswith("ERROR: An error occurred while executing the following cell"):
exit_code_workaround = 1
# inject HINTs to next TSG/SOP based on output in stderr
#
if user_provided_exe_name in error_hints:
for error_hint in error_hints[user_provided_exe_name]:
if line_decoded.find(error_hint[0]) != -1:
display(Markdown(f'HINT: Use [{error_hint[1]}]({error_hint[2]}) to resolve this issue.'))
# apply expert rules (to run follow-on notebooks), based on output
#
if rules is not None:
apply_expert_rules(line_decoded)
# Verify if a transient error, if so automatically retry (recursive)
#
if user_provided_exe_name in retry_hints:
for retry_hint in retry_hints[user_provided_exe_name]:
if line_decoded.find(retry_hint) != -1:
if retry_count < MAX_RETRIES:
print(f"RETRY: {retry_count} (due to: {retry_hint})")
retry_count = retry_count + 1
output = run(cmd, return_output=return_output, retry_count=retry_count)
if return_output:
return output
else:
return
elapsed = datetime.datetime.now().replace(microsecond=0) - start_time
# WORKAROUND: We avoid infinite hang above in the `azdata notebook run` failure case, by inferring success (from stdout output), so
# don't wait here, if success known above
#
if wait:
if p.returncode != 0:
raise SystemExit(f'Shell command:\n\n\t{cmd} ({elapsed}s elapsed)\n\nreturned non-zero exit code: {str(p.returncode)}.\n')
else:
if exit_code_workaround !=0 :
raise SystemExit(f'Shell command:\n\n\t{cmd} ({elapsed}s elapsed)\n\nreturned non-zero exit code: {str(exit_code_workaround)}.\n')
print(f'\nSUCCESS: {elapsed}s elapsed.\n')
if return_output:
return output
def load_json(filename):
"""Load a json file from disk and return the contents"""
with open(filename, encoding="utf8") as json_file:
return json.load(json_file)
def load_rules():
"""Load any 'expert rules' from the metadata of this notebook (.ipynb) that should be applied to the stderr of the running executable"""
# Load this notebook as json to get access to the expert rules in the notebook metadata.
#
try:
j = load_json("cer002-download-existing-root-ca.ipynb")
except:
pass # If the user has renamed the book, we can't load ourself. NOTE: Is there a way in Jupyter, to know your own filename?
else:
if "metadata" in j and \
"azdata" in j["metadata"] and \
"expert" in j["metadata"]["azdata"] and \
"expanded_rules" in j["metadata"]["azdata"]["expert"]:
rules = j["metadata"]["azdata"]["expert"]["expanded_rules"]
rules.sort() # Sort rules, so they run in priority order (the [0] element). Lowest value first.
# print (f"EXPERT: There are {len(rules)} rules to evaluate.")
return rules
def apply_expert_rules(line):
"""Determine if the stderr line passed in, matches the regular expressions for any of the 'expert rules', if so
inject a 'HINT' to the follow-on SOP/TSG to run"""
global rules
for rule in rules:
notebook = rule[1]
cell_type = rule[2]
output_type = rule[3] # i.e. stream or error
output_type_name = rule[4] # i.e. ename or name
output_type_value = rule[5] # i.e. SystemExit or stdout
details_name = rule[6] # i.e. evalue or text
expression = rule[7].replace("\\*", "*") # Something escaped *, and put a \ in front of it!
if debug_logging:
print(f"EXPERT: If rule '{expression}' satisfied', run '{notebook}'.")
if re.match(expression, line, re.DOTALL):
if debug_logging:
print("EXPERT: MATCH: name = value: '{0}' = '{1}' matched expression '{2}', therefore HINT '{4}'".format(output_type_name, output_type_value, expression, notebook))
match_found = True
display(Markdown(f'HINT: Use [{notebook}]({notebook}) to resolve this issue.'))
print('Common functions defined successfully.')
# Hints for binary (transient fault) retry, (known) error and install guide
#
retry_hints = {'kubectl': ['A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond']}
error_hints = {'kubectl': [['no such host', 'TSG010 - Get configuration contexts', '../monitor-k8s/tsg010-get-kubernetes-contexts.ipynb'], ['No connection could be made because the target machine actively refused it', 'TSG056 - Kubectl fails with No connection could be made because the target machine actively refused it', '../repair/tsg056-kubectl-no-connection-could-be-made.ipynb']]}
install_hint = {'kubectl': ['SOP036 - Install kubectl command line interface', '../install/sop036-install-kubectl.ipynb']}
```
### Get the Kubernetes namespace for the big data cluster
Get the namespace of the Big Data Cluster use the kubectl command line
interface .
**NOTE:**
If there is more than one Big Data Cluster in the target Kubernetes
cluster, then either:
- set \[0\] to the correct value for the big data cluster.
- set the environment variable AZDATA\_NAMESPACE, before starting
Azure Data Studio.
```
# Place Kubernetes namespace name for BDC into 'namespace' variable
if "AZDATA_NAMESPACE" in os.environ:
namespace = os.environ["AZDATA_NAMESPACE"]
else:
try:
namespace = run(f'kubectl get namespace --selector=MSSQL_CLUSTER -o jsonpath={{.items[0].metadata.name}}', return_output=True)
except:
from IPython.display import Markdown
print(f"ERROR: Unable to find a Kubernetes namespace with label 'MSSQL_CLUSTER'. SQL Server Big Data Cluster Kubernetes namespaces contain the label 'MSSQL_CLUSTER'.")
display(Markdown(f'HINT: Use [TSG081 - Get namespaces (Kubernetes)](../monitor-k8s/tsg081-get-kubernetes-namespaces.ipynb) to resolve this issue.'))
display(Markdown(f'HINT: Use [TSG010 - Get configuration contexts](../monitor-k8s/tsg010-get-kubernetes-contexts.ipynb) to resolve this issue.'))
display(Markdown(f'HINT: Use [SOP011 - Set kubernetes configuration context](../common/sop011-set-kubernetes-context.ipynb) to resolve this issue.'))
raise
print(f'The SQL Server Big Data Cluster Kubernetes namespace is: {namespace}')
```
### Get name of the ‘Running’ `controller` `pod`
```
# Place the name of the 'Running' controller pod in variable `controller`
controller = run(f'kubectl get pod --selector=app=controller -n {namespace} -o jsonpath={{.items[0].metadata.name}} --field-selector=status.phase=Running', return_output=True)
print(f"Controller pod name: {controller}")
```
### Create a temporary folder to hold Root CA certificate
```
import os
import tempfile
import shutil
path = os.path.join(tempfile.gettempdir(), local_folder_name)
if os.path.isdir(path):
shutil.rmtree(path)
os.mkdir(path)
```
### Copy Root CA certificate from `controller` `pod`
```
import os
cwd = os.getcwd()
os.chdir(path) # Workaround kubectl bug on Windows, can't put c:\ on kubectl cp cmd line
run(f'kubectl cp {controller}:{test_cert_store_root}/cacert.pem cacert.pem -c controller -n {namespace}')
run(f'kubectl cp {controller}:{test_cert_store_root}/cakey.pem cakey.pem -c controller -n {namespace}')
os.chdir(cwd)
print('Notebook execution complete.')
```
Related
-------
- [CER001 - Generate a Root CA
certificate](../cert-management/cer001-create-root-ca.ipynb)
- [CER003 - Upload existing Root CA
certificate](../cert-management/cer003-upload-existing-root-ca.ipynb)
- [CER010 - Install generated Root CA
locally](../cert-management/cer010-install-generated-root-ca-locally.ipynb)
| github_jupyter |
# Import used modules
```
import pandas as pd
import sys
sys.path.insert(0, '../src')
import benchmark_utils as bu
import analysis_utils as au
```
# Run Alignments for OpenCADD.superposition for the CAMK and CMGC Structures
Perform all pairwise alignments for the given sample structures. Every method performs 2500 alignments for the 50 CAMK and 50 CMGC structures. The benchmark is done with an Intel Core i5-1038NG7 CPU and 16 GB of RAM.
```
#bu.run_alignments(sample1_path="../data/samples/CAMK_samples.txt",
# sample2_path="../data/samples/CMGC_samples.txt",
# output_path="../data/OpenCADD_results/<NAME_OF_FILE>")
```
# Create a Dataframe containing the Alignments of all five Methods
The alignments for PyMol and ChimeraX MatchMaker are done in the respectively programs and are saved in seperate files. For the analysis, the DataFrames are combined.
```
columns = ["reference_id", "mobile_id", "method", "rmsd",
"coverage", "reference_size", "mobile_size", "time",
"SI", "MI", "SAS", "ref_name", "ref_group", "ref_species",
"ref_chain", "mob_name", "mob_group", "mob_species", "mob_chain"]
superposer_CAMK_CMGC = pd.read_csv("../data/OpenCADD_results/superposer_benchmark_CAMK_CMGC.csv", names=columns)
pymol_CAMK_CMGC = pd.read_csv("../data/PyMol_results/pymol_benchmark_CAMK_CMGC.csv", names=columns)
chimerax_CAMK_CMGC = pd.read_csv("../data/ChimeraX_results/mmaker_benchmark_CAMK_CMGC.csv", names=columns)
all_CAMK_CMGC = pd.concat([superposer_CAMK_CMGC, pymol_CAMK_CMGC, chimerax_CAMK_CMGC]).reset_index(drop=True)
```
### Compute the relative Coverage
The relative coverage is computed the following way:
coverage / min(lenght of structure 1, lenght of structure 2)
```
au.compute_rel_cov(all_CAMK_CMGC)
```
# Analysis
## General Checks
```
counts, nans, times = au.general_checks(all_CAMK_CMGC)
```
Check if every value is present.
It should be 2500 for every value, because there are 2500 alignments performed per method.
```
counts
```
Next, we check for missing alignments. Some Methods have problems with some structures.
In this case, 1 alignment is missing for Theseus and 50 for MMLigner. All missing alignments for MMLigner are with the structure 4fv3 of ERK2.
The entries with missing alignments are removed for further analysis.
```
nans
all_CAMK_CMGC[all_CAMK_CMGC["rmsd"].isna()]
all_CAMK_CMGC = all_CAMK_CMGC.dropna()
```
During the computation of the alignments, the time is measured. For all OpenCADD methods combined the CPU-time is about 11.5 hours. The time for downloading the structures is not included.
PyMol align took less than a minute.
```
times
```
### Compute Mean and Median
```
mean, median = au.compute_mean_median(all_CAMK_CMGC)
mean
median
```
## Create basic plots
It is easy to see in both plots, that MMLigner performs the best. Besides that, Theseus and MDA perform very similar to ChimeraX MatchMaker.
```
au.create_scatter_plot(all_CAMK_CMGC)
au.create_violine_plot(all_CAMK_CMGC)
```
## Check if data is normally distributed
The Kolmogorov-Smirnow-Test shows, that the values for RMSD, SI, MI, SAS and relative coverage are not normally distributed. The superposition methods have similar distributions for the measures except the relative coverage. MMLigner performs the best for all measures except the relative coverage.
```
dist_tests = au.check_distribution(all_CAMK_CMGC)
```
## Compute Correlation
Since the data is not distributed normally, the spearman correlation is used.
The three quality measures correlate very well with each other and with the rmsd. The quality measures also slightly positively correlate with the relative coverage, which means, the higher the relative coverage, the higher the quality measures.
The time negatively correlates with the quality measures, which means taking more time for an alignment produces better results. This correlation in this case is highly biased by MMLigner. It takes much more time than the other methods, but also yield overall the best results.
All three quality measures share the property, that lower values mean better alignments.
```
corr = au.compute_correlation(all_CAMK_CMGC, coeff="spearman")
corr
```
## Check for significant differences
Because the data is not normally distributed, an ANOVA is not suitable. Therefore the Kruskal-Wallis-Test is performed. The RMSD and the three quality measures are significantly different for the groups.
```
kruskal = au.compute_kruskal(all_CAMK_CMGC)
```
## Which groups are different
The statistics show, that all groups are significantly different from each other, except PyMol and MDA. Looking at the diagrams above it is still noticable, that PyMol, ChimeraX, MDA and Theseus are in the same area.
```
significant, non_significant = au.compute_mannwhitneyu(all_CAMK_CMGC)
```
# Count the best alignments
For every pair of structures, the method that has the best quality measure is selected. The following statistics show how often a method had the best results for the quality measures.
```
best_results = au.count_best_results(all_CAMK_CMGC)
```
| github_jupyter |
# Exploratory Data Analysis Case Study -
##### Conducted by Nirbhay Tandon & Naveen Sharma
## 1.Import libraries and set required parameters
```
#import all the libraries and modules
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import re
from scipy import stats
# Supress Warnings
#Enable autocomplete in Jupyter Notebook.
%config IPCompleter.greedy=True
import warnings
warnings.filterwarnings('ignore')
import os
## Set the max display columns to None so that pandas doesn't sandwich the output
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', 40)
```
### Reading and analysing Data
```
applicationData=pd.read_csv("./application_data.csv")
applicationData.head()
```
## 2. Data Inspection
```
#shape of application_data.csv data
applicationData.shape
#take information about the data
applicationData.info()
#get the information about the numerical data
applicationData.describe()
## print the column names for application_data.csv
applicationData.columns
## print the various datatypes of application_data.csv
applicationData.dtypes
```
## 3. Data Cleaning & Quality Check
In this section we will perform various checks and balances on the application_data.csv file.
We will:
* Perform a check for the number of missing/null values on each column
* Perform a check for the percentage of missing/null values of each column
* Drop the columns that have a high percentage of null values, i.e. over 60%
* Print the names of the dropped columns
* Verify that the columns were dropped by comparing the shape of the new dataframe created
* For columns with around 13% of null values we will discuss the best way to handle the missing/null values in the columns
* Check the data types of these columns and determine if they are categorical in nature or not
* Check the data types for all the columns in the dataframe and convert them to numerical data types if required
* Check for any outliers in any 3 numerical columns and treat them accordingly
* Create a bin for continous variables and analyse them
```
### Let us create a utility function to generate a list of null values in different dataframes
### We will utilize this function extensively througout the notebook.
def generateNullValuesPercentageTable(dataframe):
totalNullValues = dataframe.isnull().sum().sort_values(ascending=False)
percentageOfNullValues = round((dataframe.isnull().sum()*100/len(dataframe)).sort_values(ascending=False),2)
columnNamesWithPrcntgOfNullValues = pd.concat([totalNullValues, percentageOfNullValues], axis=1, keys=['Total Null Values', 'Percentage of Null Values'])
return columnNamesWithPrcntgOfNullValues
## Check the number of null values of each column and display them in
## decending order along with the percentage of null values there is
generateNullValuesPercentageTable(applicationData)
### Assess the shape of the dataframe before dropping
### columns with a high percentage of
### null values
print("The Initial shape of the DataFrame is: ", applicationData.shape)
#Drop all the columns where the
## percentage of missing values is above 60% in application_data.csv
droppedColumns = applicationData.columns[applicationData.isnull().mean() > 0.60]
applicationDataAfterDroppedColumns = applicationData.drop(droppedColumns, axis = 1)
print("The new shape of the DataFrame is: ", applicationDataAfterDroppedColumns.shape)
## analysing the dataframe is correct after dropping columns
applicationDataAfterDroppedColumns.head()
```
### Observation:
As you can see, the shape of the data has changed from (307511, 122) to (307511, 105). Which mean we have dropped 17 columns that had over 60% percent null values. The dropped columns are mentioned below.
```
print("The columns that have been dropped are: ", droppedColumns)
## print the percentage of columns with null values in the
## new data frame after the columns have been dropped
generateNullValuesPercentageTable(applicationDataAfterDroppedColumns)
#### Check dataframe shape to confirm no other columns were dropped
applicationDataAfterDroppedColumns.shape
```
### Observation:
As you can see above, there are still a few columns that have a above 30% of null/missing values. We can deal with those null/missing values using various methods of imputation.
##### Some key points:
- The columns with above 60% of null values have successfully been dropped
- The column with the highest percentage of null values after the drop is "LANDAREA_MEDI" with 59.38% null values. Whereas earlier it was "COMMONAREA_MEDI" with 69.87% null values
- The new shape of the dataframe is (307511, 105)
Checking the datadrame after dropping null values
```
applicationDataAfterDroppedColumns.head()
### Analyzing Columns with null values around 14% to determine
### what might be the best way to impute such values
listOfColumnsWithLessValuesOfNull = applicationDataAfterDroppedColumns.columns[applicationDataAfterDroppedColumns.isnull().mean() < 0.14]
applicationDataWithLessPrcntgOfNulls = applicationDataAfterDroppedColumns.loc[:, listOfColumnsWithLessValuesOfNull]
print(applicationDataWithLessPrcntgOfNulls.shape)
applicationDataWithLessPrcntgOfNulls.head(20)
### Analysing columns with around 13.5% null values
columnsToDescribe = ['AMT_REQ_CREDIT_BUREAU_QRT', 'AMT_REQ_CREDIT_BUREAU_YEAR', 'AMT_REQ_CREDIT_BUREAU_MON', 'AMT_REQ_CREDIT_BUREAU_DAY', 'AMT_REQ_CREDIT_BUREAU_HOUR','AMT_REQ_CREDIT_BUREAU_WEEK', 'OBS_30_CNT_SOCIAL_CIRCLE', 'OBS_60_CNT_SOCIAL_CIRCLE', 'EXT_SOURCE_2']
applicationDataAfterDroppedColumns[columnsToDescribe].describe()
### Let us plot a boxplot to see the various variables
fig, axes = plt.subplots(nrows=3, ncols = 2, figsize=(40,25))
sns.boxplot(data=applicationDataAfterDroppedColumns.AMT_REQ_CREDIT_BUREAU_YEAR, ax=axes[0][0])
axes[0][0].set_title('AMT_REQ_CREDIT_BUREAU_YEAR')
sns.boxplot(data=applicationDataAfterDroppedColumns.AMT_REQ_CREDIT_BUREAU_MON, ax=axes[0][1])
axes[0][1].set_title('AMT_REQ_CREDIT_BUREAU_MON')
sns.boxplot(data=applicationDataAfterDroppedColumns.AMT_REQ_CREDIT_BUREAU_DAY, ax=axes[1][0])
axes[1][0].set_title('AMT_REQ_CREDIT_BUREAU_DAY')
sns.boxplot(applicationDataAfterDroppedColumns.AMT_REQ_CREDIT_BUREAU_HOUR, ax=axes[1][1])
axes[1][1].set_title('AMT_REQ_CREDIT_BUREAU_HOUR')
sns.boxplot(applicationDataAfterDroppedColumns.AMT_REQ_CREDIT_BUREAU_WEEK, ax=axes[2][0])
axes[2][0].set_title('AMT_REQ_CREDIT_BUREAU_WEEK')
plt.show()
```
### Observation
As you can see above, when we take a look at the columns that have a low number of null values, the shape of the data changes to (307511, 71) compared to (307511, 105). We lose 34 columns in the process.
Checking columns having less no. of Null values(around 13% or so) and analysing the best metric
to impute the missing/null values in those columns basis if the column/variable is 'Categorical' or 'Continuous''
- AMT_REQ_CREDIT_BUREAU_HOUR (99.4% of the values are 0.0 with 4.0 and 3.0 values being outliers. Its safe to impute the missing values with 0.0)
- AMT_REQ_CREDIT_BUREAU_DAY (99.4% of the values are 0.0 with 9.0 and 8.0 values being outliers. Its safe to impute the missing values with 0.0)
- AMT_REQ_CREDIT_BUREAU_WEEK (96.8% of the values are 0.0 with 8.0 and 7.0 values being outliers. Its safe to impute the missing values with 0.0)
- AMT_REQ_CREDIT_BUREAU_MON (83.6% of the values are 0.0. Its safe to impute the missing values with mode : 0.0)
- AMT_REQ_CREDIT_BUREAU_YEAR (It seems fine to use the median value 1.0 here for imputing the missing values)
```
### Checking for categorical data
categoricalDataColumns = applicationDataAfterDroppedColumns.nunique().sort_values()
categoricalDataColumns
```
### Observation:
Given the wide number of columns with a less number of unique values, we will convert all columns with upto 5 values into categorical columns
```
listOfColumnsWithMaxTenUniqueValues = [i for i in applicationDataAfterDroppedColumns.columns if applicationDataAfterDroppedColumns[i].nunique() <= 5]
for col in listOfColumnsWithMaxTenUniqueValues:
applicationDataAfterDroppedColumns[col] = applicationDataAfterDroppedColumns[col].astype('category')
applicationDataAfterDroppedColumns.shape
applicationDataAfterDroppedColumns.head()
## Check for datatypes of all columns in the new dataframe
applicationDataAfterDroppedColumns.info()
```
### Observation:
We notice above that after dropping the null columns we still have:
- 43 Categorical
- 48 Float
- 6 Integer
- 8 Object data types
```
## Convert the categorical data columns into individual columns with numeric values for better analysis
## we will do this using one-hot-encoding method
convertedCategoricalColumnsDataframe = pd.get_dummies(applicationDataAfterDroppedColumns, columns=listOfColumnsWithMaxTenUniqueValues, prefix=listOfColumnsWithMaxTenUniqueValues)
convertedCategoricalColumnsDataframe.head()
## Converting these columns has changed the shape of the data to
print("Shape of Application Data after categorical column conversion: ", convertedCategoricalColumnsDataframe.shape)
```
### Observation
As you can see above we have successfully converted the varius categorical datatypes into their own columns.
The new shape of the data is (307511, 158) compared to (307511, 105). We have introuced 53 new columns. These will help us identify the best possible method to use for imputing values.
```
### Count the number of missing values in the new dataframe
generateNullValuesPercentageTable(convertedCategoricalColumnsDataframe)
```
### Observation
Let us take the following columns - AMT_REQ_CREDIT_BUREAU_YEAR, AMT_REQ_CREDIT_BUREAU_MON, OBS_30_CNT_SOCIAL_CIRCLE, OBS_60_CNT_SOCIAL_CIRCLE, EXT_SOURCE_2.
Determine their datatypes and using the describe above try and identify what values can be used to impute into the null columns.
```
listOfCols = ['AMT_REQ_CREDIT_BUREAU_YEAR', 'AMT_REQ_CREDIT_BUREAU_MON', 'OBS_30_CNT_SOCIAL_CIRCLE', 'OBS_60_CNT_SOCIAL_CIRCLE', 'EXT_SOURCE_2']
convertedCategoricalColumnsDataframe[listOfCols].dtypes
applicationDataAfterDroppedColumns['AMT_REQ_CREDIT_BUREAU_HOUR'].fillna(0.0, inplace = True)
applicationDataAfterDroppedColumns['AMT_REQ_CREDIT_BUREAU_HOUR'] = applicationDataAfterDroppedColumns['AMT_REQ_CREDIT_BUREAU_HOUR'].astype(int)
## convert DAYS_BIRTH to years
def func_age_yrs(x):
return round(abs(x/365),0)
applicationDataAfterDroppedColumns['DAYS_BIRTH'] = applicationDataAfterDroppedColumns['DAYS_BIRTH'].apply(func_age_yrs)
```
### Observation
In all the selected columns we can see that we can use the median to impute the values in the dataframe. They all correspond to 0.00 except EXT_SOURCE_2. For EXT_SOURCE_2 we observe that the mean and the median values are roughly similar at 5.143927e-01 for mean & 5.659614e-01 for median. So we could use either of those values to impute.
Let us now check for outliers on 6 numerical columns.
For this we can use our dataset from after we dropped the columns with over 60% null values.
```
### We will use boxplots to handle the outliers on AMT_CREDIT, AMT_ANNUITY, AMT_GOODS_PRICE
fig, axes = plt.subplots(nrows=3, ncols = 2, figsize=(50,50))
sns.boxplot(data= applicationDataAfterDroppedColumns.AMT_CREDIT.dropna(), ax=axes[0][0])
axes[0][0].set_title('AMT_CREDIT')
sns.boxplot(data= applicationDataAfterDroppedColumns.AMT_ANNUITY.dropna(), ax=axes[0][1])
axes[0][1].set_title('AMT_ANNUITY')
sns.boxplot(data= applicationDataAfterDroppedColumns.AMT_GOODS_PRICE.dropna(), ax=axes[1][0])
axes[1][0].set_title('AMT_GOODS_PRICE')
sns.boxplot(data= applicationDataAfterDroppedColumns.AMT_INCOME_TOTAL.dropna(), ax=axes[1][1])
axes[1][1].set_title('AMT_INCOME_TOTAL')
sns.boxplot(data= applicationDataAfterDroppedColumns.DAYS_BIRTH.dropna(), ax=axes[2][0])
axes[2][0].set_title('DAYS_BIRTH')
sns.boxplot(data= applicationDataAfterDroppedColumns.DAYS_EMPLOYED.dropna(), ax=axes[2][1])
axes[2][1].set_title('DAYS_EMPLOYED')
plt.show()
```
### Observation
We can easily see in the box plot that there are so many outliers which has to removed for the better calculation. So, In the next part of the code we remove outliers from the function "remove_outliers" which accept dataframe and columns name (In which we want to remove outliers) as argument and return the outliers removed dataframe.
Analysing outliers in Numeric variables and Handling/Treating them with appropriate methods.
- AMT_REQ_CREDIT_BUREAU_HOUR (99.4% of the values are 0.0 with value '4' and '3' being outliers. Should be retained)
Considering that its the number of enquiries made by the company to credit bureau, this could significantly mean that the company was extremely cautious in making a decision of whether to grant loan/credit to this particular client or not. This might imply that it could be a case of 'High Risk' client and can influence the Target variable. Its better to retain these outlier values
- AMT_INCOME_TOTAL ( Clearly 117000000.0 is an outlier here.)
The above oulier can be dropped in order to not skew with the analysis. We can use IQR to remove this value.
- DAYS_BIRTH ( There is no outlier in this column)
- DAYS_EMPLOYED ( Clearly 1001 is an outlier here and should be deleted.18% of the column values are 1001)
Clearly 1001 is an outlier here. 18% of the column values are 1001. Since , this represents the no. of years of employement as on the application date, these should be deleted. Though values above 40 years till 49 years of employment seems questionable as well but lets not drop it for now considering exception cases.
Another way to see the distribution of is using a distribution plot.
```
fig, axes = plt.subplots(nrows=3, ncols = 2, figsize=(50,50))
sns.distplot(applicationDataAfterDroppedColumns.AMT_CREDIT.dropna(), ax=axes[0][0])
axes[0][0].set_title('AMT_CREDIT')
sns.distplot(applicationDataAfterDroppedColumns.AMT_ANNUITY.dropna(), ax=axes[0][1])
axes[0][1].set_title('AMT_ANNUITY')
sns.distplot(applicationDataAfterDroppedColumns.AMT_GOODS_PRICE.dropna(), ax=axes[1][0])
axes[1][0].set_title('AMT_GOODS_PRICE')
sns.distplot(applicationDataAfterDroppedColumns.AMT_INCOME_TOTAL.dropna(), ax=axes[1][1])
axes[1][1].set_title('AMT_INCOME_TOTAL')
sns.distplot(applicationDataAfterDroppedColumns.DAYS_BIRTH.dropna(), ax=axes[2][0])
axes[2][0].set_title('DAYS_BIRTH')
sns.distplot(applicationDataAfterDroppedColumns.DAYS_EMPLOYED.dropna(), ax=axes[2][1])
axes[2][1].set_title('DAYS_EMPLOYED')
plt.show()
```
### Observation
As you can see from the distplots above there are a few outliers that aren't properly normalized.
The 'DAYS_EMPLOYED' column is heavily skewed in the -ve side of the plot.
```
#Function for removing outliers
def remove_outlier(df, col_name):
q1 = df[col_name].quantile(0.25)
q3 = df[col_name].quantile(0.75)
iqr = q3-q1 #Interquartile range
l = q1-1.5*iqr
h = q3+1.5*iqr
dfOutput = df.loc[(df[col_name] > l) & (df[col_name] < h)]
return dfOutput
cols=['AMT_CREDIT','AMT_ANNUITY', 'AMT_GOODS_PRICE', 'AMT_INCOME_TOTAL', 'DAYS_EMPLOYED']
for i in cols:
applicationDataAfterDroppedColumns=remove_outlier(applicationDataAfterDroppedColumns,i)
applicationDataAfterDroppedColumns.head()
### Plot the box plot again after removing outliers
fig, axes = plt.subplots(nrows=3, ncols = 2, figsize=(50,50))
sns.boxplot(data= applicationDataAfterDroppedColumns.AMT_CREDIT.dropna(), ax=axes[0][0])
axes[0][0].set_title('AMT_CREDIT')
sns.boxplot(data= applicationDataAfterDroppedColumns.AMT_ANNUITY.dropna(), ax=axes[0][1])
axes[0][1].set_title('AMT_ANNUITY')
sns.boxplot(data= applicationDataAfterDroppedColumns.AMT_GOODS_PRICE.dropna(), ax=axes[1][0])
axes[1][0].set_title('AMT_GOODS_PRICE')
sns.boxplot(data= applicationDataAfterDroppedColumns.AMT_INCOME_TOTAL.dropna(), ax=axes[1][1])
axes[1][1].set_title('AMT_INCOME_TOTAL')
sns.boxplot(data= applicationDataAfterDroppedColumns.DAYS_BIRTH.dropna(), ax=axes[2][0])
axes[2][0].set_title('DAYS_BIRTH')
sns.boxplot(data= applicationDataAfterDroppedColumns.DAYS_EMPLOYED.dropna(), ax=axes[2][1])
axes[2][1].set_title('DAYS_EMPLOYED')
plt.show()
```
### Observation
After dropping the outliers we observe that there very few points mentioned on the box plots above for the outliers.
```
### Plotting the distribution plot after removing the outliers
fig, axes = plt.subplots(nrows=3, ncols = 2, figsize=(50,50))
sns.distplot(applicationDataAfterDroppedColumns.AMT_CREDIT.dropna(), ax=axes[0][0])
axes[0][0].set_title('AMT_CREDIT')
sns.distplot(applicationDataAfterDroppedColumns.AMT_ANNUITY.dropna(), ax=axes[0][1])
axes[0][1].set_title('AMT_ANNUITY')
sns.distplot(applicationDataAfterDroppedColumns.AMT_GOODS_PRICE.dropna(), ax=axes[1][0])
axes[1][0].set_title('AMT_GOODS_PRICE')
sns.distplot(applicationDataAfterDroppedColumns.AMT_INCOME_TOTAL.dropna(), ax=axes[1][1])
axes[1][1].set_title('AMT_INCOME_TOTAL')
sns.distplot(applicationDataAfterDroppedColumns.DAYS_BIRTH.dropna(), ax=axes[2][0])
axes[2][0].set_title('DAYS_BIRTH')
sns.distplot(applicationDataAfterDroppedColumns.DAYS_EMPLOYED.dropna(), ax=axes[2][1])
axes[2][1].set_title('DAYS_EMPLOYED')
plt.show()
```
### Observation
Based on the distplots above you can see that there is a marked difference between the minimum values for various columns, particularly the DAYS_EMPLOYED column where the minimum value increased from -7500 to -6000. This proves that the treatment of outliers was succesful
```
applicationDataAfterDroppedColumns.shape
```
### Observation
We observe that after removing the outliers the boxplots show a slight shift in the maximum ranges.
The distribution plot gives us a more significant display in changes. There is a significant reduction in the max ranges on the x-axis for all the three variables we chose.
As we can see above, after treating the outliers for various columns the shape of our dataset has changed significantly. The shape of the dataframe after dropping columns with high number of null values was (307511, 105) & after treating for outliers is (209624, 105).
Let us now create bins for 3 different continous variables and plot them. We will use AMT_INCOME_TOTAL, AMT_CREDIT & DAYS_BIRTH to create our bins.
```
## Creating bins for Income range based on AMT_INCOME_TOTAL
bins=[0,100000,200000,300000,400000,500000,600000,20000000]
range_period=['0-100000','100000-200000','200000-300000','300000-400000','400000-500000','500000-600000','600000 and above']
applicationDataAfterDroppedColumns['Income_amount_range']=pd.cut(applicationDataAfterDroppedColumns['AMT_INCOME_TOTAL'],bins,labels=range_period)
plotIncomeAmountRange = applicationDataAfterDroppedColumns['Income_amount_range'].value_counts().plot(kind='bar', title='Income Range Bins Plot')
plotIncomeAmountRange.set_xlabel('Income Range Bins')
plotIncomeAmountRange.set_ylabel('Count')
```
### Observation
As you can clearly see from the plot above:
- The most number of people earn between 100000-200000
- The number of people who earn between 200000-300000 is less than half of the number of people in 100000-200000 range
- No one earns above 300000.
```
#create bins for credit anount
bins=[0,50000,100000,150000,200000,250000,300000,400000]
range_period=['0-50000','50000-100000','100000-150000','150000-200000','200000-250000','250000-300000','300000-400000']
applicationDataAfterDroppedColumns['credit_amount_range']=pd.cut(applicationDataAfterDroppedColumns['AMT_CREDIT'],bins,labels=range_period)
plotCreditAmountRange = applicationDataAfterDroppedColumns['credit_amount_range'].value_counts().plot(kind='bar', title='Credit Amount Range Plots')
plotCreditAmountRange.set_xlabel('Credit Amount Range Bins')
plotCreditAmountRange.set_ylabel('Count')
```
### Observation
As you can see from the plots above
- Very less number of people borrow money between 0-50000
- Highest number of people are borrowing money between 250000-300000
```
##Creating bins for age range for DAYS_BIRTH in years
bins = [10, 20, 30, 40, 50, 60, 70, 80]
labels = ['10-20','21-30','31-40','41-50','51-60','61-70','71-80']
applicationDataAfterDroppedColumns['BINNED_AGE'] = pd.cut(applicationDataAfterDroppedColumns['DAYS_BIRTH'], bins=bins,labels=labels)
plotAgeRange = applicationDataAfterDroppedColumns['BINNED_AGE'].value_counts().plot(kind='bar', title='Age Range Plot')
plotAgeRange.set_xlabel('Age Range')
plotAgeRange.set_ylabel('Count')
```
### Observation
- People between the ages of 71-80 & 10-20 are not borrowing any money.
- For people in the age range of 10-20, no borrowing could suggest that children/teenagers/young adults could have just opened new bank accounts with their parents or have just joined university so do not have a need of borrowing money
- People in between the ages of 31-40 have a significantly higher number of borrowers, this could be suggestive of various personal expenses & it would be beneficial for the firm to identify the reasons why they are borrowing more so that they can introduce newer products at more competitive interest rates to these customers
# 4. Data Analysis
In this section we will perform indepth analysis on the application_data.csv file.
This will be achieved by:
- Checking the imbalance percentage in the dataset
- Dividing the dataset based on the "TARGET" column into 2 separate dataframes
- Performing univariate analysis for categorical variables on both Target = 0 & Target = 1 columns
- Identifying the correlation between the numerical columns for both Target = 0 & Target = 1 columns
- Comparing the results across continous variables
- Performing bivariate analysis for numerical variables on both Target = 0 & Target = 1 columns
## Selecting relevant columns from 'applicationDataAfterDroppedColumns' which would be used for EDA further
- Selecting only the relevant columns(25 or so) from 'applicationDataAfterDroppedColumns' i.e. removing those columns which aren't relevant for analysis out of a total of 105 columns
```
applicationDataWithRelevantColumns = applicationDataAfterDroppedColumns.loc[:,['SK_ID_CURR',
'TARGET',
'NAME_CONTRACT_TYPE',
'CODE_GENDER',
'FLAG_OWN_CAR',
'FLAG_OWN_REALTY',
'CNT_CHILDREN',
'AMT_INCOME_TOTAL',
'AMT_CREDIT',
'AMT_ANNUITY',
'AMT_GOODS_PRICE',
'NAME_INCOME_TYPE',
'NAME_EDUCATION_TYPE',
'NAME_FAMILY_STATUS',
'NAME_HOUSING_TYPE',
'REGION_POPULATION_RELATIVE',
'BINNED_AGE',
'DAYS_EMPLOYED',
'DAYS_REGISTRATION',
'DAYS_ID_PUBLISH',
'FLAG_CONT_MOBILE',
'OCCUPATION_TYPE',
'CNT_FAM_MEMBERS',
'REGION_RATING_CLIENT',
'REGION_RATING_CLIENT_W_CITY',
'ORGANIZATION_TYPE',
'AMT_REQ_CREDIT_BUREAU_HOUR',
'AMT_REQ_CREDIT_BUREAU_DAY']]
```
We will now use applicationDataWithRelevantColumns as our dataframe to run further analysis
```
### Checking shape of the new dataframe
applicationDataWithRelevantColumns.shape
applicationDataWithRelevantColumns['CODE_GENDER'].value_counts()
```
Since the number of Females is higher than Males, we can safely impute XNA values with F.
```
applicationDataWithRelevantColumns.loc[applicationDataWithRelevantColumns['CODE_GENDER']=='XNA','CODE_GENDER']='F'
applicationDataWithRelevantColumns['CODE_GENDER'].value_counts()
#Check the total percentage of target value as 0 and 1.
imbalancePercentage = applicationDataWithRelevantColumns['TARGET'].value_counts()*100/len(applicationDataAfterDroppedColumns)
imbalancePercentage
imbalancePercentage.plot(kind='bar',rot=0)
```
### Observation
We can easily see that this data is very much imbalance. Rows with target value 0 is only 90.612239% and with 1 is only 9.387761%.
This also means that only 9.38% of all the loan applicants default while paying back their loans.
```
#Splitting the data based on target values
one_df = applicationDataWithRelevantColumns.loc[applicationDataWithRelevantColumns['TARGET']==1]
zero_df = applicationDataWithRelevantColumns.loc[applicationDataWithRelevantColumns['TARGET']==0]
## Inspecting data with TARGET = 1
one_df.head()
one_df.info()
one_df.shape
## Inspecting data with TARGET = 0
zero_df.head()
zero_df.describe
zero_df.shape
zero_df.info
```
We will now use the following columns to perform Univariate & Bivariate analysis
- CODE_GENDER
- NAME_CONTRACT_TYPE
- NAME_INCOME_TYPE
- NAME_EDUCATION_TYPE
- NAME_FAMILY_STATUS
- NAME_HOUSING_TYPE
- OCCUPATION_TYPE
- ORGANIZATION_TYPE
### Univariate Analysis:-
Univariate Analysis on one_df dataset
```
#Univariate Analysis for categorical variable 'CODE_GENDER' in dataframe one_df.
sns.countplot(x ='CODE_GENDER', data = one_df)
plt.title('Number of applications by Gender')
plt.ylabel('Number of Applications')
plt.xlabel('Gender')
plt.show()
```
### Observation
As you can see above the number of Female applicants is higher than the number of Male applicants.
```
#Univariate Analysis for categorical variable 'NAME_EDUCATION_TYPE' in dataframe T1.
sns.countplot(x ='NAME_EDUCATION_TYPE', data = one_df)
plt.title("Number of applications by Client's Education Level")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Education Level")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
From the plot above we can infer that:
- The highest number of applications for credit were made by people having Secondary/ secondary special education and these people defaulted on being able to pay back their loans. This could mean that they face trouble in being able to manage their money effectively or have jobs that pay less/are contractual in nature
- People with higher education also applied for a credit and defaulted on their loans
```
#Univariate Analysis for categorical variable 'NAME_CONTRACT_TYPE' in dataframe one_df.
sns.countplot(x ='NAME_CONTRACT_TYPE', data = one_df)
plt.title('Number of applications by Contract Type')
plt.ylabel('Number of Applications')
plt.xlabel('Contract Type')
plt.show()
```
### Observation
- A high number of applicants who defaulted applied for cash loans
```
#Univariate Analysis for categorical variable 'NAME_INCOME_TYPE' in dataframe one_df.
sns.countplot(x ='NAME_INCOME_TYPE', data = one_df)
plt.title("Number of applications by Client's Income Type")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Income Type")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
- Mostly working professionals apply for credit and are also the ones that default on being able to payback the loans on time
- State servants have a very low number of defaulters
```
#Univariate Analysis for categorical variable 'NAME_FAMILY_STATUS' in dataframe one_df.
sns.countplot(x ='NAME_FAMILY_STATUS', data = one_df)
plt.title("Number of applications by Client's Family Status")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Family Status")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
- Married applicants make a higher number of applications as compared to other categories
- It would be beneficial for the bank to introduce newer products for people in such a category to attract more customers
```
#Univariate Analysis for categorical variable 'NAME_HOUSING_TYPE' in dataframe one_df.
sns.countplot(x ='NAME_HOUSING_TYPE', data = one_df)
plt.title("Number of applications by Client's Housing Status")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Housing Status")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
- People who live in their own apartment/house apply for loans almost 160 times more than those who live with their parents.
- People living in office apartments default significantly less. This could be because their houses are rent free or they pay minimum charges to live in the house.
```
#Univariate Analysis for categorical variable 'OCCUPATION_TYPE' in dataframe one_df.
sns.countplot(x ='OCCUPATION_TYPE', data = one_df)
plt.title("Number of applications by Client's Occupation Type")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Occupation Type")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
- Labourers apply for a lot of loans and default on being able to repay them. This could be because of the contractual nature of their work and the unsetady + low income they might earn from their daily jobs
- IT & HR Staff make very few applications for credit and default the least on their loan applications. This could be, in stark contrast to the labourers, because of the stable job & salaried nature of their work. Thus enabling them to be better at handling monthly expenses.
```
# Since there are subcategories like Type1,2 etc under few categories like Business Entity,Trade etc.
# Because of this, there are a lot of categories making it difficult to analyse data
# Its better to remove the types and just have the main category there
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Business Entity Type 3", "Business Entity")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Business Entity Type 2", "Business Entity")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Business Entity Type 1", "Business Entity")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Trade: type 7", "Trade")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Trade: type 3", "Trade")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Trade: type 2", "Trade")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Trade: type 1", "Trade")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Trade: type 6", "Trade")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Trade: type 5", "Trade")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Trade: type 4", "Trade")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Transport: type 4", "Transport")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Transport: type 3", "Transport")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Transport: type 2", "Transport")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Transport: type 1", "Transport")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 1", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 2", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 3", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 4", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 5", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 6", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 7", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 8", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 9", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 10", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 11", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 12", "Industry")
one_df.ORGANIZATION_TYPE= one_df.ORGANIZATION_TYPE.replace("Industry: type 13", "Industry")
one_df['ORGANIZATION_TYPE'].value_counts()
#Univariate Analysis for categorical variable 'ORGANIZATION_TYPE' in dataframe one_df.
plt.figure(figsize = (14,14))
sns.countplot(x ='ORGANIZATION_TYPE', data = one_df)
plt.title("Number of applications by Client's Organization Type")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Organization Type")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
- Based on the plot above we can see that Business Entity employees have the maximum number of loan applications
- Religious people, priests etc dont seem to be making any credit applications at all
- Self-employed people also make a lot of loan applications. This could be to boost their business or to repay other loans.
##### Continuous - Continuous Bivariate Analysis for one_df dataframe
```
## Plotting cont-cont Client Income vs Credit Amount
plt.figure(figsize=(12,12))
sns.scatterplot(x="AMT_INCOME_TOTAL", y="AMT_CREDIT",
hue="CODE_GENDER", style="CODE_GENDER", data=one_df)
plt.xlabel('Income of client')
plt.ylabel('Credit Amount of loan')
plt.title('Client Income vs Credit Amount')
plt.show()
```
### Observation
- We do see some outliers here wherein Females having income less than 50000 have applied for loan with credit amount 1300000 approx
- Most of the loans seem to be concentrated between credit amount of 200000 & 6000000 for income ranging from 50000-150000
```
## Plotting cont-cont Client Income vs Region population
plt.figure(figsize=(12,12))
sns.scatterplot(x="AMT_INCOME_TOTAL", y="REGION_POPULATION_RELATIVE",
hue="CODE_GENDER", style="CODE_GENDER", data=one_df)
plt.xlabel('Income of client')
plt.ylabel('Population of region where client lives')
plt.title('Client Income vs Region population')
plt.show()
```
### Observation
- Very less no of people live in highly dense/populated region
- Most of the clients live between population density of 0.00 to 0.04
##### Univariate analysis for zero_df dataframe
```
#Univariate Analysis for categorical variable 'CODE_GENDER' in dataframe zero_df.
sns.countplot(x ='CODE_GENDER', data = zero_df)
plt.title('Number of applications by Gender')
plt.ylabel('Number of Applications')
plt.xlabel('Gender')
plt.show()
```
### Observation
As you can see above the number of Female applicants is higher than the number of Male applicants.
```
#Univariate Analysis for categorical variable 'NAME_CONTRACT_TYPE' in dataframe zero_df.
sns.countplot(x ='NAME_CONTRACT_TYPE', data = zero_df)
plt.title('Number of applications by Contract Type')
plt.ylabel('Number of Applications')
plt.xlabel('Contract Type')
plt.show()
```
### Observation
Applicants prefer to apply more for cash loans rather than revolving loans
```
#Univariate Analysis for categorical variable 'NAME_INCOME_TYPE' in dataframe zero_df.
sns.countplot(x ='NAME_INCOME_TYPE', data = zero_df)
plt.title("Number of applications by Client's Income Type")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Income Type")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
- Working people make the most number of applications and are able to successfully repay their loans as well.
- Students, Pensioners, Business men and Maternity leave applicants is close to 0. This could be due to a multitude of reasons.
```
#Univariate Analysis for categorical variable 'NAME_EDUCATION_TYPE' in dataframe zero_df.
sns.countplot(x ='NAME_EDUCATION_TYPE', data = zero_df)
plt.title("Number of applications by Client's Education Level")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Education Level")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
From the plot above we can infer that:
- The highest number of applications for credit were made by people having Secondary/ secondary special education and these people did not default on being able to pay back their loans.
- People with higher education also applied for a credit and were able to repay them successfully
```
#Univariate Analysis for categorical variable 'NAME_FAMILY_STATUS' in dataframe zero_df.
sns.countplot(x ='NAME_FAMILY_STATUS', data = zero_df)
plt.title("Number of applications by Client's Family Status")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Family Status")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
From the plot above we can infer that:
- Married people apply for credit the most.
- Married people are able to repay their loans without any defaults as well
```
#Univariate Analysis for categorical variable 'NAME_HOUSING_TYPE' in dataframe zero_df.
sns.countplot(x ='NAME_HOUSING_TYPE', data = zero_df)
plt.title("Number of applications by Client's Housing Status")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Housing Status")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
- People who live in their own apartment/house apply for loans almost 160 times more than those who live with their parents.
- People living in office apartments apply for loans significantly less. This could be because their houses are rent free or they pay minimum charges to live in the house.
- People in rented apartments apply for loans significantly less. This could be due to the added expenses of paying rent and other utility bills leaves them with not enough capital to payback their loans.
```
#Univariate Analysis for categorical variable 'OCCUPATION_TYPE' in dataframe zero_df.
sns.countplot(x ='OCCUPATION_TYPE', data = zero_df)
plt.title("Number of applications by Client's Occupation Type")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Occupation Type")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
- Labourers apply for a lot of loans.
- IT & HR Staff make very few applications for credit. This could be, in stark contrast to the labourers, because of the stable job & salaried nature of their work. Thus enabling them to be better at handling monthly expenses.
```
# Since there are subcategories like Type1,2 etc under few categories like Business Entity,Trade etc.
# Because of this, there are a lot of categories making it difficult to analyse data
# Its better to remove the types and just have the main category there
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Business Entity Type 3", "Business Entity")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Business Entity Type 2", "Business Entity")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Business Entity Type 1", "Business Entity")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Trade: type 7", "Trade")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Trade: type 3", "Trade")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Trade: type 2", "Trade")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Trade: type 1", "Trade")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Trade: type 6", "Trade")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Trade: type 5", "Trade")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Trade: type 4", "Trade")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Transport: type 4", "Transport")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Transport: type 3", "Transport")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Transport: type 2", "Transport")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Transport: type 1", "Transport")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 1", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 2", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 3", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 4", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 5", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 6", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 7", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 8", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 9", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 10", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 11", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 12", "Industry")
zero_df.ORGANIZATION_TYPE= zero_df.ORGANIZATION_TYPE.replace("Industry: type 13", "Industry")
zero_df['ORGANIZATION_TYPE'].value_counts()
#Univariate Analysis for categorical variable 'ORGANIZATION_TYPE' in dataframe zero_df.
plt.figure(figsize = (14,14))
sns.countplot(x ='ORGANIZATION_TYPE', data = zero_df)
plt.title("Number of applications by Client's Organization Type")
plt.ylabel('Number of Applications')
plt.xlabel("Client's Organization Type")
plt.xticks(rotation = 90)
plt.show()
```
### Observation
- Based on the plot above we can see that Business Entity employees have the maximum number of loan applications
- Religious people, priests etc dont seem to be making a lot of credit applications at all. They are able to repay their loans on time as well.
- Self-employed people also make a lot of loan applications. This could be to boost their business or to repay other loans.
### Bivariate Analysis for zero_df
```
### Let us create a helper function to help with
### plotting various graphs
def uniplot(df,col,title,hue =None):
sns.set_style('whitegrid')
sns.set_context('talk')
plt.rcParams["axes.labelsize"] = 20
plt.rcParams['axes.titlesize'] = 22
plt.rcParams['axes.titlepad'] = 30
plt.figure(figsize=(40,20))
temp = pd.Series(data = hue)
fig, ax = plt.subplots()
width = len(df[col].unique()) + 7 + 4*len(temp.unique())
fig.set_size_inches(width , 8)
plt.xticks(rotation=45)
plt.title(title)
ax = sns.countplot(data = df, x= col, order=df[col].value_counts().index,hue = hue,
palette='magma')
plt.show()
# PLotting for income range
uniplot(zero_df,col='NAME_INCOME_TYPE',title='Distribution of Income type',hue='CODE_GENDER')
```
### Observation
- For income type ‘working’, ’commercial associate’, and ‘State Servant’ the number of credits are higher than others.
- For this Females are having more number of credit applications than males in all the categories.
```
uniplot(zero_df,col='NAME_CONTRACT_TYPE',title='Distribution of contract type',hue='CODE_GENDER')
```
### Observation
- For contract type ‘cash loans’ is having higher number of credits than ‘Revolving loans’ contract type.
- For this also Females are applying for credit a lot more than males.
```
uniplot(zero_df,col='NAME_FAMILY_STATUS',title='Distribution of Family status',hue='CODE_GENDER')
```
### Observation
- As observed above the number of married females applying for loans is almost 3.5 times the number of single females.
- No male widowers are applying for credit
```
uniplot(zero_df,col='NAME_EDUCATION_TYPE',title='Distribution of education level',hue='CODE_GENDER')
```
### Observation
- No person with an 'Academic Degree' is applying for a loan
- The number of females with 'Higher Education' that apply for a loan is almost double the number of males for the same category
```
uniplot(zero_df,col='NAME_HOUSING_TYPE',title='Distribution of Housing Type',hue='CODE_GENDER')
```
### Observation
- Females living in their own apartments/houses apply for more loans and are able to successfully payback.
- A very small number of females living in Co-op apartments apply for loans
```
uniplot(zero_df,col='OCCUPATION_TYPE',title='Distribution Occupation Type',hue='CODE_GENDER')
```
### Observation
- Male Labourers & Drivers take more loans and are able to successfully payback in time.
- Female Care staff & Sales Staff are also able to take loans and payback in time
### Bivariate Analysis on one_df
Perform correlation between numerical columns for finding correlation which having TARGET value as 1
```
uniplot(one_df,col='NAME_INCOME_TYPE',title='Distribution of Income type',hue='CODE_GENDER')
```
### Observation
- For income type ‘working’, ’commercial associate’, and ‘State Servant’ the number of credits are higher than others.
- Females have more number of credit applications than males in all the categories.
```
uniplot(one_df,col='NAME_CONTRACT_TYPE',title='Distribution of contract type',hue='CODE_GENDER')
```
### Observation
- For contract type ‘cash loans’ is having higher number of credits than ‘Revolving loans’ contract type.
- For this also Females are applying for credit a lot more than males.
- Females are also able to payback their loans on time
```
uniplot(one_df,col='NAME_FAMILY_STATUS',title='Distribution of Family status',hue='CODE_GENDER')
```
### Observation
- As observed above the number of married females applying for loans is almost 3.5 times the number of single females.
- No male widowers are applying for credit
- The number of males applying for loans and being able to not payback is higher if they are unmarried/single compared to females
- A very small number of male widowers are unable to payback their loans after
```
uniplot(one_df,col='NAME_EDUCATION_TYPE',title='Distribution of education level',hue='CODE_GENDER')
```
### Observation
- Males with lower secondary education make more loan applications and default more compared to females
- There is very little difference between the number of defaulters for males and females with secondary education compared to the non-defaulters we saw above
```
uniplot(one_df,col='NAME_HOUSING_TYPE',title='Distribution of Housing Type',hue='CODE_GENDER')
```
### Observation
- Males living with their parents tend to apply and default more on their loans
- Almost an equal number of males and females default on loans if they are living in rented apartments
```
uniplot(one_df,col='OCCUPATION_TYPE',title='Distribution Occupation Type',hue='CODE_GENDER')
```
### Observations
- The number of male applicants who default on paying back their loans is almost double the amount of female applicants
- Irrespective of gender, managers seem to default on their loans equally
#### Categorical vs Numerical Analysis
```
# Box plotting for Credit amount for zero_df based on education type and family status
plt.figure(figsize=(40,20))
plt.xticks(rotation=45)
sns.boxplot(data =zero_df, x='NAME_EDUCATION_TYPE',y='AMT_CREDIT', hue ='NAME_FAMILY_STATUS',orient='v')
plt.title('Credit amount vs Education Status')
plt.show()
```
### Observation
- Widows with secondary education have a very high median credit amount borrowing and default on paying back loans as well. It would be better to be vary of lending to them
- Widows with an academic degree have a higher median for borrowing as compared to any other category.
- People in civil marriages, those who are seperated and widows with secondary education have the same median values and usually borrow in around 400000
```
# Box plotting for Income amount for zero_df based on their education type & family status
plt.figure(figsize=(40,20))
plt.xticks(rotation=45)
plt.yscale('log')
sns.boxplot(data =zero_df, x='NAME_EDUCATION_TYPE',y='AMT_INCOME_TOTAL', hue ='NAME_FAMILY_STATUS',orient='v')
plt.title('Income amount vs Education Status')
plt.show()
```
### Observation
- Except widows, the median earning for all other family status types with an incomplete higher education is the same
- Median income for all family status categories is the same for people with a secondary education
```
# Box plotting for Credit amount for one_df
plt.figure(figsize=(16,12))
plt.xticks(rotation=45)
sns.boxplot(data =one_df, x='NAME_EDUCATION_TYPE',y='AMT_CREDIT', hue ='NAME_FAMILY_STATUS',orient='v')
plt.title('Credit amount vs Education Status')
plt.show()
```
### Observation
- Widows with secondary education have a very high median credit amount borrowing and default on paying back loans as well. It would be better to be vary of lending to them
- Married people have a consistently high median across all categories of education except secondary education
```
# Box plotting for Income amount for one_df
plt.figure(figsize=(40,20))
plt.xticks(rotation=45)
plt.yscale('log')
sns.boxplot(data =one_df, x='NAME_EDUCATION_TYPE',y='AMT_INCOME_TOTAL', hue ='NAME_FAMILY_STATUS',orient='v')
plt.title('Income amount vs Education Status')
plt.show()
```
### Observation
- The median income for all family status types is the same for people with education type as Secondary/secondary special
- The median income for widows is the lowest across all the education types
```
### Perform correlation between CNT_CHILDREN, AMT_INCOME_TOTAL, AMT_CREDIT, AMT_GOODS_PRICE, REGION_POPULATION_RELATIVE
### and AMT_ANNUITY. Then make correlation matrix across the one_df dataframe
columns=['CNT_CHILDREN','AMT_INCOME_TOTAL','AMT_CREDIT','AMT_GOODS_PRICE','REGION_POPULATION_RELATIVE', 'AMT_ANNUITY']
corr=one_df[columns].corr()
corr.style.background_gradient(cmap='coolwarm')
```
### Observation
In the heatmap above: The closer you are to RED there is a stronger relationship, the closer you are to blue the weaker the relationship.
As we can see from the corelation matrix above, there is a very close relationship between AMT_GOODS_PRICE & AMT_CREDIT.
AMT_ANNUITY & AMT_CREDIT have a medium/strong relationship. Annuity has a similar relationship with AMT_GOODS_PRICE.
```
### Sorting based on the correlation and extracting top 10 relationships on the defaulters in one_df
corrOneDf = corr.where(np.triu(np.ones(corr.shape), k=1).astype(np.bool)).unstack().reset_index()
corrOneDf.columns = ['VAR1','VAR2','Correlation']
corrOneDf.sort_values('Correlation', ascending = False).nlargest(10, 'Correlation')
```
### Observation
In the correlation matrix, we can identify-
Columns with High Correlation:
1.AMT_GOODS_PRICE and AMT_CREDIT
Columns with Medium Correlation:
1.REGION_POPULATION_RELATIVE and AMT_INCOME_TOTAL
2.REGION_POPULATION_RELATIVE and AMT_GOODS_PRICE
3.REGION_POPULATION_RELATIVE and AMT_CREDIT
Columns with low correlation:
1.AMT_INCOME_TOTAL and CNT_CHILDREN
We also observed that the top 10 correlation pairs are:
- VAR1 VAR2 Correlation Value
- AMT_GOODS_PRICE AMT_CREDIT 0.981276
- AMT_ANNUITY AMT_CREDIT 0.748446
- AMT_ANNUITY AMT_GOODS_PRICE 0.747315
- AMT_ANNUITY AMT_INCOME_TOTAL 0.390809
- AMT_GOODS_PRICE AMT_INCOME_TOTAL 0.317123
- AMT_CREDIT AMT_INCOME_TOTAL 0.313347
- REGION_POPULATION_RELATIVE AMT_INCOME_TOTAL 0.141307
- AMT_ANNUITY REGION_POPULATION_RELATIVE 0.065024
- REGION_POPULATION_RELATIVE AMT_GOODS_PRICE 0.055120
- REGION_POPULATION_RELATIVE AMT_CREDIT 0.050097
Perform correlation between numerical columns for finding correlation which having TARGET value as 0
```
#Perform correlation between CNT_CHILDREN, AMT_INCOME_TOTAL, AMT_CREDIT, AMT_GOODS_PRICE and REGION_POPULATION_RELATIVE
#Then make correlation matrix
corrZero=zero_df[columns].corr()
corrZero.style.background_gradient(cmap='coolwarm')
```
### Observation
In the heatmap above: The closer you are to RED there is a stronger relationship, the closer you are to blue the weaker the relationship.
As we can see from the corelation matrix above, there is a very close relationship between AMT_GOODS_PRICE & AMT_CREDIT.
AMT_ANNUITY & AMT_CREDIT have a medium/strong relationship. Annuity has a similar relationship with AMT_GOODS_PRICE.
This relationship is consistent with the one we saw for the defaulters in the one_df dataframe. Thus confirming that the relationships are consistent across TARGET values
```
corrZeroDf = corrZero.where(np.triu(np.ones(corrZero.shape), k=1).astype(np.bool)).unstack().reset_index()
corrZeroDf.columns = ['VAR1','VAR2','Correlation']
# corrOneDf.dropna(subset - ['Correlation'],inplace = True)
corrZeroDf.sort_values('Correlation', ascending = False).nlargest(10, 'Correlation')
```
In the correlation matrix, we can identify-
Columns with High Correlation:
1.AMT_GOODS_PRICE and AMT_CREDIT
Columns with Medium Correlation:
1.AMT_INCOME_TOTAL and AMT_CREDIT
2.AMT_INCOME_TOTAL and AMT_GOODS_PRICE
Columns with low correlation:
1.AMT_GOODS_PRICE and CNT_CHILDREN
We also observed that the top 10 correlation pairs are:
- VAR1 VAR2 Correlation
- AMT_GOODS_PRICE AMT_CREDIT 0.981276
- AMT_ANNUITY AMT_CREDIT 0.748446
- AMT_ANNUITY AMT_GOODS_PRICE 0.747315
- AMT_ANNUITY AMT_INCOME_TOTAL 0.390809
- AMT_GOODS_PRICE AMT_INCOME_TOTAL 0.317123
- AMT_CREDIT AMT_INCOME_TOTAL 0.313347
- REGION_POPULATION_RELATIVE AMT_INCOME_TOTAL 0.141307
- AMT_ANNUITY REGION_POPULATION_RELATIVE 0.065024
- REGION_POPULATION_RELATIVE AMT_GOODS_PRICE 0.055120
- REGION_POPULATION_RELATIVE AMT_CREDIT 0.050097
#### Key Obervation
We also observed that the top categories between both the data frames zero_df & one_df is the same:
AMT_GOODS_PRICE AMT_CREDIT 0.981276
### Analysing Numerical Data
```
#Box plot on the numerical columns having TARGET value as 1
plt.figure(figsize=(25,25))
plt.subplot(2,2,1)
plt.title('CHILDREN COUNT')
sns.boxplot(one_df['CNT_CHILDREN'])
plt.subplot(2,2,2)
plt.title('AMT_INCOME_TOTAL')
sns.boxplot(one_df['AMT_INCOME_TOTAL'])
plt.subplot(2,2,3)
plt.title('AMT_CREDIT')
sns.boxplot(one_df['AMT_CREDIT'])
plt.subplot(2,2,4)
plt.title('AMT_GOODS_PRICE')
sns.boxplot(one_df['AMT_GOODS_PRICE'])
plt.show()
```
### Observation
- From the box plots above we can safely say that having children has no impact on the reason to why someone defaults on paying back their loans
- The amount of credit taken is roughly around 450000 by the defaulters
```
#Box plot on the numerical columns having TARGET value as 0
plt.figure(figsize=(25,25))
plt.subplot(2,2,1)
plt.title('CHILDREN COUNT')
sns.boxplot(zero_df['CNT_CHILDREN'])
plt.subplot(2,2,2)
plt.title('AMT_INCOME_TOTAL')
sns.boxplot(zero_df['AMT_INCOME_TOTAL'])
plt.subplot(2,2,3)
plt.title('AMT_CREDIT')
sns.boxplot(zero_df['AMT_CREDIT'])
plt.subplot(2,2,4)
plt.title('AMT_GOODS_PRICE')
sns.boxplot(zero_df['AMT_GOODS_PRICE'])
plt.show()
```
### Observation
- From the box plots above we can safely say that having children has no impact oa persons ability to repay their loans
- The amount of credit taken is roughly around 450000 by the defaulters
- There are no outliers in the amoount of goods price
- The income median lies just below 150000
### Bivariate Analysis on zero_df for continuous - continuous (Target value =0)
```
## Plotting cont-cont Client Income vs Credit Amount
plt.figure(figsize=(12,12))
sns.scatterplot(x="AMT_INCOME_TOTAL", y="AMT_CREDIT",
hue="CODE_GENDER", style="CODE_GENDER", data=zero_df)
plt.xlabel('Income of client')
plt.ylabel('Credit Amount of loan')
plt.title('Client Income vs Credit Amount')
plt.show()
```
### Observation
- We do see some outliers here wherein Females having income less than 50000 have applied for loan with credit amount 1300000 approx
```
## Plotting cont-cont Client Income vs Region population
plt.figure(figsize=(12,12))
sns.scatterplot(x="AMT_INCOME_TOTAL", y="REGION_POPULATION_RELATIVE",
hue="CODE_GENDER", style="CODE_GENDER", data=zero_df)
plt.xlabel('Income of client')
plt.ylabel('Population of region where client lives')
plt.title('Client Income vs Region population')
plt.show()
```
### Observation
- Very less no of people live in highly dense/populated region >0.07
- Most of the clients live between population density of 0.00 to 0.04
# 5 PREVIOUS DATA
Read the dataset file previous_application.csv which consist previous loan of the customer.
```
previousApplicationData=pd.read_csv("./previous_application.csv")
previousApplicationData.head()
```
### Analysing previous application data
```
previousApplicationData.shape
previousApplicationData.describe
previousApplicationData.columns
previousApplicationData.dtypes
### Join the previous application data and application data files using merge
mergedApplicationDataAndPreviousData = pd.merge(applicationDataWithRelevantColumns, previousApplicationData, how='left', on=['SK_ID_CURR'])
mergedApplicationDataAndPreviousData.head()
```
### Observation
We will be merging on 'SK_ID_CURR' column as we have duplicate IDs present in the SK_ID_CURR in previousApplicationData and in the application_data file all the values are unique.
```
mergedApplicationDataAndPreviousData.shape
mergedApplicationDataAndPreviousData.NAME_CONTRACT_STATUS.value_counts(normalize=True)
```
### Analysis
We will be focusing on analysing the NAME_CONTRACT_STATUS Column and the various relationships based on that.
## Univariate Analysis
```
uniplot(mergedApplicationDataAndPreviousData,col='NAME_CONTRACT_STATUS',title='Distribution of contract status type', hue=None)
```
### Observation
- A large number of applications were approved for the clients
- Some clients who recieved the offer did not use their loan offers
- The number of refused & cancelled applications is roughly the same
## Bivariate Analysis
```
uniplot(mergedApplicationDataAndPreviousData,col='NAME_CONTRACT_STATUS',title='Distribution Occupation Type',hue='NAME_INCOME_TYPE')
```
### Observation
Based on the plot above we can conclude that:
- Working professionals have the highest number of approved loan applications.
- Working professionals also have the highest number of refused or cancelled loan applications
- Students, pensioners, businessmen and applicants on maternity leave have statistically low or no application status data present
```
uniplot(mergedApplicationDataAndPreviousData,col='NAME_CONTRACT_STATUS',title='Distribution based on Gender',hue='CODE_GENDER')
```
### Observation
- Female applicants make more applications and have a higher number of applications approved
- They also have a higher number of applications refused or canceled
- The number of male applicant statuses is lower than female ones across the board. This could be because of low number of males present in the dataset.
```
uniplot(mergedApplicationDataAndPreviousData,col='NAME_CONTRACT_STATUS',title='Distribution Target',hue='TARGET')
```
### Observation
- Based on the target column, we see that a high number of applicants who have a history of being abe to repay their loans are approved for new loans
- A very low number of defaulters are approved for new loans. This means that the bank is following a cautious approach to defaulters
```
uniplot(mergedApplicationDataAndPreviousData,col='NAME_CONTRACT_STATUS',title='Distribution based on Family Status',hue='NAME_FAMILY_STATUS')
```
### Observation
- A large number of married people make loan applications & are approved for loans
- Separated individuals have a very low number of applications in the unused offer
- The number of single/not married people who apply for loans and are refused or have their applications cancelled as compared to approved is less than half.
```
uniplot(mergedApplicationDataAndPreviousData,col='NAME_CONTRACT_STATUS',title='Distribution based Application Start Day',hue='WEEKDAY_APPR_PROCESS_START')
```
### Observation
- Most applicants start their loan applications on a Saturday and are successfully approved
- Applicants who start their applications on Friday have a higher chance of getting rejected or cancelling their application compared to the other 2 weekend days, Saturday and Sunday
- The number of cancelled applications is highest on Monday. This could suggest that after starting the application on the weekend, the client changed their mind on a workday.
```
uniplot(mergedApplicationDataAndPreviousData,col='NAME_CONTRACT_STATUS',title='Distribution of Age on Loans',hue='BINNED_AGE')
```
### Observation
- People between the ages of 31-40 apply for the most number of loans and have consistently higher values across all application statuses
- People above the age of 71 & below 20 dont make any loan applications
- The people in the ages of 31-40 could be applying for more loans as they are married or living with a partner
```
plt.figure(figsize=(40,25))
sns.catplot(x="NAME_CONTRACT_STATUS", hue="TARGET", col="CODE_GENDER",
data=mergedApplicationDataAndPreviousData, kind="count")
```
### Observation
- Female population has high chances of getting the loans approved
- Cancellation of loans by females is significant across defaulters and non defaulters
### Continous & Categorical Plots
```
### Plotting the relationship between NAME_CONTRACT_STATUS vs AMT_CREDIT_x
### from the merged application data and splitting on the basis of family status
plt.figure(figsize=(40,25))
plt.xticks(rotation=45)
sns.boxplot(data =mergedApplicationDataAndPreviousData, x='NAME_CONTRACT_STATUS',y='AMT_CREDIT_x', hue ='NAME_FAMILY_STATUS',orient='v')
plt.title('Income amount vs Application Status based on Family Status')
plt.show()
```
### Observation
- Married people take a higher amount of credit and have a higher median chance of getting approved
- People in Civil marriage, widows & separated applicants have a consistently similar median value across all the application statuses
```
### Plotting the relationship between NAME_CONTRACT_STATUS vs AMT_INCOME_TOTAL
### from the merged application data and splitting on the basis of family status
plt.figure(figsize=(40,25))
plt.xticks(rotation=45)
plt.yscale('log')
sns.boxplot(data =mergedApplicationDataAndPreviousData, x='NAME_CONTRACT_STATUS',y='AMT_INCOME_TOTAL', hue ='NAME_FAMILY_STATUS',orient='v')
plt.title('Income amount vs Application status based on Family Status')
plt.show()
```
### Observation
- People who are married, live in civil marriages & single/not married earn consistently well across all application status types
- Their median income is also the same
- Widows earn less than all the other categories
### Continous & Continuous Plots
```
plt.figure(figsize=(30,20))
plt.scatter(mergedApplicationDataAndPreviousData.AMT_APPLICATION, mergedApplicationDataAndPreviousData.AMT_CREDIT_y)
plt.title("Final Amount Approved vs Credit Amount Applied")
plt.xlabel("Credit Amount applied by Client")
plt.ylabel("Final Amount approved by Bank")
plt.show()
```
### Observation
- The Credit Amount applied vs Final Amount approved shows a good linear relation till 2000000.
- However post 2000000, we could see good number of outliers where the approved amount is quite less as compared to amount applied
- The number of applications with credit amount > 3500000 are quite less and there are not very good chances that the same amount is going to be approved
# Conclusion
Through this case study we have made the following conclusions:
- Most popular days for making applications is Saturday. The bank could focus on keeping offices open longer on Saturday to aid in completion of the applications.
- Most popular age group for taking loans or credit is 31-40 with the most number of applications. The firm should focus on exploring more lucrative options for clients in that age range. They could be offered lower interest rates, longer repayment holidays etc.
- Married people have the highest chance of making a loan application and being approved for a loan.
- Because of the imbalance in the data, Females appear to be making the most number of loan applications. They also have a higher chance of getting approved and being able to repay the loans on time
- Widows with secondary education have a very high median credit amount borrowing and default on paying back loans as well. It would be better to be vary of lending to them
- Male labourers have high number of applications and also a high number of defaults as compared to females. It would be better for the bank to assess whether the person borrowing in this occupation type could be helped with staged loans or with loans on a lower interest rate than the other categories
- The number of applications with credit amount > 3500000 are quite less and there are not very good chances that the same amount is going to be approved
- Cancellation of loans by females is significant across defaulters and non defaulters
```
sns.boxplot(data= applicationData.AMT_ANNUITY.head(500000).isnull())
axes[0][1].set_title('AMT_ANNUITY')
plt.show()
print(applicationDataAfterDroppedColumns.AMT_ANNUITY.head(500000).isnull().sum())
print(applicationData.AMT_ANNUITY.head(500000).isnull().sum())
sns.boxplot(data= applicationDataAfterDroppedColumns.AMT_ANNUITY.dropna())
plt.show()
```
# END OF FILE
| github_jupyter |
# Introduction to NumPy
Forked from [Lecture 2](https://github.com/jrjohansson/scientific-python-lectures/blob/master/Lecture-2-Numpy.ipynb) of [Scientific Python Lectures](http://github.com/jrjohansson/scientific-python-lectures) by [J.R. Johansson](http://jrjohansson.github.io/)
```
%matplotlib inline
import traceback
import matplotlib.pyplot as plt
import numpy as np
```
### Why NumPy?
```
%%time
total = 0
for i in range(100000):
total += i
%%time
total = np.arange(100000).sum()
%%time
l = list(range(0, 1000000))
ltimes5 = [x * 5 for x in l]
%%time
l = np.arange(1000000)
ltimes5 = l * 5
```
## Introduction
The `numpy` package (module) is used in almost all numerical computation using Python. It is a package that provide high-performance vector, matrix and higher-dimensional data structures for Python. It is implemented in C and Fortran so when calculations are vectorized (formulated with vectors and matrices), performance is very good.
To use `numpy` you need to import the module, using for example:
```
import numpy as np
```
In the `numpy` package the terminology used for vectors, matrices and higher-dimensional data sets is *array*.
## Creating `numpy` arrays
There are a number of ways to initialize new numpy arrays, for example from
* a Python list or tuples
* using functions that are dedicated to generating numpy arrays, such as `arange`, `linspace`, etc.
* reading data from files
### From lists
For example, to create new vector and matrix arrays from Python lists we can use the `numpy.array` function.
```
# a vector: the argument to the array function is a Python list
v = np.array([1,2,3,4])
v
# a matrix: the argument to the array function is a nested Python list
M = np.array([[1, 2], [3, 4]])
M
```
The `v` and `M` objects are both of the type `ndarray` that the `numpy` module provides.
```
type(v), type(M)
```
The difference between the `v` and `M` arrays is only their shapes. We can get information about the shape of an array by using the `ndarray.shape` property.
```
v.shape
M.shape
```
The number of elements in the array is available through the `ndarray.size` property:
```
M.size
```
Equivalently, we could use the function `numpy.shape` and `numpy.size`
```
np.shape(M)
np.size(M)
```
So far the `numpy.ndarray` looks awefully much like a Python list (or nested list). Why not simply use Python lists for computations instead of creating a new array type?
There are several reasons:
* Python lists are very general. They can contain any kind of object. They are dynamically typed. They do not support mathematical functions such as matrix and dot multiplications, etc. Implementing such functions for Python lists would not be very efficient because of the dynamic typing.
* Numpy arrays are **statically typed** and **homogeneous**. The type of the elements is determined when the array is created.
* Numpy arrays are memory efficient.
* Because of the static typing, fast implementation of mathematical functions such as multiplication and addition of `numpy` arrays can be implemented in a compiled language (C and Fortran is used).
Using the `dtype` (data type) property of an `ndarray`, we can see what type the data of an array has:
```
M.dtype
```
We get an error if we try to assign a value of the wrong type to an element in a numpy array:
```
try:
M[0,0] = "hello"
except ValueError as e:
print(traceback.format_exc())
```
If we want, we can explicitly define the type of the array data when we create it, using the `dtype` keyword argument:
```
M = np.array([[1, 2], [3, 4]], dtype=complex)
M
```
Common data types that can be used with `dtype` are: `int`, `float`, `complex`, `bool`, `object`, etc.
We can also explicitly define the bit size of the data types, for example: `int64`, `int16`, `float128`, `complex128`.
### Using array-generating functions
For larger arrays it is inpractical to initialize the data manually, using explicit python lists. Instead we can use one of the many functions in `numpy` that generate arrays of different forms. Some of the more common are:
#### arange
```
# create a range
x = np.arange(0, 10, 1) # arguments: start, stop, step
x
x = np.arange(-1, 1, 0.1)
x
```
#### linspace and logspace
```
# using linspace, both end points ARE included
np.linspace(0, 10, 25)
np.logspace(0, 10, 10, base=np.e)
```
#### mgrid
```
x, y = np.mgrid[0:5, 0:5] # similar to meshgrid in MATLAB
x
y
```
#### random data
```
# uniform random numbers in [0,1]
np.random.rand(5,5)
# standard normal distributed random numbers
np.random.randn(5,5)
```
#### diag
```
# a diagonal matrix
np.diag([1,2,3])
# diagonal with offset from the main diagonal
np.diag([1,2,3], k=1)
```
#### zeros and ones
```
np.zeros((3,3))
np.ones((3,3))
```
## File I/O
### Comma-separated values (CSV)
A very common file format for data files is comma-separated values (CSV), or related formats such as TSV (tab-separated values). To read data from such files into Numpy arrays we can use the `numpy.genfromtxt` function. For example,
```
!head ../data/stockholm_td_adj.dat
data = np.genfromtxt('../data/stockholm_td_adj.dat')
data.shape
fig, ax = plt.subplots(figsize=(14,4))
ax.plot(data[:,0]+data[:,1]/12.0+data[:,2]/365, data[:,5])
ax.axis('tight')
ax.set_title('tempeatures in Stockholm')
ax.set_xlabel('year')
ax.set_ylabel('temperature (C)');
```
Using `numpy.savetxt` we can store a Numpy array to a file in CSV format:
```
M = np.random.rand(3,3)
M
np.savetxt("../data/random-matrix.csv", M)
!cat ../data/random-matrix.csv
np.savetxt("../data/random-matrix.csv", M, fmt='%.5f') # fmt specifies the format
!cat ../data/random-matrix.csv
```
### Numpy's native file format
Useful when storing and reading back numpy array data. Use the functions `numpy.save` and `numpy.load`:
```
np.save("../data/random-matrix.npy", M)
!file ../data/random-matrix.npy
np.load("../data/random-matrix.npy")
```
## More properties of the numpy arrays
```
M.itemsize # bytes per element
M.nbytes # number of bytes
M.ndim # number of dimensions
```
## Manipulating arrays
### Indexing
We can index elements in an array using square brackets and indices:
```
# v is a vector, and has only one dimension, taking one index
v[0]
# M is a matrix, or a 2 dimensional array, taking two indices
M[1,1]
```
If we omit an index of a multidimensional array it returns the whole row (or, in general, a N-1 dimensional array)
```
M
M[1]
```
The same thing can be achieved with using `:` instead of an index:
```
M[1,:] # row 1
M[:,1] # column 1
```
We can assign new values to elements in an array using indexing:
```
M[0,0] = 1
M
# also works for rows and columns
M[1,:] = 0
M[:,2] = -1
M
```
### Index slicing
Index slicing is the technical name for the syntax `M[lower:upper:step]` to extract part of an array:
```
A = np.array([1,2,3,4,5])
A
A[1:3]
```
Array slices are *mutable*: if they are assigned a new value the original array from which the slice was extracted is modified:
```
A[1:3] = [-2,-3]
A
```
We can omit any of the three parameters in `M[lower:upper:step]`:
```
A[::] # lower, upper, step all take the default values
A[::2] # step is 2, lower and upper defaults to the beginning and end of the array
A[:3] # first three elements
A[3:] # elements from index 3
```
Negative indices counts from the end of the array (positive index from the begining):
```
A = np.array([1,2,3,4,5])
A[-1] # the last element in the array
A[-3:] # the last three elements
```
Index slicing works exactly the same way for multidimensional arrays:
```
A = np.array([[n+m*10 for n in range(5)] for m in range(5)])
A
# a block from the original array
A[1:4, 1:4]
# strides
A[::2, ::2]
```
### Fancy indexing
Fancy indexing is the name for when an array or list is used in-place of an index:
```
row_indices = [1, 2, 3]
A[row_indices]
col_indices = [1, 2, -1] # remember, index -1 means the last element
A[row_indices, col_indices]
```
We can also use index masks: If the index mask is an Numpy array of data type `bool`, then an element is selected (True) or not (False) depending on the value of the index mask at the position of each element:
```
B = np.array([n for n in range(5)])
B
row_mask = np.array([True, False, True, False, False])
B[row_mask]
# same thing
row_mask = np.array([1,0,1,0,0], dtype=bool)
B[row_mask]
```
This feature is very useful to conditionally select elements from an array, using for example comparison operators:
```
x = np.arange(0, 10, 0.5)
x
mask = (5 < x) * (x < 7.5)
mask
x[mask]
```
## Functions for extracting data from arrays and creating arrays
### where
The index mask can be converted to position index using the `where` function
```
indices = np.where(mask)
indices
x[indices] # this indexing is equivalent to the fancy indexing x[mask]
```
### diag
With the diag function we can also extract the diagonal and subdiagonals of an array:
```
np.diag(A)
np.diag(A, -1)
```
### take
The `take` function is similar to fancy indexing described above:
```
v2 = np.arange(-3,3)
v2
row_indices = [1, 3, 5]
v2[row_indices] # fancy indexing
v2.take(row_indices)
```
But `take` also works on lists and other objects:
```
np.take([-3, -2, -1, 0, 1, 2], row_indices)
```
### choose
Constructs an array by picking elements from several arrays:
```
which = [1, 0, 1, 0]
choices = [[-2,-2,-2,-2], [5,5,5,5]]
np.choose(which, choices)
```
## Linear algebra
Vectorizing code is the key to writing efficient numerical calculation with Python/Numpy. That means that as much as possible of a program should be formulated in terms of matrix and vector operations, like matrix-matrix multiplication.
### Scalar-array operations
We can use the usual arithmetic operators to multiply, add, subtract, and divide arrays with scalar numbers.
```
v1 = np.arange(0, 5)
v1 * 2
v1 + 2
A * 2, A + 2
```
### Element-wise array-array operations
When we add, subtract, multiply and divide arrays with each other, the default behaviour is **element-wise** operations:
```
A * A # element-wise multiplication
v1 * v1
```
If we multiply arrays with compatible shapes, we get an element-wise multiplication of each row:
```
A.shape, v1.shape
A * v1
```
### Matrix algebra
What about matrix mutiplication? There are two ways. We can either use the `dot` function, which applies a matrix-matrix, matrix-vector, or inner vector multiplication to its two arguments:
```
np.dot(A, A)
```
Python 3 has a new operator for using infix notation with matrix multiplication.
```
A @ A
np.dot(A, v1)
np.dot(v1, v1)
```
Alternatively, we can cast the array objects to the type `matrix`. This changes the behavior of the standard arithmetic operators `+, -, *` to use matrix algebra.
```
M = np.matrix(A)
v = np.matrix(v1).T # make it a column vector
v
M * M
M * v
# inner product
v.T * v
# with matrix objects, standard matrix algebra applies
v + M*v
```
If we try to add, subtract or multiply objects with incomplatible shapes we get an error:
```
v = np.matrix([1,2,3,4,5,6]).T
M.shape, v.shape
import traceback
try:
M * v
except ValueError as e:
print(traceback.format_exc())
```
See also the related functions: `inner`, `outer`, `cross`, `kron`, `tensordot`. Try for example `help(np.kron)`.
### Array/Matrix transformations
Above we have used the `.T` to transpose the matrix object `v`. We could also have used the `transpose` function to accomplish the same thing.
Other mathematical functions that transform matrix objects are:
```
C = np.matrix([[1j, 2j], [3j, 4j]])
C
np.conjugate(C)
```
Hermitian conjugate: transpose + conjugate
```
C.H
```
We can extract the real and imaginary parts of complex-valued arrays using `real` and `imag`:
```
np.real(C) # same as: C.real
np.imag(C) # same as: C.imag
```
Or the complex argument and absolute value
```
np.angle(C+1) # heads up MATLAB Users, angle is used instead of arg
abs(C)
```
### Matrix computations
#### Inverse
```
np.linalg.inv(C) # equivalent to C.I
C.I * C
```
#### Determinant
```
np.linalg.det(C)
np.linalg.det(C.I)
```
### Data processing
Often it is useful to store datasets in Numpy arrays. Numpy provides a number of functions to calculate statistics of datasets in arrays.
For example, let's calculate some properties from the Stockholm temperature dataset used above.
```
# reminder, the tempeature dataset is stored in the data variable:
np.shape(data)
```
#### mean
```
# the temperature data is in column 3
np.mean(data[:,3])
```
The daily mean temperature in Stockholm over the last 200 years has been about 6.2 C.
#### standard deviations and variance
```
np.std(data[:,3]), np.var(data[:,3])
```
#### min and max
```
# lowest daily average temperature
data[:,3].min()
# highest daily average temperature
data[:,3].max()
```
#### sum, prod, and trace
```
d = np.arange(0, 10)
d
# sum up all elements
np.sum(d)
# product of all elements
np.prod(d+1)
# cummulative sum
np.cumsum(d)
# cummulative product
np.cumprod(d+1)
# same as: diag(A).sum()
np.trace(A)
```
### Computations on subsets of arrays
We can compute with subsets of the data in an array using indexing, fancy indexing, and the other methods of extracting data from an array (described above).
For example, let's go back to the temperature dataset:
```
!head -n 3 ../data/stockholm_td_adj.dat
```
The dataformat is: year, month, day, daily average temperature, low, high, location.
If we are interested in the average temperature only in a particular month, say February, then we can create a index mask and use it to select only the data for that month using:
```
np.unique(data[:,1]) # the month column takes values from 1 to 12
mask_feb = data[:,1] == 2
# the temperature data is in column 3
np.mean(data[mask_feb,3])
```
With these tools we have very powerful data processing capabilities at our disposal. For example, to extract the average monthly average temperatures for each month of the year only takes a few lines of code:
```
months = np.arange(1,13)
monthly_mean = [np.mean(data[data[:,1] == month, 3]) for month in months]
fig, ax = plt.subplots()
ax.bar(months, monthly_mean)
ax.set_xlabel("Month")
ax.set_ylabel("Monthly avg. temp.");
```
### Calculations with higher-dimensional data
When functions such as `min`, `max`, etc. are applied to a multidimensional arrays, it is sometimes useful to apply the calculation to the entire array, and sometimes only on a row or column basis. Using the `axis` argument we can specify how these functions should behave:
```
m = np.random.rand(3,3)
m
# global max
m.max()
# max in each column
m.max(axis=0)
# max in each row
m.max(axis=1)
```
Many other functions and methods in the `array` and `matrix` classes accept the same (optional) `axis` keyword argument.
## Reshaping, resizing and stacking arrays
The shape of an Numpy array can be modified without copying the underlaying data, which makes it a fast operation even for large arrays.
```
A
n, m = A.shape
B = A.reshape((1,n*m))
B
B[0,0:5] = 5 # modify the array
B
A # and the original variable is also changed. B is only a different view of the same data
```
We can also use the function `flatten` to make a higher-dimensional array into a vector. But this function create a copy of the data.
```
B = A.flatten()
B
B[0:5] = 10
B
A # now A has not changed, because B's data is a copy of A's, not refering to the same data
```
## Adding a new dimension: newaxis
With `newaxis`, we can insert new dimensions in an array, for example converting a vector to a column or row matrix:
```
v = np.array([1,2,3])
v.shape
# make a column matrix of the vector v
v[:, np.newaxis]
# column matrix
v[:, np.newaxis].shape
# row matrix
v[np.newaxis, :].shape
```
## Stacking and repeating arrays
Using function `repeat`, `tile`, `vstack`, `hstack`, and `concatenate` we can create larger vectors and matrices from smaller ones:
### tile and repeat
```
a = np.array([[1, 2], [3, 4]])
# repeat each element 3 times
np.repeat(a, 3)
# tile the matrix 3 times
np.tile(a, 3)
```
### concatenate
```
b = np.array([[5, 6]])
np.concatenate((a, b), axis=0)
np.concatenate((a, b.T), axis=1)
```
### hstack and vstack
```
np.vstack((a,b))
np.hstack((a,b.T))
```
## Copy and "deep copy"
To achieve high performance, assignments in Python usually do not copy the underlaying objects. This is important for example when objects are passed between functions, to avoid an excessive amount of memory copying when it is not necessary (technical term: pass by reference).
```
A = np.array([[1, 2], [3, 4]])
A
# now B is referring to the same array data as A
B = A
# changing B affects A
B[0,0] = 10
B
A
```
If we want to avoid this behavior, so that when we get a new completely independent object `B` copied from `A`, then we need to do a so-called "deep copy" using the function `copy`:
```
B = np.copy(A)
# now, if we modify B, A is not affected
B[0,0] = -5
B
A
```
## Iterating over array elements
Generally, we want to avoid iterating over the elements of arrays whenever we can (at all costs). The reason is that in a interpreted language like Python (or MATLAB/R), iterations are really slow compared to vectorized operations.
However, sometimes iterations are unavoidable. For such cases, the Python `for` loop is the most convenient way to iterate over an array:
```
v = np.array([1,2,3,4])
for element in v:
print(element)
M = np.array([[1,2], [3,4]])
for row in M:
print("row", row)
for element in row:
print(element)
```
When we need to iterate over each element of an array and modify its elements, it is convenient to use the `enumerate` function to obtain both the element and its index in the `for` loop:
```
for row_idx, row in enumerate(M):
print("row_idx", row_idx, "row", row)
for col_idx, element in enumerate(row):
print("col_idx", col_idx, "element", element)
# update the matrix M: square each element
M[row_idx, col_idx] = element ** 2
# each element in M is now squared
M
```
## Vectorizing functions
As mentioned several times by now, to get good performance we should try to avoid looping over elements in our vectors and matrices, and instead use vectorized algorithms. The first step in converting a scalar algorithm to a vectorized algorithm is to make sure that the functions we write work with vector inputs.
```
def theta(x):
"""
Scalar implemenation of the Heaviside step function.
"""
if x >= 0:
return 1
else:
return 0
try:
theta(np.array([-3,-2,-1,0,1,2,3]))
except Exception as e:
print(traceback.format_exc())
```
OK, that didn't work because we didn't write the `Theta` function so that it can handle a vector input...
To get a vectorized version of Theta we can use the Numpy function `vectorize`. In many cases it can automatically vectorize a function:
```
theta_vec = np.vectorize(theta)
%%time
theta_vec(np.array([-3,-2,-1,0,1,2,3]))
```
We can also implement the function to accept a vector input from the beginning (requires more effort but might give better performance):
```
def theta(x):
"""
Vector-aware implemenation of the Heaviside step function.
"""
return 1 * (x >= 0)
%%time
theta(np.array([-3,-2,-1,0,1,2,3]))
# still works for scalars as well
theta(-1.2), theta(2.6)
```
## Using arrays in conditions
When using arrays in conditions,for example `if` statements and other boolean expressions, one needs to use `any` or `all`, which requires that any or all elements in the array evalutes to `True`:
```
M
if (M > 5).any():
print("at least one element in M is larger than 5")
else:
print("no element in M is larger than 5")
if (M > 5).all():
print("all elements in M are larger than 5")
else:
print("all elements in M are not larger than 5")
```
## Type casting
Since Numpy arrays are *statically typed*, the type of an array does not change once created. But we can explicitly cast an array of some type to another using the `astype` functions (see also the similar `asarray` function). This always create a new array of new type:
```
M.dtype
M2 = M.astype(float)
M2
M2.dtype
M3 = M.astype(bool)
M3
```
## Further reading
* http://numpy.scipy.org - Official Numpy Documentation
* http://scipy.org/Tentative_NumPy_Tutorial - Official Numpy Quickstart Tutorial (highly recommended)
* http://www.scipy-lectures.org/intro/numpy/index.html - Scipy Lectures: Lecture 1.3
## Versions
```
%reload_ext version_information
%version_information numpy
```
| github_jupyter |
# Transporter analysis of bacillus mother-spore
```
from __future__ import print_function, division, absolute_import
import sys
import qminospy
from qminospy.me2 import ME_NLP
# python imports
from copy import copy
import re
from os.path import join, dirname, abspath
import sys
sys.path.append('/home/UCSD/cobra_utils')
from collections import defaultdict
import pickle
# third party imports
import pandas
import cobra
from tqdm import tqdm
import numpy as np
import scipy
# COBRAme
import cobrame
from cobrame.util import building, mu, me_model_interface
from cobrame.io.json import save_json_me_model, save_reduced_json_me_model
# ECOLIme
import bacillusme
from bacillusme import (transcription, translation, flat_files, generics, formulas, compartments)
from cobrame.util.helper_functions import *
import copy
from scipy import stats
import matplotlib.pyplot as plt
%load_ext autoreload
%autoreload 2
print(cobra.__file__)
print(cobrame.__file__)
print(bacillusme.__file__)
ecoli_files = dirname(abspath(bacillusme.__file__))
pd.set_option('display.max_colwidth', None)
with open("../../me_models/solution.pickle", "rb") as outfile:
me = pickle.load(outfile)
```
### Closing mechanisms
```
with open("./sporeme_solution_v3.pickle", "rb") as outfile:
sporeme = pickle.load(outfile)
sporeme.solution.x_dict['biomass_dilution_s']
main_mechanisms = [ 'ACKr_REV_BSU29470-MONOMER',
'PGK_REV_BSU33930-MONOMER',
'PYK_FWD_BSU29180-MONOMER_mod_mn2_mod_k']
for r in main_mechanisms:
sporeme.reactions.get_by_id(r).bounds = (0,0)
sporeme.reactions.get_by_id(r+'_s').bounds = (0,0)
version = 'v5_KO_ACK_PGK_PYK'
solve_me_model(sporeme, max_mu = 0.1, min_mu = .01, using_soplex=False, precision = 1e-3,growth_key = 'sigma')
sporeme.solution.x_dict['biomass_dilution_s']
sporeme.reactions.get_by_id('PRPPS_REV_BSU00510-MONOMER_mod_mn2_mod_pi_s').bounds = (0,0)
solve_me_model(sporeme, max_mu = 0.1, min_mu = .01, using_soplex=False, precision = 1e-3,growth_key = 'sigma')
if sporeme.solution: sporeme.solution.x_dict['biomass_dilution_s']
```
### GK
```
with open("./sporeme_solution_v3.pickle", "rb") as outfile:
sporeme = pickle.load(outfile)
for r in sporeme.reactions.query(re.compile('BSU15680-MONOMER.*_s$')):
print(r.id)
r.bounds = (0,0)
solve_me_model(sporeme, max_mu = 0.1, min_mu = .01, using_soplex=False, precision = 1e-3,growth_key = 'sigma')
if sporeme.solution: sporeme.solution.x_dict['biomass_dilution_s']
flux_based_reactions(sporeme,'fum_c',only_types=['MetabolicReaction']).head(10)
```
### CYTK
```
with open("./sporeme_solution_v3.pickle", "rb") as outfile:
sporeme = pickle.load(outfile)
for r in sporeme.reactions.query('BSU22890-MONOMER'):
print(r.id)
r.bounds = (0,0)
for r in sporeme.reactions.query(re.compile('BSU37150-MONOMER.*_s$')):
print(r.id,r.reaction)
r.bounds = (0,0)
solve_me_model(sporeme, max_mu = 0.1, min_mu = .01, using_soplex=False, precision = 1e-3,growth_key = 'sigma')
if sporeme.solution: sporeme.solution.x_dict['biomass_dilution_s']
flux_based_reactions(sporeme,'ctp_s',only_types=['MetabolicReaction'])
flux_based_reactions(sporeme,'cbp_c',only_types=['MetabolicReaction'])
```
### Methionine
```
with open("./sporeme_solution_v3.pickle", "rb") as outfile:
sporeme = pickle.load(outfile)
for r in get_transport_reactions(sporeme,'met__L_s',comps=['c','s']):
print(r.id)
r.bounds = (0,0)
solve_me_model(sporeme, max_mu = 0.1, min_mu = .01, using_soplex=False, precision = 1e-3,growth_key = 'sigma')
if sporeme.solution: print(sporeme.solution.x_dict['biomass_dilution_s'])
met = 'suchms_s'
print(sporeme.metabolites.get_by_id(met).name)
flux_based_reactions(sporeme,met,only_types=['MetabolicReaction'])
```
### Mechanisms
```
with open("./sporeme_solution_v3.pickle", "rb") as outfile:
sporeme = pickle.load(outfile)
main_mechanisms = [ 'ACKr_REV_BSU29470-MONOMER_s',
'PGK_REV_BSU33930-MONOMER_s',
'PYK_FWD_BSU29180-MONOMER_mod_mn2_mod_k_s',
'PRPPS_REV_BSU00510-MONOMER_mod_mn2_mod_pi_s']
for r in main_mechanisms:
sporeme.reactions.get_by_id(r).bounds = (0,0)
solve_me_model(sporeme, max_mu = 0.1, min_mu = .01, using_soplex=False, precision = 1e-6,growth_key = 'sigma')
sporeme.solution
with open("./sporeme_solution_{}.pickle".format(version), "wb") as outfile:
pickle.dump(sporeme, outfile)
# Previously identified essential metabolites
exchange_list = ['4fe4s_s','2fe2s_s','udcpp_s','pydx5p_s','3fe4s_s','cl_s','sheme_s','cu_s','mn2_s',
'bmocogdp_s','dpm_s','thmpp_s','zn2_s','cbl1_s','cobalt2_s']
additional = [m.id for m in sporeme.metabolites if isinstance(m,cobrame.Metabolite)]
transported_metabolites = exchange_list+additional
# Get transport reactions
def get_compartments(r):
comps = []
if isinstance(r,cobrame.MetabolicReaction):
for m in r.metabolites:
if isinstance(m,cobrame.Metabolite):
comps.append(m.id[-1])
return list(set(comps))
def get_all_transport(model):
transport_reactions = []
for r in tqdm(model.reactions):
comps = get_compartments(r)
if len(comps) > 1 and 's' in comps:
transport_reactions.append(r.id)
return list(set(transport_reactions))
def get_active_transport(transport_reactions):
active_transporters = []
for r in tqdm(transport_reactions):
if 'SPONT' not in r and abs(sporeme.solution.x_dict[r])>0.:
active_transporters.append(r)
# Include arginine transport
arginine_transport = [r.id for r in get_transport_reactions(sporeme,'arg__L_c',comps=['c','s'])+get_transport_reactions(sporeme,'arg__L_c',comps=['s','c'])]
[active_transporters.append(r) for r in arginine_transport]
active_transporters = list(set(active_transporters))
return active_transporters
```
## Check by group of transporters of metabolite
```
def get_necessary_metabolites(model,active_transporters):
necessary_metabolites = []
for r in tqdm(active_transporters):
rxn = model.reactions.get_by_id(r)
for m in rxn.products:
if not isinstance(m,cobrame.Metabolite):
continue
met_root = m.id[:-2]
for i in rxn.reactants:
if met_root in i.id:
necessary_metabolites.append(m.id)
return list(set(necessary_metabolites))
def get_all_available_transport(model,necessary_metabolites):
available_transport = []
at_dict = {}
for m in tqdm(necessary_metabolites):
rxns = get_transport_reactions(model,m,comps=['c','s']) + get_transport_reactions(model,m,comps=['s','c'])
[available_transport.append(r.id) for r in rxns]
at_dict[m] = []
[at_dict[m].append(r.id) for r in rxns]
return list(set(available_transport)), at_dict
# Previously identified essential metabolites
exchange_list = ['4fe4s_s','2fe2s_s','udcpp_s','pydx5p_s','3fe4s_s','cl_s','sheme_s','cu_s','mn2_s',
'bmocogdp_s','dpm_s','thmpp_s','zn2_s','cbl1_s','cobalt2_s']
additional = [m.id for m in sporeme.metabolites if isinstance(m,cobrame.Metabolite)]
transported_metabolites = exchange_list+additional
transport_reactions = get_all_transport(sporeme)
print('{} transport reactions identified'.format(len(transport_reactions)))
active_transporters = get_active_transport(transport_reactions)
necessary_metabolites = get_necessary_metabolites(sporeme,active_transporters)
necessary_metabolites.remove('h_s')
necessary_metabolites.remove('h_c')
available_transport, at_dict = get_all_available_transport(sporeme,necessary_metabolites)
print('{} active transport reactions identified'.format(len(active_transporters)))
print('{} necessary metabolites identified'.format(len(necessary_metabolites)))
print('{} available transport reactions identified'.format(len(available_transport)))
all_transporters_to_open = list(set(active_transporters + available_transport))
print('{} open transport reactions identified'.format(len(all_transporters_to_open)))
print('Included {}'.format(set(active_transporters)-set(available_transport)))
for r in transport_reactions:
if r not in all_transporters_to_open and 'SPONT' not in r:
rxn = sporeme.reactions.get_by_id(r)
rxn.upper_bound = 0
rxn.lower_bound = 0
solve_me_model(sporeme, max_mu = 0.1, min_mu = .01, using_soplex=False, precision = 1e-6,growth_key = 'sigma')
from bacillusme.analysis import sensitivity as ss
flux_results_df = ss.transporter_knockout(sporeme,necessary_metabolites, \
NP=20,solution=1,biomass_dilution='biomass_dilution_s',\
growth_key = 'sigma',single_change_function='group_knockout')
flux_results_df.to_csv('group_KO_flux_results_{}.csv'.format(version))
flux_results_df = pd.read_csv('group_KO_flux_results_{}.csv'.format(version),index_col=0)
flux_results_df.loc['biomass_dilution_s'].sort_values().plot.bar(figsize=(12 ,4))
plt.tight_layout()
plt.savefig("group_KO_flux_results_{}.svg".format(version), format="SVG")
```
### Close metabolite one by one
Including information about arginine being transported
```
with open("./sporeme_solution_{}.pickle".format(version), "rb") as outfile:
sporeme = pickle.load(outfile)
for r in transport_reactions:
if r not in all_transporters_to_open and 'SPONT' not in r:
rxn = sporeme.reactions.get_by_id(r)
rxn.upper_bound = 0
rxn.lower_bound = 0
flux_results_df = pd.read_csv('group_KO_flux_results_{}.csv'.format(version),index_col=0)
sorted_mets = flux_results_df.loc['biomass_dilution_s'].sort_values(ascending=False).drop('base').index.to_list()
sorted_mets.remove('arg__L_s')
sorted_mets.append('arg__L_s')
from bacillusme.analysis import sensitivity as ss
flux_results_df = ss.transporter_knockout(sporeme,sorted_mets, \
NP=20,solution=1,biomass_dilution='biomass_dilution_s',\
growth_key = 'sigma',single_change_function='group_knockout',sequential=True)
flux_results_df.to_csv('group_1by1_KO_flux_results_{}.csv'.format(version))
flux_results_df = pd.read_csv('group_1by1_KO_flux_results_{}.csv'.format(version),index_col=0)
flux_results_df.loc['biomass_dilution_s',sorted_mets[::-1]].plot.bar(figsize=(12,4))
plt.tight_layout()
plt.savefig("group_1by1_KO_flux_results_{}.svg".format(version), format="SVG")
```
# Cases
```
pd.set_option('display.max_colwidth', None)
```
### Original
```
# CYTK2 KO
version = 'v4'
flux_results_df = pd.read_csv('group_KO_flux_results_{}.csv'.format(version),index_col=0)
flux_results_df.loc['biomass_dilution_s'].sort_values().plot.bar(figsize=(12 ,4))
flux_results_df = pd.read_csv('group_1by1_KO_flux_results_{}.csv'.format(version),index_col=0)
sorted_mets = flux_results_df.loc['biomass_dilution_s'].sort_values(ascending=True)
last_met = sorted_mets.index[list(sorted_mets.index).index(sorted_mets[sorted_mets<1e-5].index[-1])+1]
print(last_met)
flux_dict = flux_results_df[last_met].to_dict() # Last time before model breaks
flux_results_df = pd.read_csv('group_1by1_KO_flux_results_{}.csv'.format(version),index_col=0)
flux_results_df.loc['biomass_dilution_s',sorted_mets.index[::-1]].plot.bar(figsize=(12,4))
plt.tight_layout()
flux_dict['biomass_dilution']
met='atp_s' # ATP production and glucose uptake
prod_atp_df = flux_based_reactions(sporeme,met,flux_dict=flux_dict,only_types=['MetabolicReaction'])
prod_atp_df = prod_atp_df[prod_atp_df['met_flux']>0]
prod_atp_df['met_flux'].sum()
prod_atp_df['met_flux'].div(prod_atp_df['met_flux'].sum())
```
### All mechanisms KO
```
version = 'v5_all_KO'
flux_results_df = pd.read_csv('group_KO_flux_results_{}.csv'.format(version),index_col=0)
flux_results_df.loc['biomass_dilution_s'].sort_values().plot.bar(figsize=(12 ,4))
flux_results_df = pd.read_csv('group_1by1_KO_flux_results_{}.csv'.format(version),index_col=0)
sorted_mets = flux_results_df.loc['biomass_dilution_s'].sort_values(ascending=True)
last_met = sorted_mets.index[list(sorted_mets.index).index(sorted_mets[sorted_mets<1e-5].index[-1])+1]
print(last_met)
flux_dict = flux_results_df[last_met].to_dict() # Last time before model breaks
flux_results_df = pd.read_csv('group_1by1_KO_flux_results_{}.csv'.format(version),index_col=0)
flux_results_df.loc['biomass_dilution_s',sorted_mets.index[::-1]].plot.bar(figsize=(12,4))
plt.tight_layout()
flux_dict['biomass_dilution']
met='atp_s' # ATP production and glucose uptake
prod_atp_df = flux_based_reactions(sporeme,met,flux_dict=flux_dict,only_types=['MetabolicReaction'])
prod_atp_df = prod_atp_df[prod_atp_df['met_flux']>0]
prod_atp_df['met_flux'].sum()
prod_atp_df['met_flux'].div(prod_atp_df['met_flux'].sum())
flux_based_reactions(sporeme,met,flux_dict=flux_dict,only_types=['MetabolicReaction'])
flux_based_reactions(sporeme,'prpp_s',flux_dict=flux_dict,only_types=['MetabolicReaction'])
sporeme.metabolites.prpp_s.name
```
| github_jupyter |
# Data formats 1 - introduction
## [Download exercises zip](../_static/generated/formats.zip)
[Browse files online](https://github.com/DavidLeoni/softpython-en/tree/master/formats)
## Introduction
In these tutorials we will see how to load and write tabular data such as CSV, and we will mention tree-like data such as JSON files. We will also spend a couple of words about opendata catalogs and licenses (creative commons).
In these tutorials we will review main data formats:
Textual formats
* Line files
* CSV (tabular data)
* JSON (tree-like data, just mention)
Binary formats (just mention)
* fogli Excel
We will also mention open data catalogs and licenses (Creative Commons)
### What to do
1. unzip exercises in a folder, you should get something like this:
```
formats
formats1-lines.ipynb
formats1-lines-sol.ipynb
formats2-csv.ipynb
formats2-csv-sol.ipynb
formats3-json.ipynb
formats3-json-sol.ipynb
formats4-chal.ipynb
jupman.py
```
<div class="alert alert-warning">
**WARNING**: to correctly visualize the notebook, it MUST be in an unzipped folder !
</div>
2. open Jupyter Notebook from that folder. Two things should open, first a console and then browser. The browser should show a file list: navigate the list and open the notebook `formats/formats1-lines.ipynb`
3. Go on reading that notebook, and follow instuctions inside.
Shortcut keys:
- to execute Python code inside a Jupyter cell, press `Control + Enter`
- to execute Python code inside a Jupyter cell AND select next cell, press `Shift + Enter`
- to execute Python code inside a Jupyter cell AND a create a new cell aftwerwards, press `Alt + Enter`
- If the notebooks look stuck, try to select `Kernel -> Restart`
## Line files
Line files are typically text files which contain information grouped by lines. An example using historical characters might be like the following:
```
Leonardo
da Vinci
Sandro
Botticelli
Niccolò
Macchiavelli
```
We can immediately see a regularity: first two lines contain data of Leonardo da Vinci, second one the name and then the surname. Successive lines instead have data of Sandro Botticelli, with again first the name and then the surname and so on.
We might want to do a program that reads the lines and prints on the terminal names and surnames like the following:
```
Leonardo da Vinci
Sandro Botticelli
Niccolò Macchiavelli
```
To start having an approximation of the final result, we can open the file, read only the first line and print it:
```
with open('people-simple.txt', encoding='utf-8') as f:
line=f.readline()
print(line)
```
What happened? Let's examing first rows:
### open command
The command
```python
open('people-simple.txt', encoding='utf-8')
```
allows us to open the text file by telling PYthon the file path `'people-simple.txt'` and the encoding in which it was written (`encoding='utf-8'`).
### The encoding
The encoding dependes on the operating system and on the editor used to write the file. When we open a file, Python is not capable to divine the encoding, and if we do not specify anything Python might open the file assuming an encoding different from the original - in other words, if we omit the encoding (or we put a wrong one) we might end up seeing weird characters (like little squares instead of accented letters).
In general, when you open a file, try first to specify the encoding `utf-8` which is the most common one. If it doesn't work try others, for example for files written in south Europe with Windows you might check `encoding='latin-1'`. If you open a file written elsewhere, you might need other encodings. For more in-depth information, you can read [Dive into Python - Chapter 4 - Strings](https://diveintopython3.problemsolving.io/strings.html), and [Dive into Python - Chapter 11 - File](https://diveintopython3.problemsolving.io/files.html), **both of which are extremely recommended readings**.
### with block
The `with` defines a block with instructions inside:
```python
with open('people-simple.txt', encoding='utf-8') as f:
line=f.readline()
print(line)
```
We used the `with` to tell PYthon that in any case, even if errors occur, we want that after having used the file, that is after having executed the instructions inside the internal block (the `line=f.readline()` and `print(line)`) Python must automatically close the file. Properly closing a file avoids to waste memory resources and creating hard to find paranormal errors. If you want to avoid hunting for never closed zombie files, always remember to open all files in `with` blocks! Furthermore, at the end of the row in the part `as f:` we assigned the file to a variable hereby called `f`, but we could have used any other name we liked.
<div class="alert alert-warning">
**WARNING**: To indent the code, ALWAYS use sequences of four white spaces. Sequences of 2 spaces. Sequences of only 2 spaces even if allowed are not recommended.
</div>
<div class="alert alert-warning">
**WARNING**: Depending on the editor you use, by pressing TAB you might get a sequence o f white spaces like it happens in Jupyter (4 spaces which is the recommended length), or a special tabulation character (to avoid)! As much as this annoying this distinction might appear, remember it because it might generate very hard to find errors.
</div>
<div class="alert alert-warning">
**WARNING**: In the commands to create blocks such as `with`, always remember to put the character of colon `:` at the end of the line !
</div>
The command
```
line=f.readline()
```
puts in the variable `line` the entire line, like a string. Warning: the string will contain at the end the special character of line return !
You might wonder where that `readline` comes from. Like everything in Python, our variable `f` which represents the file we just opened is an object, and like any object, depending on its type, it has particular methods we can use on it. In this case the method is `readline`.
The following command prints the string content:
```python
print(line)
```
**✪ 1.1 EXERCISE**: Try to rewrite here the block we've just seen, and execute the cell by pressing Control-Enter. Rewrite the code with the fingers, not with copy-paste ! Pay attention to correct indentation with spaces in the block.
```
# write here
with open('people-simple.txt', encoding='utf-8') as f:
line=f.readline()
print(line)
```
**✪ 1.2 EXERCISE**: you might wondering what exactly is that `f`, and what exatly the method `readlines` should be doing. When you find yourself in these situations, you might help yourself with functions `type` and `help`. This time, directly copy paste the same code here, but insert inside `with` block the commands:
* `print(type(f))`
* `help(f)`
* `help(f.readline)` # Attention: remember the f. before the readline !!
Every time you add something, try to execute with Control+Enter and see what happens
```
# write here the code (copy and paste)
with open('people-simple.txt', encoding='utf-8') as f:
line=f.readline()
print(line)
print(type(f))
help(f.readline)
help(f)
```
First we put the content of the first line into the variable `line`, now we might put it in a variable witha more meaningful name, like `name`. Also, we can directly read the next row into the variable `surname` and then print the concatenation of both:
```
with open('people-simple.txt', encoding='utf-8') as f:
name=f.readline()
surname=f.readline()
print(name + ' ' + surname)
```
**PROBLEM !** The printing puts a weird carriage return. Why is that? If you remember, first we said that `readline` reads the line content in a string adding to the end also the special newline character. To eliminate it, you can use the command `rstrip()`:
```
with open('people-simple.txt', encoding='utf-8') as f:
name=f.readline().rstrip()
surname=f.readline().rstrip()
print(name + ' ' + surname)
```
**✪ 1.3 EXERCISE**: Again, rewrite the block above in the cell below, ed execute the cell with Control+Enter. Question: what happens if you use `strip()` instead of `rstrip()`? What about `lstrip()`? Can you deduce the meaning of `r` and `l`? If you can't manage it, try to use python command `help` by calling `help(string.rstrip)`
```
# write here
with open('people-simple.txt', encoding='utf-8') as f:
name=f.readline().rstrip()
surname=f.readline().rstrip()
print(name + ' ' + surname)
```
Very good, we have the first line ! Now we can read all the lines in sequence. To this end, we can use a `while` cycle:
```
with open('people-simple.txt', encoding='utf-8') as f:
line=f.readline()
while line != "":
name = line.rstrip()
surname=f.readline().rstrip()
print(name + ' ' + surname)
line=f.readline()
```
<div class="alert alert-info">
**NOTE**: In Python there are [shorter ways](https://thispointer.com/5-different-ways-to-read-a-file-line-by-line-in-python/)
to read a text file line by line, we used this approach to make explicit all passages.
</div>
What did we do? First, we added a `while` cycle in a new block
<div class="alert alert-warning">
**WARNING**: In new block, since it is already within the external `with`, the instructions are indented of 8 spaces and not 4! If you use the wrong spaces, bad things happen !
</div>
We first read a line, and two cases are possible:
a. we are the end of the file (or file is empty) : in this case `readline()` call returns an empty string
b. we are not at the end of the file: the first line is put as a string inside the variable `line`. Since Python internally uses a pointer to keep track at which position we are when reading inside the file, after the read such pointer is moved at the beginning of the next line. This way the next call to `readline()` will read a line from the new position.
In `while` block we tell Python to continue the cycle as long as `line` is _not_ empty. If this is the case, inside the `while` block we parse the name from the line and put it in variable `name` (removing extra newline character with `rstrip()` as we did before), then we proceed reading the next line and parse the result inside the `surname` variable. Finally, we read again a line into the `line` variable so it will be ready for the next round of name extraction. If line is empty the cycle will terminate:
```python
while line != "": # enter cycle if line contains characters
name = line.rstrip() # parses the name
surname=f.readline().rstrip() # reads next line and parses surname
print(name + ' ' + surname)
line=f.readline() # read next line
```
**✪ 1.4 EXERCISE**: As before, rewrite in the cell below the code with the `while`, paying attention to the indentation (for the external `with` line use copy-and-paste):
```
# write here the code of internal while
with open('people-simple.txt', encoding='utf-8') as f:
line=f.readline()
while line != "":
name = line.rstrip()
surname=f.readline().rstrip()
print(name + ' ' + surname)
line=f.readline()
```
## people-complex line file
Look at the file `people-complex.txt`:
```
name: Leonardo
surname: da Vinci
birthdate: 1452-04-15
name: Sandro
surname: Botticelli
birthdate: 1445-03-01
name: Niccolò
surname: Macchiavelli
birthdate: 1469-05-03
```
Supposing to read the file to print this output, how would you do it?
```
Leonardo da Vinci, 1452-04-15
Sandro Botticelli, 1445-03-01
Niccolò Macchiavelli, 1469-05-03
```
**Hint 1**: to obtain the string `'abcde'`, the substring `'cde'`, which starts at index 2, you can ue the operator square brackets, using the index followed by colon `:`
```
x = 'abcde'
x[2:]
x[3:]
```
**Hint 2**: To know the length of a string, use the function `len`:
```
len('abcde')
```
**✪ 1.5 EXERCISE**: Write here the solution of the exercise 'People complex':
```
# write here
with open('people-complex.txt', encoding='utf-8') as f:
line=f.readline()
while line != "":
name = line.rstrip()[len("name: "):]
surname= f.readline().rstrip()[len("surname: "):]
born = f.readline().rstrip()[len("birthdate: "):]
print(name + ' ' + surname + ', ' + born)
line=f.readline()
```
## Exercise - line file immersione-in-python-toc
✪✪✪ This exercise is more challenging, if you are a beginner you might skip it and go on to CSVs
The book Dive into Python is nice and for the italian version there is a PDF, which has a problem though: if you try to print it, you will discover that the index is missing. Without despairing, we found a program to extract titles in a file as follows, but you will discover it is not exactly nice to see. Since we are Python ninjas, we decided to transform raw titles in a [real table of contents](http://softpython.readthedocs.io/it/latest/_static/toc-immersione-in-python-3.txt). Sure enough there are smarter ways to do this, like loading the pdf in Python with an appropriate module for pdfs, still this makes for an interesting exercise.
You are given the file `immersione-in-python-toc.txt`:
```
BookmarkBegin
BookmarkTitle: Il vostro primo programma Python
BookmarkLevel: 1
BookmarkPageNumber: 38
BookmarkBegin
BookmarkTitle: Immersione!
BookmarkLevel: 2
BookmarkPageNumber: 38
BookmarkBegin
BookmarkTitle: Dichiarare funzioni
BookmarkLevel: 2
BookmarkPageNumber: 41
BookmarkBeginint
BookmarkTitle: Argomenti opzionali e con nome
BookmarkLevel: 3
BookmarkPageNumber: 42
BookmarkBegin
BookmarkTitle: Scrivere codice leggibile
BookmarkLevel: 2
BookmarkPageNumber: 44
BookmarkBegin
BookmarkTitle: Stringhe di documentazione
BookmarkLevel: 3
BookmarkPageNumber: 44
BookmarkBegin
BookmarkTitle: Il percorso di ricerca di import
BookmarkLevel: 2
BookmarkPageNumber: 46
BookmarkBegin
BookmarkTitle: Ogni cosa è un oggetto
BookmarkLevel: 2
BookmarkPageNumber: 47
```
Write a python program to print the following output:
```
Il vostro primo programma Python 38
Immersione! 38
Dichiarare funzioni 41
Argomenti opzionali e con nome 42
Scrivere codice leggibile 44
Stringhe di documentazione 44
Il percorso di ricerca di import 46
Ogni cosa è un oggetto 47
```
For this exercise, you will need to insert in the output artificial spaces, in a qunatity determined by the rows `BookmarkLevel`
**QUESTION**: what's that weird value `è` at the end of the original file? Should we report it in the output?
**HINT 1**: To convert a string into an integer number, use the function `int`:
```
x = '5'
x
int(x)
```
<div class="alert alert-warning">
**Warning**: `int(x)` returns a value, and never modifies the argument `x`!
</div>
**HINT 2**: To substitute a substring in a string, you can use the method `.replace`:
```
x = 'abcde'
x.replace('cd', 'HELLO' )
```
**HINT 3**: while there is only one sequence to substitute, `replace` is fine, but if we had a milion of horrible sequences like `>`, `>`, `&x3e;`, what should we do? As good data cleaners, we recognize these are [HTML escape sequences](https://corsidia.com/materia/web-design/caratterispecialihtml), so we could use methods specific to sequences like [html.escape](https://docs.python.org/3/library/html.html#html.unescape). TRy it instead of `replace` and check if it works!
NOTE: Before using `html.unescape`, import the module `html` with the command:
```python
import html
```
**HINT 4**: To write _n_ copies of a character, use `*` like this:
```
"b" * 3
"b" * 7
```
**IMPLEMENTATION**: Write here the solution for the line file `immersione-in-python-toc.txt`, and try execute it by pressing Control + Enter:
```
# write here
import html
with open("immersione-in-python-toc.txt", encoding='utf-8') as f:
line=f.readline()
while line != "":
line = f.readline().strip()
title = html.unescape(line[len("BookmarkTitle: "):])
line=f.readline().strip()
level = int(line[len("BookmarkLevel: "):])
line=f.readline().strip()
page = line[len("BookmarkPageNumber: "):]
print((" " * level) + title + " " + page)
line=f.readline()
```
## Continue
Go on with [CSV tabular files](https://en.softpython.org/formats/formats2-csv-sol.html)
| 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.
```
# 用 tf.data 加载 CSV 数据
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://tensorflow.google.cn/tutorials/load_data/csv"><img src="https://tensorflow.google.cn/images/tf_logo_32px.png" />在 Tensorflow.org 上查看</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/zh-cn/tutorials/load_data/csv.ipynb"><img src="https://tensorflow.google.cn/images/colab_logo_32px.png" />在 Google Colab 运行</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/zh-cn/tutorials/load_data/csv.ipynb"><img src="https://tensorflow.google.cn/images/GitHub-Mark-32px.png" />在 Github 上查看源代码</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/site/zh-cn/tutorials/load_data/csv.ipynb"><img src="https://tensorflow.google.cn/images/download_logo_32px.png" />下载此 notebook</a>
</td>
</table>
Note: 我们的 TensorFlow 社区翻译了这些文档。因为社区翻译是尽力而为, 所以无法保证它们是最准确的,并且反映了最新的
[官方英文文档](https://www.tensorflow.org/?hl=en)。如果您有改进此翻译的建议, 请提交 pull request 到
[tensorflow/docs](https://github.com/tensorflow/docs) GitHub 仓库。要志愿地撰写或者审核译文,请加入
[docs-zh-cn@tensorflow.org Google Group](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-zh-cn)。
这篇教程通过一个示例展示了怎样将 CSV 格式的数据加载进 `tf.data.Dataset`。
这篇教程使用的是泰坦尼克号乘客的数据。模型会根据乘客的年龄、性别、票务舱和是否独自旅行等特征来预测乘客生还的可能性。
## 设置
```
try:
# Colab only
%tensorflow_version 2.x
except Exception:
pass
from __future__ import absolute_import, division, print_function, unicode_literals
import functools
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
TRAIN_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/train.csv"
TEST_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/eval.csv"
train_file_path = tf.keras.utils.get_file("train.csv", TRAIN_DATA_URL)
test_file_path = tf.keras.utils.get_file("eval.csv", TEST_DATA_URL)
# 让 numpy 数据更易读。
np.set_printoptions(precision=3, suppress=True)
```
## 加载数据
开始的时候,我们通过打印 CSV 文件的前几行来了解文件的格式。
```
!head {train_file_path}
```
正如你看到的那样,CSV 文件的每列都会有一个列名。dataset 的构造函数会自动识别这些列名。如果你使用的文件的第一行不包含列名,那么需要将列名通过字符串列表传给 `make_csv_dataset` 函数的 `column_names` 参数。
```python
CSV_COLUMNS = ['survived', 'sex', 'age', 'n_siblings_spouses', 'parch', 'fare', 'class', 'deck', 'embark_town', 'alone']
dataset = tf.data.experimental.make_csv_dataset(
...,
column_names=CSV_COLUMNS,
...)
```
这个示例使用了所有的列。如果你需要忽略数据集中的某些列,创建一个包含你需要使用的列的列表,然后传给构造器的(可选)参数 `select_columns`。
```python
dataset = tf.data.experimental.make_csv_dataset(
...,
select_columns = columns_to_use,
...)
```
对于包含模型需要预测的值的列是你需要显式指定的。
```
LABEL_COLUMN = 'survived'
LABELS = [0, 1]
```
现在从文件中读取 CSV 数据并且创建 dataset。
(完整的文档,参考 `tf.data.experimental.make_csv_dataset`)
```
def get_dataset(file_path):
dataset = tf.data.experimental.make_csv_dataset(
file_path,
batch_size=12, # 为了示例更容易展示,手动设置较小的值
label_name=LABEL_COLUMN,
na_value="?",
num_epochs=1,
ignore_errors=True)
return dataset
raw_train_data = get_dataset(train_file_path)
raw_test_data = get_dataset(test_file_path)
```
dataset 中的每个条目都是一个批次,用一个元组(*多个样本*,*多个标签*)表示。样本中的数据组织形式是以列为主的张量(而不是以行为主的张量),每条数据中包含的元素个数就是批次大小(这个示例中是 12)。
阅读下面的示例有助于你的理解。
```
examples, labels = next(iter(raw_train_data)) # 第一个批次
print("EXAMPLES: \n", examples, "\n")
print("LABELS: \n", labels)
```
## 数据预处理
### 分类数据
CSV 数据中的有些列是分类的列。也就是说,这些列只能在有限的集合中取值。
使用 `tf.feature_column` API 创建一个 `tf.feature_column.indicator_column` 集合,每个 `tf.feature_column.indicator_column` 对应一个分类的列。
```
CATEGORIES = {
'sex': ['male', 'female'],
'class' : ['First', 'Second', 'Third'],
'deck' : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
'embark_town' : ['Cherbourg', 'Southhampton', 'Queenstown'],
'alone' : ['y', 'n']
}
categorical_columns = []
for feature, vocab in CATEGORIES.items():
cat_col = tf.feature_column.categorical_column_with_vocabulary_list(
key=feature, vocabulary_list=vocab)
categorical_columns.append(tf.feature_column.indicator_column(cat_col))
# 你刚才创建的内容
categorical_columns
```
这将是后续构建模型时处理输入数据的一部分。
### 连续数据
连续数据需要标准化。
写一个函数标准化这些值,然后将这些值改造成 2 维的张量。
```
def process_continuous_data(mean, data):
# 标准化数据
data = tf.cast(data, tf.float32) * 1/(2*mean)
return tf.reshape(data, [-1, 1])
```
现在创建一个数值列的集合。`tf.feature_columns.numeric_column` API 会使用 `normalizer_fn` 参数。在传参的时候使用 [`functools.partial`](https://docs.python.org/3/library/functools.html#functools.partial),`functools.partial` 由使用每个列的均值进行标准化的函数构成。
```
MEANS = {
'age' : 29.631308,
'n_siblings_spouses' : 0.545455,
'parch' : 0.379585,
'fare' : 34.385399
}
numerical_columns = []
for feature in MEANS.keys():
num_col = tf.feature_column.numeric_column(feature, normalizer_fn=functools.partial(process_continuous_data, MEANS[feature]))
numerical_columns.append(num_col)
# 你刚才创建的内容。
numerical_columns
```
这里使用标准化的方法需要提前知道每列的均值。如果需要计算连续的数据流的标准化的值可以使用 [TensorFlow Transform](https://www.tensorflow.org/tfx/transform/get_started)。
### 创建预处理层
将这两个特征列的集合相加,并且传给 `tf.keras.layers.DenseFeatures` 从而创建一个进行预处理的输入层。
```
preprocessing_layer = tf.keras.layers.DenseFeatures(categorical_columns+numerical_columns)
```
## 构建模型
从 `preprocessing_layer` 开始构建 `tf.keras.Sequential`。
```
model = tf.keras.Sequential([
preprocessing_layer,
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid'),
])
model.compile(
loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
```
## 训练、评估和预测
现在可以实例化和训练模型。
```
train_data = raw_train_data.shuffle(500)
test_data = raw_test_data
model.fit(train_data, epochs=20)
```
当模型训练完成的时候,你可以在测试集 `test_data` 上检查准确性。
```
test_loss, test_accuracy = model.evaluate(test_data)
print('\n\nTest Loss {}, Test Accuracy {}'.format(test_loss, test_accuracy))
```
使用 `tf.keras.Model.predict` 推断一个批次或多个批次的标签。
```
predictions = model.predict(test_data)
# 显示部分结果
for prediction, survived in zip(predictions[:10], list(test_data)[0][1][:10]):
print("Predicted survival: {:.2%}".format(prediction[0]),
" | Actual outcome: ",
("SURVIVED" if bool(survived) else "DIED"))
```
| github_jupyter |
<img width="100" src="https://carbonplan-assets.s3.amazonaws.com/monogram/dark-small.png" style="margin-left:0px;margin-top:20px"/>
# Forest Emissions Tracking - Validation
_CarbonPlan ClimateTrace Team_
This notebook compares our estimates of country-level forest emissions to prior estimates from other
groups. The notebook currently compares againsts:
- Global Forest Watch (Zarin et al. 2016)
- Global Carbon Project (Friedlingstein et al. 2020)
```
import geopandas
import pandas as pd
from io import StringIO
import matplotlib.pyplot as plt
import numpy as np
from carbonplan_styles.mpl import set_theme
set_theme()
axis_name_size = 12
# country shapes from GADM36
countries = geopandas.read_file("s3://carbonplan-climatetrace/inputs/shapes/countries.shp")
# CarbonPlan's emissions
emissions = pd.read_csv("s3://carbonplan-climatetrace/v0.4/country_rollups_emissions.csv")
agb = pd.read_csv("s3://carbonplan-climatetrace/v0.4/country_rollups_agb.csv")
# Input data
# ----------
# GFW emissions
gfw_emissions = pd.read_excel(
"s3://carbonplan-climatetrace/validation/gfw_global_emissions.xlsx",
sheet_name="Country co2 emissions",
).dropna(axis=0)
gfw_emissions = gfw_emissions[gfw_emissions["threshold"] == 10] # select threshold
# rename
gfw_emissions.loc[gfw_emissions.country == "Republic of Congo", "country"] = "Congo"
gfw_emissions.loc[
gfw_emissions.country == "Bolivia", "country"
] = "Bolivia (Plurinational State of)"
gfw_emissions.loc[gfw_emissions.country == "Brunei", "country"] = "Brunei Darussalam"
gfw_emissions.loc[gfw_emissions.country == "Côte d'Ivoire", "country"] = "Côte dIvoire"
gfw_emissions.loc[gfw_emissions.country == "Laos", "country"] = "Lao Peoples Democratic Republic"
gfw_emissions.loc[gfw_emissions.country == "Swaziland", "country"] = "Eswatini"
gfw_emissions.loc[gfw_emissions.country == "Tanzania", "country"] = "United Republic of Tanzania"
gfw_emissions.loc[
gfw_emissions.country == "Venezuela", "country"
] = "Venezuela (Bolivarian Republic of)"
gfw_emissions.loc[gfw_emissions.country == "Vietnam", "country"] = "Viet Nam"
gfw_emissions.loc[
gfw_emissions.country == "Virgin Islands, U.S.", "country"
] = "United States Virgin Islands"
gfw_emissions.loc[gfw_emissions.country == "Zimbabwe", "country"] = "Zimbabwe)"
emissions.groupby("begin_date").sum().mean() / 1e9
# Merge emissions dataframes with countries GeoDataFrame
gfw_countries = countries.merge(gfw_emissions.rename(columns={"country": "name"}), on="name")
trace_countries = countries.merge(emissions.rename(columns={"iso3_country": "alpha3"}), on="alpha3")
agb_countries = countries.merge(agb.rename(columns={"iso3_country": "alpha3"}), on="alpha3")
agb = pd.merge(
left=agb_countries.rename(columns={"agb": "trace_agb"}),
right=gfw_countries[["alpha3", "abg_co2_stock_2000__Mg"]].rename(
columns={"abg_co2_stock_2000__Mg": "gfw_agb_co2"}
),
on="alpha3",
)
agb["trace_agb_co2"] = agb.trace_agb * 0.5 * 3.67
agb["trace_agb_co2"] = agb.trace_agb_co2 / 1e6
agb["gfw_agb_co2"] = agb.gfw_agb_co2 / 1e6
agb = agb[["name", "alpha3", "geometry", "trace_agb_co2", "gfw_agb_co2"]]
# reformat to "wide" format (time x country)
trace_wide = (
emissions.drop(columns=["end_date"])
.pivot(index="begin_date", columns="iso3_country")
.droplevel(0, axis=1)
)
trace_wide.index = pd.to_datetime(trace_wide.index)
gfw_wide = gfw_emissions.set_index("country").filter(regex="whrc_aboveground_co2_emissions_Mg_.*").T
gfw_wide.index = [pd.to_datetime(f"{l[-4:]}-01-01") for l in gfw_wide.index]
gfw_wide.head()
df = pd.read_csv("s3://carbonplan-climatetrace/v0.4/country_rollups_emissions_from_clearing.csv")
df.head()
df.loc[df.iso3_country == "AGO"].tCO2eq / 1e6
```
## Part 1 - Compare time-averaged country emissions (tropics only)
```
# Create a new dataframe with average emissions
avg_emissions = countries.set_index("alpha3")
avg_emissions["trace"] = trace_wide.mean().transpose() / 1e6
# avg_emissions["trace"] = trace_wide.loc['2020-01-01'] / 1e6
avg_emissions = avg_emissions.reset_index().set_index("name")
avg_emissions["gfw"] = gfw_wide.mean().transpose() / 1e6
# avg_emissions["gfw"] = gfw_wide.loc['2020-01-01'] / 1e6
avg_emissions = avg_emissions.dropna()
len(avg_emissions)
from sklearn.metrics import r2_score
r2_score(avg_emissions.gfw, avg_emissions.trace)
avg_emissions["me"] = avg_emissions.trace - avg_emissions.gfw
avg_emissions["mae"] = (avg_emissions.trace - avg_emissions.gfw).abs()
avg_emissions["mape"] = (avg_emissions.trace - avg_emissions.gfw).abs() / avg_emissions.gfw * 100
avg_emissions = avg_emissions.replace(np.inf, np.nan)
avg_emissions.mean().round(2)
sub = avg_emissions.loc[(avg_emissions.mape > 1) & (avg_emissions.gfw > 1)]
sub
(avg_emissions.gfw > 1).mean()
top20 = avg_emissions.sort_values(by="mae", ascending=False).head(20)
names = {
"Democratic Republic of the Congo": "DRC",
"Lao Peoples Democratic Republic": "Laos",
"Bolivia (Plurinational State of)": "Bolivia",
"Côte dIvoire": "Côte d'Ivoire",
"United Republic of Tanzania": "Tanzania",
"Viet Nam": "Vietnam",
"Venezuela (Bolivarian Republic of)": "Venezuela",
}
plt.figure(figsize=(12, 10))
for i, row in top20.reset_index()[["name", "alpha3"]].iterrows():
plt.subplot(5, 4, i + 1)
name = row["name"]
alpha3 = row["alpha3"]
plt.plot(gfw_wide[name].index, gfw_wide[name].values / 1e6, label="Zarin et al.")
plt.plot(trace_wide[alpha3].index, trace_wide[alpha3].values / 1e6, label="CarbonPlan")
plt.xticks(["2001-01-01", "2010-01-01", "2020-01-01"], [2001, 2010, 2020])
if name in names:
name = names[name]
plt.title(name, fontsize=axis_name_size)
if i > 3:
plt.ylim(0, 200)
if i == 8:
plt.ylabel("Emissions [Mt CO2 / yr]", fontsize=axis_name_size)
ax = plt.gca()
fig = plt.gcf()
handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc="upper center", ncol=2, bbox_to_anchor=(0.5, 1.03))
plt.tight_layout()
plt.savefig("top20_time_series.png", bbox_inches="tight")
plt.show()
plt.close()
# Scatter Plot
xmin = 1e-6
xmax = 1e4
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot([xmin, xmax], [xmin, xmax], "0.5")
avg_emissions.plot.scatter("gfw", "trace", ax=plt.gca())
plt.gca().set_xscale("log")
plt.gca().set_yscale("log")
plt.ylabel("CarbonPlan [Mt CO$_2$ / yr]", fontsize=axis_name_size)
plt.xlabel("Zarin [Mt CO$_2$ / yr]", fontsize=axis_name_size)
plt.xlim(xmin, xmax)
plt.ylim(xmin, xmax)
plt.title("a) Forest related carbon emissions", fontsize=axis_name_size)
xmin = 1e-4
xmax = 1e6
plt.subplot(1, 2, 2)
plt.plot([xmin, xmax], [xmin, xmax], "0.5")
agb.plot.scatter("gfw_agb_co2", "trace_agb_co2", ax=plt.gca())
plt.gca().set_xscale("log")
plt.gca().set_yscale("log")
plt.ylabel("CarbonPlan [Mt CO$_2$]", fontsize=axis_name_size)
plt.xlabel("Zarin [Mt CO$_2$]", fontsize=axis_name_size)
plt.xlim(xmin, xmax)
plt.ylim(xmin, xmax)
plt.title("b) Forest AGB stock in 2000", fontsize=axis_name_size)
plt.tight_layout()
plt.savefig("gfw_scatter.png")
```
## Part 2 - Maps of Tropical Emissions
```
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.figure(figsize=(14, 8))
plt.subplot(2, 1, 1)
kwargs = dict(
legend=True,
legend_kwds={
"orientation": "vertical",
"label": "Emissions [Mt CO$_2$ / yr]",
},
lw=0.25,
cmap="Reds",
vmin=0,
vmax=1000,
)
ax = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="2%", pad=0.2)
avg_emissions.plot("trace", ax=ax, cax=cax, **kwargs)
ax.set_title("Forest related carbon emissions from CarbonPlan", fontsize=axis_name_size)
ax.set_xlabel("Longitude", fontsize=axis_name_size)
ax.set_ylabel("Latitude", fontsize=axis_name_size)
plt.subplot(2, 1, 2)
kwargs = dict(
legend=True,
legend_kwds={
"orientation": "vertical",
"label": "Emissions Difference [%]",
},
lw=0.25,
cmap="RdBu_r",
vmin=-20,
vmax=20,
)
avg_emissions["pdiff"] = (
(avg_emissions["trace"] - avg_emissions["gfw"]) / avg_emissions["gfw"]
) * 100
ax = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="2%", pad=0.2)
avg_emissions.plot("pdiff", ax=ax, cax=cax, **kwargs)
ax.set_title("% difference from Zarin", fontsize=axis_name_size)
ax.set_xlabel("Longitude", fontsize=axis_name_size)
ax.set_ylabel("Latitude", fontsize=axis_name_size)
plt.tight_layout()
plt.savefig("gfw_map.png")
```
## Part 3 - Compare fire emissions
```
# CarbonPlan's emissions
emissions = {}
versions = ["v0.4"]
for version in versions:
for mechanism in ["fire"]:
emissions[version + "-" + mechanism] = pd.read_csv(
"s3://carbonplan-climatetrace/{}/country_rollups_emissions_from_{}.csv".format(
version, mechanism
)
)
# Blue Sky Fire emissions
emissions["Blue Sky"] = pd.read_csv("forest-fires_bsa.csv")
emissions[f"{version}-fire"]
emissions["Blue Sky"]
version = "v0.4"
comparison = pd.merge(
emissions[f"{version}-fire"].rename({"tCO2eq": "CarbonPlan"}, axis=1),
emissions["Blue Sky"].rename({"tCO2": "BSA"}, axis=1),
how="inner", # "left",
left_on=["iso3_country", "begin_date"],
right_on=["iso3_country", "begin_date"],
)
comparison["BSA"] /= 1e6
comparison["CarbonPlan"] /= 1e6
comparison["year"] = pd.to_datetime(comparison.begin_date).dt.year
comparison["BSA"] = comparison.BSA.fillna(0)
r2_score(comparison.BSA, comparison.CarbonPlan)
(comparison.CarbonPlan - comparison.BSA).mean()
(comparison.CarbonPlan <= comparison.BSA).mean()
len(comparison.iso3_country.unique())
xmin = 1e-4
xmax = 1e4
plt.figure(figsize=(5, 5))
plt.plot([xmin, xmax], [xmin, xmax], "0.5")
comparison.plot.scatter("BSA", "CarbonPlan", ax=plt.gca())
plt.gca().set_xscale("log")
plt.gca().set_yscale("log")
plt.ylabel("CarbonPlan [Mt CO$_2$ / yr]", fontsize=axis_name_size)
plt.xlabel("BSA [Mt CO$_2$ / yr]", fontsize=axis_name_size)
plt.yticks()
plt.xlim(xmin, xmax)
plt.ylim(xmin, xmax)
plt.title("Forest fire emissions", fontsize=axis_name_size)
plt.savefig("bsa_scatter.png", bbox_inches="tight")
avg_yr = comparison.groupby("iso3_country").mean()
xmin = 1e-4
xmax = 1e4
plt.figure(figsize=(5, 5))
plt.plot([xmin, xmax], [xmin, xmax], "0.5")
avg_yr.plot.scatter("BSA", "CarbonPlan", ax=plt.gca())
plt.gca().set_xscale("log")
plt.gca().set_yscale("log")
plt.ylabel("CarbonPlan [Mt CO$_2$ / yr]", fontsize=axis_name_size)
plt.xlabel("BSA [Mt CO$_2$ / yr]", fontsize=axis_name_size)
plt.xlim(xmin, xmax)
plt.ylim(xmin, xmax)
plt.title("Forest fire emissions", fontsize=axis_name_size)
plt.tight_layout()
plt.savefig("bsa_scatter_avg.png")
comparison.head()
comparison.loc[comparison.iso3_country.isin(["RUS", "USA"])]
comparison.loc[comparison.iso3_country.isin(["BRA"])]
emissions["Mt CO2"] = emissions.tCO2eq / 1e6
sub = emissions.loc[(emissions.iso3_country == "LKA"), ["begin_date", "Mt CO2", "iso3_country"]]
sub["year"] = pd.to_datetime(sub.begin_date).dt.year
plt.plot(sub.year, sub["Mt CO2"], "o-")
plt.xticks([2001, 2005, 2010, 2015, 2020], [2001, 2005, 2010, 2015, 2020])
plt.ylabel("Mt CO2")
plt.grid()
sub[["iso3_country", "year", "Mt CO2"]]
```
| github_jupyter |
```
import pandas as pd
df = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/00397/LasVegasTripAdvisorReviews-Dataset.csv", sep=';')
df.head()
df['Score'].value_counts(normalize=True)
from sklearn.model_selection import train_test_split
train, test = train_test_split(df, train_size=0.80, test_size=0.20, stratify=df['Score'], random_state=1337)
train['Score'].value_counts(normalize=True)
def wrangle(X):
X = X.copy()
def country_aggregation(row): #reduce number of country categories to 4. 'USA', 'Canada', 'UK', and all else 'other'.
if row['User country'] != "USA" and row['User country'] != 'Canada' and row['User country'] != 'UK':
return "Other"
else:
return row['User country']
def score_aggregation(row):
if row['Score'] == 5:
return "Excellent"
elif row['Score'] == 4 or row['Score'] == 3:
return "Average"
else:
return "Bad"
X['User country'] = X.apply(country_aggregation, axis=1)
#if not predict: #only modify score column if passing in training/test data. Do not run when running real predictions!
X['Score'] = X.apply(score_aggregation, axis=1)
X = X.drop(['Member years'], axis=1)
X['Hotel stars'] = X['Hotel stars'].str.replace("," , ".").astype(str)
X['Hotel stars'] = X['Hotel stars'].replace({"3": 1, "3.5": 2, "4": 3, "4.5": 4, "5": 5}).astype(int) #ordinal encoding
X.loc[(X['Hotel name'] == "Trump International Hotel Las Vegas") | #Trump international is a hotel only, no casino.
(X['Hotel name'] == "Marriott's Grand Chateau") | #Marriott's Grand Chateau is a hotel only, no casino.
(X['Hotel name'] == "Wyndham Grand Desert"), 'Casino'] = "NO" #Wyndham Grand Desert is a hotel only, no casino.
return X
train = wrangle(train)
test = wrangle(test)
from sklearn.metrics import accuracy_score
majority_class = train['Score'].mode()[0]
y_pred = [majority_class] * len(train['Score'])
print("Train baseline accuracy is: ", accuracy_score(train['Score'], y_pred))
majority_class = test['Score'].mode()[0]
y_pred = [majority_class] * len(test['Score'])
print("Test baseline accuracy is: ", accuracy_score(test['Score'], y_pred))
target = 'Score'
train_features = train.drop([target], axis=1)
numeric_features = train_features.select_dtypes(include='number').columns.tolist()
categorical_features = train_features.select_dtypes(exclude='number').nunique().index.tolist()
features = numeric_features + categorical_features
features_logistic = categorical_features.copy()
features_logistic.append('Hotel stars') #add hotel stars to features list, so we can specify to onehotencoder that we want to encode it, even though it is numeric(as we already did ordinal encoding on it)
y_train = train[target]
X_train = train[features]
X_test = test[features]
y_test = test[target]
X_train.shape
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, VotingClassifier
from sklearn.preprocessing import StandardScaler
import category_encoders as ce
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import SelectKBest
from xgboost import XGBClassifier
from imblearn.over_sampling import RandomOverSampler
#When hyperparamater tuning, set tune to "True", and mark each model that we want to tune to "True".
tune = False
forest = False
logistic = False
xgboost = False
forest_distributions = {
'model__n_estimators': range(250, 500, 50),
'model__max_depth': range(3, 14),
'model__max_features': range(2, 14),
'model__min_samples_leaf': range(2, 4)
}
logistic_distributions = {
'kbest__k': range(1, 20),
'model__C': [0.001, 0.01, 0.1, 1, 10, 100, 1000]
}
xgboost_distributions = {
'model__n_estimators': [75, 100, 125, 150, 175],
'model__max_depth': [6, 7, 8, 9, 10, 11, 12, 13],
'model__learning_rate': [0.01, 0.02, 0.03, 0.04, 0.05, 0.07, 0.10, 0.12, 0.14, 0.16],
'model__min_child_leaf':[1, 2, 3],
'model__min_child_weight': [1, 2, 3, 4],
'model__colsample_bytree':[0.2, 0.3, 0.4, 0.50, 0.60, 0.70],
'model__subsample':[0.3, 0.4, 0.5, 0.6, 0.7, 0.8],
'model__gamma':[0],
'model__scale_pos_weight': [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70,
75, 80, 85, 90, 95, 100]
}
if tune: #If we are hyperparamater tuning, pass no parameters into estimators and find paramaters via GridSearchCV / RandomizedSearchCV
forest_pipeline = Pipeline([('encoder', ce.OrdinalEncoder()),
('model', RandomForestClassifier(random_state=1337))])
logistic_pipeline = Pipeline([('encoder', ce.OneHotEncoder()),
('scaler', StandardScaler()),
('kbest', SelectKBest()),
('model', LogisticRegression(random_state=1337))])
xgboost_pipeline = Pipeline([('encoder', ce.OrdinalEncoder()),
('model', XGBClassifier(seed=1337))])
forest_search = GridSearchCV(
forest_pipeline,
param_grid=forest_distributions,
cv=3,
scoring='neg_log_loss', #good out of the box scoring metric for multiclass hyperparameter tuning
verbose=10,
n_jobs=15
)
logistic_search = GridSearchCV(
logistic_pipeline,
param_grid=logistic_distributions,
cv=3,
scoring='neg_log_loss', #good out of the box scoring metric for multiclass hyperparameter tuning
verbose=10,
n_jobs=15
)
xgboost_search = RandomizedSearchCV(
estimator=xgboost_pipeline,
param_distributions=xgboost_distributions,
n_iter=10000,
cv=3,
scoring='neg_log_loss', #good out of the box scoring metric for multiclass hyperparameter tuning
verbose=10,
random_state=1337,
n_jobs=15
)
X_train, y_train = RandomOverSampler(sampling_strategy='not majority').fit_resample(X_train, y_train)
if forest:
forest_search.fit(X_train, y_train)
forest_train_pred = forest_search.predict(X_train)
forest_test_pred = forest_search.predict(X_test)
forest_test_pred_proba = forest_search.predict_proba(X_test)
if logistic:
logistic_search.fit(X_train, y_train)
logistic_train_pred = logistic_search.predict(X_train)
logistic_test_pred = logistic_search.predict(X_test)
logistic_test_pred_proba = logistic_search.predict_proba(X_test)
if xgboost:
xgboost_search.fit(X_train, y_train)
xgboost_train_pred = xgboost_search.predict(X_train)
xgboost_test_pred = xgboost_search.predict(X_test)
xgboost_test_pred_proba = xgboost_search.predict_proba(X_test)
#When hyperparameter tuning, pass our best estimators into votingclassifier. Only run when all 3 models are being tuned.
if forest and logistic and xgboost:
voting_model = VotingClassifier(estimators=[('forest', forest_search.best_estimator_), #VotingClassifier is Soft Voting/Majority Rule classifier for unfitted estimators
('logistic', logistic_search.best_estimator_),
('xgboost', xgboost_search.best_estimator_),],
voting='soft', weights=[2, 1, 2]) #soft voting per recommendation from sklearn documentation, when used on tuned classifiers.
voting_model.fit(X_train, y_train)
else: #If we are not hyperparameter tuning, pass in our best params(from previous tuning runs).
forest_pipeline = Pipeline([('encoder', ce.OrdinalEncoder()),
('model', RandomForestClassifier(random_state=1337,
max_depth=13,
max_features=11,
min_samples_leaf=2,
n_estimators=450))])
logistic_pipeline = Pipeline([('encoder', ce.OneHotEncoder(cols=features_logistic)), #use features list which contains "Hotel stars" so that it gets properly encoded.
('scaler', StandardScaler()),
('kbest', SelectKBest(k=19)),
('model', LogisticRegression(random_state=1337, C=0.01))])
xgboost_pipeline = Pipeline([('encoder', ce.OrdinalEncoder()),
('model', XGBClassifier(random_state=1337, n_estimators=175, min_child_weight=1,
min_child_leaf=2, max_depth=11, learning_rate=0.04,
gamma=0, subsample=0.8, colsample_bytree=0.3, scale_pos_weight=100))])
X_train, y_train = RandomOverSampler(sampling_strategy='not majority').fit_resample(X_train, y_train) #over sample all but the majority class
forest_pipeline.fit(X_train, y_train)
forest_train_pred = forest_pipeline.predict(X_train)
forest_test_pred = forest_pipeline.predict(X_test)
forest_test_pred_proba = forest_pipeline.predict_proba(X_test)
logistic_pipeline.fit(X_train, y_train)
logistic_train_pred = logistic_pipeline.predict(X_train)
logistic_test_pred = logistic_pipeline.predict(X_test)
logistic_test_pred_proba = logistic_pipeline.predict_proba(X_test)
xgboost_pipeline.fit(X_train, y_train)
xgboost_train_pred = xgboost_pipeline.predict(X_train)
xgboost_test_pred = xgboost_pipeline.predict(X_test)
xgboost_test_pred_proba = xgboost_pipeline.predict_proba(X_test)
voting_model = VotingClassifier(estimators=[('forest', forest_pipeline), #VotingClassifier is Soft Voting/Majority Rule classifier for unfitted estimators
('logistic', logistic_pipeline),
('xgboost', xgboost_pipeline),],
voting='soft') #soft voting per recommendation from sklearn documentation, when used on tuned classifiers.
voting_model.fit(X_train, y_train)
#pickle the model
from joblib import dump
dump(voting_model, 'voting_model.joblib', compress=True)
#print package versions for pipenv
import joblib
import sklearn
import category_encoders as ce
import xgboost
import imblearn
print(f'joblib=={joblib.__version__}')
print(f'scikit-learn=={sklearn.__version__}')
print(f'category_encoders=={ce.__version__}')
print(f'xgboost=={xgboost.__version__}')
print(f'imblearn=={imblearn.__version__}')
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.metrics import roc_auc_score, plot_roc_curve
if tune:
target_names = ['Average', 'Bad', 'Excellent']
if forest:
print(forest_search.best_params_, '\n')
print("Best Random Forest CV score: ", forest_search.best_score_, '\n')
print("Random forest ROC-AUC: ", roc_auc_score(y_test, forest_test_pred_proba, multi_class='ovr', labels=target_names), '\n')
print(classification_report(y_test, forest_test_pred, target_names=target_names), '\n')
print('\n')
if logistic:
print(logistic_search.best_params_, '\n')
print("Best logistic regression CV score: ", logistic_search.best_score_, '\n')
print("Logistic regression ROC-AUC: ", roc_auc_score(y_test, logistic_test_pred_proba, multi_class='ovr', labels=target_names), '\n')
print(classification_report(y_test, logistic_test_pred, target_names=target_names), '\n')
print('\n')
if xgboost:
print(xgboost_search.best_params_, '\n')
print("Best xgboost CV score: ", xgboost_search.best_score_, '\n')
print("Xgboost ROC-AUC: ", roc_auc_score(y_test, xgboost_test_pred_proba, multi_class='ovr', labels=target_names), '\n')
print(classification_report(y_test, xgboost_test_pred, target_names=target_names), '\n')
print('\n')
if forest and logistic and xgboost:
print("Voting classifier, final accuracy score on test set: ", voting_model.score(X_test, y_test))
combined_model = voting_model.predict_proba(X_test)
print("Voting classifier, final ROC AUC on test set: ", roc_auc_score(y_test, combined_model, multi_class='ovr', labels=target_names))
else:
target_names = ['Average', 'Bad', 'Excellent']
print("Random forest ROC-AUC: ", roc_auc_score(y_test, forest_test_pred_proba, multi_class='ovr', labels=target_names), '\n')
print(classification_report(y_test, forest_test_pred, target_names=target_names))
print('\n')
print("Logistic regression ROC-AUC: ", roc_auc_score(y_test, logistic_test_pred_proba, multi_class='ovr', labels=target_names), '\n')
print(classification_report(y_test, logistic_test_pred, target_names=target_names))
print('\n')
print("Xgboost ROC-AUC: ", roc_auc_score(y_test, xgboost_test_pred_proba, multi_class='ovr', labels=target_names), '\n')
print(classification_report(y_test, xgboost_test_pred, target_names=target_names))
print('\n')
print("Voting classifier, final accuracy score on test set: ", voting_model.score(X_test, y_test))
combined_model = voting_model.predict_proba(X_test)
print("Voting classifier, final ROC AUC on test set: ", roc_auc_score(y_test, combined_model, multi_class='ovr', labels=target_names))
###While this is a good way to evaluate the estimator we are passing in, unless using a 3 way train/validate/test split, this should not be used for feature selection.
###Instead, passing in an unfit estimator and specifying the amount of CV rounds will allow us to see more generalized permutation importance.
import eli5
from eli5.sklearn import PermutationImportance
permuter = PermutationImportance(
xgboost_pipeline.named_steps.model, #prefit estimator
scoring='roc_auc_ovo',
n_iter=300,
random_state=1337
)
permuter.fit(xgboost_pipeline.named_steps.encoder.transform(X_test), y_test)
feature_names = X_test.columns.tolist()
eli5.show_weights(
permuter,
top=None,
feature_names=feature_names
)
import eli5
from eli5.sklearn import PermutationImportance
permuter = PermutationImportance(
forest_pipeline.named_steps.model, #prefit estimator
scoring='roc_auc_ovo',
n_iter=300,
random_state=1337
)
permuter.fit(forest_pipeline.named_steps.encoder.transform(X_test), y_test)
feature_names = X_test.columns.tolist()
eli5.show_weights(
permuter,
top=None,
feature_names=feature_names
)
permuter = PermutationImportance(
logistic_pipeline.named_steps.model, #prefit estimator
scoring='roc_auc_ovo',
n_iter=300,
random_state=1337
)
X_test_encoded = logistic_pipeline.named_steps.encoder.transform(X_test)
X_test_scaled = logistic_pipeline.named_steps.scaler.transform(X_test_encoded)
X_test_final = logistic_pipeline.named_steps.kbest.transform(X_test_scaled)
selected_mask = logistic_pipeline.named_steps.kbest.get_support()
all_names = X_test_encoded.columns
selected_names = all_names[selected_mask]
permuter.fit(X_test_final, y_test)
feature_names = selected_names.tolist()
eli5.show_weights(
permuter,
top=None,
feature_names=feature_names
)
from pdpbox.pdp import pdp_isolate, pdp_plot
feature = 'Hotel stars'
isolated = pdp_isolate(
model=forest_pipeline,
dataset=X_test,
model_features=X_test.columns,
feature=feature
)
pdp_plot(isolated,feature_name=feature, plot_lines=True);
from pdpbox.pdp import pdp_interact, pdp_interact_plot
features_interact = ['Nr. reviews', 'Hotel stars']
interaction = pdp_interact(
model=forest_pipeline,
dataset=X_test,
model_features=X_test.columns,
features=features_interact
)
pdp_interact_plot(interaction, plot_type='grid', feature_names=features_interact);
```
| github_jupyter |
# Object Oriented Programming (OOP)
### classes and attributes
```
# definition of a class object
class vec3:
pass
# instance of the vec3 class object
a = vec3()
# add some attributes to the v instance
a.x = 1
a.y = 2
a.z = 2.5
print(a)
print(a.z)
print(a.__dict__)
# another instance of the vec3 class object
b = vec3()
print(b)
print(b.__dict__)
class vec2:
pass
print(isinstance(a, vec3))
print(isinstance(b, vec3))
print(isinstance(a, vec2))
# all vec3 instances should have the attributes x, y, z
class vec3:
# attributes
x = 1
y = 2
z = 2.5
a = vec3()
b = vec3()
print(a, a.__dict__)
print(b, b.__dict__)
# !!! Neither a nor b has x, y, or z! Huh?
# the class vec3 owns x, y and z!
print(vec3.__dict__)
# but a and b still have access to x, y and z
print(a.x, a.y, a.z)
print(b.x, b.y, b.z)
# this changes z for all vec3 instances
vec3.z = 3
print(vec3.__dict__)
print(a.x, a.y, a.z)
print(b.x, b.y, b.z)
# what if we change z only for a?
a.z = 7
print(vec3.__dict__)
print(a.x, a.y, a.z)
print(b.x, b.y, b.z)
# a now has both a class level attribute z and it's own attribute z!
print(a.__dict__)
# if we get rid of a.z, a will default back to vec3.z
del a.__dict__['z']
print(a.__dict__)
print(a.x, a.y, a.z)
```
### initialization
```
# class initialization
class vec3:
""" __init__() is a method of vec3 (i.e. a function belonging to the class vec3).
It is called whenever we create a new instance of a vec3 object.
"""
def __init__(self):
self.x = 10
self.y = 20
self.z = 30
a = vec3()
print(vec3.__dict__)
print(a.__dict__)
# a and b are two separate instances of the vec3 object
b = vec3()
print(a)
print(b)
a.x = 5
print(a.__dict__)
print(b.__dict__)
# passing arguments during class instantiation
class vec3:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
a = vec3(2, 4, 6)
print(a.__dict__)
class vec3:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
a = vec3()
b = vec3(1, 2, 3)
print(a.__dict__)
print(b.__dict__)
```
### methods
```
# class methods are just functions (e.g. __init__) that are wrapped up into the class
class vec3:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def translate(self, dx, dy, dz):
self.x += dx
self.y += dy
self.z += dz
a = vec3(1, 2, 3)
print(a.__dict__)
a.translate(10, 10, -10)
print(a.__dict__)
# two ways to call a class method
a = vec3(1, 2, 3)
vec3.translate(a, 10, 10, -10)
print(a.__dict__)
a = vec3(1, 2, 3)
a.translate(10, 10, -10)
print(a.__dict__)
```
### special methods
```
class vec3:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f"({self.x}, {self.y}, {self.z})"
def translate(self, dx, dy, dz):
self.x += dx
self.y += dy
self.z += dz
a = vec3(1, 2, 3)
print(a)
```
### inheritance
```
# vec4 inherits all of vec3's functionality
class vec4(vec3):
pass
a = vec4()
print(a.__dict__)
a = vec4(1, 2, 3)
print(a.__dict__)
a.translate(10, 10, -10)
print(a.__dict__)
print(issubclass(vec4, vec2))
print(issubclass(vec4, vec3))
# vec4 extends vec3's functionality
class vec4(vec3):
""" vec4 instantiation will use this __init__ instead of vec3's
"""
def __init__(self):
self.w = 1
a = vec4()
print(a.__dict__)
class vec4(vec3):
def __init__(self, x=0, y=0, z=0, w=1):
vec3.__init__(self, x, y, z) # or you could use `super().__init__(x, y, z)`
self.w = w
a = vec4()
print(a.__dict__)
a = vec4(1, 2, 3)
print(a.__dict__)
a = vec4(1, 2, 3, 0)
print(a.__dict__)
print(help(vec4))
print(help(vec3))
# all classes inherit from builtins.object by default
class tmp1(object):
pass
class tmp2():
pass
print(help(tmp1))
print(help(tmp2))
```
### Exercise: Create a class
### Diabetes dataset
```
import numpy as np
from sklearn import datasets
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
y -= y.mean()
features = "age sex bmi map tc ldl hdl tch ltg glu".split()
```
### OLS regression class
```
from sklearn.linear_model import LinearRegression
class MyLinearRegression:
def __init__(self, X, y):
self.data = X
self.target = y
self.model = LinearRegression()
self.fit()
def fit(self):
self.model.fit(self.data, self.target)
return self.predict(self.data)
def predict(self, X):
return self.model.predict(X)
def params(self):
return self.model.coef_
def getMSE(self, X, y):
return np.mean((y - self.predict(X))**2)
def getR2(self, X, y):
return self.model.score(X, y)
mymodel = MyLinearRegression(X, y)
print(mymodel.params())
print(f"MSE = {mymodel.getMSE(X, y)}")
print(f"R^2 = {mymodel.getR2(X, y)}")
```
### Exercise: Add a method to MyLinearRegression that automatically loads the dibaetes data set.
### Exercise: Add a method to MyLinearRegression that plots the slope factors in a bar graph.
### Exercise: Ridge regression class
```
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_validate, GridSearchCV
class MyRigeRegression:
def __init__(self, X, y, alphas):
```
### Exercise: KNN regression class
```
from sklearn import neighbors
class MyRigeRegression:
def __init__(self, X, y, K):
```
| github_jupyter |
## Prettify Your Data Structures With Pretty Print in Python
Dealing with data is essential for any Pythonista, but sometimes that data is just not very pretty. Computers don’t care about formatting, but without good formatting, humans may find something hard to read. The output isn’t pretty when you use `print()` on large dictionaries or long lists—it’s efficient, but not pretty.
The `pprint` module in Python is a utility module that you can use to print data structures in a readable, pretty way. It’s a part of the standard library that’s especially useful for debugging code dealing with API requests, large JSON files, and data in general.
## Understanding the Need for Python’s Pretty Print
The Python `pprint` module is helpful in many situations. It comes in handy when making API requests, dealing with JSON files, or handling complicated and nested data. You’ll probably find that using the normal `print()` function isn’t adequate to efficiently explore your data and debug your application. When you use `print()` with dictionaries and lists, the output doesn’t contain any newlines.
Example: You’ll make a request to {JSON} Placeholder for some mock user information. The first thing to do is to make the HTTP `GET` request and put the response into a dictionary:
```
from urllib import request
import json
# Here, you make a basic GET request and then parse the response
# Into a dictionary with `json.loads()`. With the dictionary
# Now in a variable, a common next step is to print the contents with print():
response = request.urlopen("https://jsonplaceholder.typicode.com/users")
json_response = response.read()
# `json.loads(str)` - decoding JSON
users = json.loads(json_response)
print(users)
```
One huge line with no newlines. Depending on your console settings, this might appear as one very long line. Alternatively, your console output might have its word-wrapping mode on, which is the most common situation. Unfortunately, that doesn’t make the output much friendlier!
If you look at the 1st and last characters, you can see that this appears to be a `list`. You might be tempted to start writing a loop to print the items:
```
for user in users:
print(user)
```
This `for` loop would print each object on a separate line, but even then, each object takes up way more space than can fit on a single line. Printing in this way does make things a bit better, but it’s by no means ideal. The above example is a relatively simple data structure, but what would you do with a deeply nested dictionary 100 times the size?
Sure, you could write a function that uses recursion to find a way to print everything. Unfortunately, you’ll likely run into some edge cases where this won’t work. You might even find yourself writing a whole module of functions just to get to grips with the structure of the data!
Enter the `pprint` module!
## Working With pprint
`pprint` is a Python module made to print data structures in a pretty way. It has long been part of the Python standard library, so installing it separately isn’t necessary. All you need to do is to import its `pprint()` function:
```
from pprint import pprint
# Then, instead of going with the normal `print(users)` approach
# As you did in the example above, you can call your new
# Favorite function to make the output pretty
pprint(users)
```
How pretty! The keys of the dictionaries are even visually indented! This output makes it so much more straightforward to scan and visually analyze data structures.
If you’re a fan of typing as little as possible, then you’ll be pleased to know that `pprint()` has an alias, `pp()`:
```
from pprint import pp
# `pp()` is just a wrapper around `pprint()`,
# and it’ll behave exactly the same way.
pp(users)
```
**NOTE:** Python has included this alias since version 3.8.0 alpha 2.
However, even the default output may be too much information to scan at first. Maybe all you really want is to verify that you’re dealing with a list of plain objects. For that, you’ll want to tweak the output a little.
For these situations, there are various parameters you can pass to `pprint()` to make even the tersest data structures pretty.
## Exploring Optional Parameters of pprint()
There are 7 parameters that you can use to configure your Pythonic pretty printer. You don’t need to use them all, and some will be more useful than others. The one you’ll find most valuable will probably be depth.
## Summarizing Your Data: depth
One of the handiest parameters to play around with is `depth`. The following Python command will only print the full contents of users if the data structure is at or lower than the specified `depth`—all while keeping things pretty, of course. The contents of deeper data structures are replaced with three dots `...`:
```
pprint(users, depth=1)
print('-------------------')
# Now you can immediately see that this is indeed a list of dictionaries.
# To explore the data structure further, you can increase the depth by one level,
# Which will print all the top-level keys of the dictionaries in users:
pprint(users, depth=2)
```
Now you can quickly check whether all the dictionaries share their top-level keys. This is a valuable observation to make, especially if you’re tasked with developing an application that consumes data like this.
## Giving Your Data Space: indent
The `indent` parameter controls how indented each level of the pretty-printed representation will be in the output. The default `indent` is just `1`, which translates to **one space character**:
```
pprint(users[0], depth=1)
print('------------')
pprint(users[0], depth=1, indent=4)
```
The most important part of the indenting behavior of `pprint()` is keeping all the keys aligned visually. How much indentation is applied depends on both the `indent` parameter and where the key is.
Since there’s no nesting in the examples above, the amount of indentation is based completely on the `indent` parameter. In both examples, note how the opening curly bracket (`{`) is counted as a unit of indentation for the 1st key. In the 1st example, the opening single quote `'` for the 1st key comes right after `{` without any spaces in between because the indent is set to `1`.
When there is nesting, however, the indentation is applied to the 1st element in-line, and `pprint()` then keeps all following elements aligned with the 1st one. So if you set your `indent` to `4` when printing users, the 1st element will be indented by four characters, while the nested elements will be indented by more than 8 characters because the indentation starts from the end of the 1st key:
```
pprint(users[0], depth=2, indent=4)
```
## Limiting Your Line Lengths: width
By default, `pprint()` will only output up to 80 characters per line. You can customize this value by passing in a `width` argument. `pprint()` will make an effort to fit the contents on one line. If the contents of a data structure go over this limit, then it’ll print every element of the current data structure on a new line:
```
pprint(users[0])
```
When you leave the `width` at the default of 80 characters, the dictionary at `users[0]['address']['geo']` only contains a '`lat`' and a '`lng`' attribute. This means that taking the sum of the indent and the number of characters needed to print out the dictionary, including the spaces in between, comes to less than 80 characters. Since it’s less than 80 characters, the default `width`, `pprint()` puts it all on one line.
However, the dictionary at `users[0]['company']` would go over the default `width`, so `pprint()` puts each key on a new line. This is true of dictionaries, lists, tuples, and sets:
```
pprint(users[0], width=160)
```
If you set the `width` to a large value like `160`, then all the nested dictionaries fit on one line. You can even take it to extremes and use a huge value like `500`, which, for this example, prints the whole dictionary on one line:
```
pprint(users[0], width=500)
```
Here, you get the effects of setting width to a relatively large value. You can go the other way and set width to a low value such as `1`. However, the main effect that this will have is making sure every data structure will display its components on separate lines. You’ll still get the visual indentation that lines up the components:
```
pprint(users[0], width=5)
```
## Squeezing Your Long Sequences: compact
You might think that compact refers to the behavior you explored in the section about `width` — that is, whether `compact` makes data structures appear on one line or separate lines. However, `compact` only affects the output once a line goes over the `width`.
**NOTE:** `compact` only affects the output of sequences: lists, sets, and tuples, and NOT dictionaries. This is intentional, though it’s not clear why this decision was taken.
If `compact` is `True`, then the output will wrap onto the next line. The default behavior is for each element to appear on its own line if the data structure is longer than the `width`:
```
pprint(users, depth=1)
print('-------------')
pprint(users, depth=1, width=40)
print('-------------')
pprint(users, depth=1, width=40, compact=True)
```
Pretty-printing this list using the default settings prints out the abbreviated version on one line. Limiting `width` to 40 characters, you force `pprint()` to output all the list’s elements on separate lines. If you then set `compact=True`, then the list will wrap at 40 characters and be more compact than it would typically look.
**NOTE:** Beware that setting the `width` to less than `7` characters — which, in this case, is equivalent to the `[{...},` output — seems to bypass the depth argument completely, and `pprint()` ends up printing everything without any folding. This has been reported as bug #45611.
`compact` is useful for long sequences with short elements that would otherwise take up many lines and make the output less readable.
## Directing Your Output: stream
The `stream` parameter refers to the output of `pprint()`. By default, it goes to the same place that `print()` goes to. Specifically, it goes to `sys.stdout`, which is actually a file object in Python. However, you can redirect this to any file object, just like you can with `print()`:
```
from urllib import request
from pprint import pprint
import json
response = request.urlopen("https://jsonplaceholder.typicode.com/users")
print('type:', type(response), '\n')
json_response = response.read()
users = json.loads(json_response)
with open("output.txt", mode="w") as file_object:
pprint(users, stream=file_object)
```
Here you create a `file_object` with `open()`, and then you set the stream parameter in `pprint()` to that `file_object`. If you then open the `output.txt` file, you should see that you’ve pretty-printed everything in users there.
Python does have its own `logging` module. However, you can also use `pprint()` to send pretty outputs to files and have these act as logs if you prefer.
## Preventing Dictionary Sorting: sort_dicts
Although dictionaries are generally considered unordered data structures, since Python 3.6, dictionaries are ordered by insertion.
`pprint()` orders the keys alphabetically for printing:
```
pprint(users[0], depth=1)
print()
pprint(users[0], depth=1, sort_dicts=False)
```
Unless you set `sort_dicts` to `False`, Python’s `pprint()` sorts the keys alphabetically. It keeps the output for dictionaries consistent, readable, and—well—pretty!
When `pprint()` was first implemented, dictionaries were unordered. Without alphabetically ordering the keys, a dictionary’s keys could have theoretically differed at each print.
## Prettifying Your Numbers: underscore_numbers
The `underscore_numbers` parameter is a feature introduced in Python 3.10 that makes long numbers more readable. Considering that the example you’ve been using so far doesn’t contain any long numbers, you’ll need a new example to try it out:
```
number_list = [123456789, 10000000000000]
pprint(number_list, underscore_numbers=True)
```
If you tried running this call to `pprint()` and got an error, you’re not alone. As of October 2021, this argument doesn’t work when calling `pprint()` directly. The Python community noticed this quickly, and it’s been fixed in the December 2021 3.10.1 bug fix release. The folks at Python care about their pretty printer!
If `underscore_numbers` doesn’t work when you call `pprint()` directly and you really want pretty numbers, there is a workaround: When you create your own `PrettyPrinter` object, this parameter should work just like it does in the example above.
## Creating a Custom PrettyPrinter Object
It’s possible to create an instance of `PrettyPrinter` that has defaults you’ve defined. Once you have this new instance of your custom `PrettyPrinter` object, you can use it by calling the `.pprint()` method on the `PrettyPrinter` instance:
```
from pprint import PrettyPrinter
custom_printer = PrettyPrinter(
indent=4,
width=100,
depth=2,
compact=True,
sort_dicts=False,
underscore_numbers=True
)
custom_printer.pprint(users[0])
number_list = [123456789, 10000000000000]
custom_printer.pprint(number_list)
```
With these commands, you:
1. Imported `PrettyPrinter`, which is a class definition
2. Created a new instance of that class with certain parameters
3. Printed the first user in users
4. Defined a list of a couple of long numbers
5. Printed `number_list`, which also demonstrates `underscore_numbers` in action
**NOTE:** that the arguments you passed to `PrettyPrinter` are exactly the same as the default `pprint()` arguments, except that you skipped the 1st parameter. In `pprint()`, this is the object you want to print.
This way, you can have various printer presets—perhaps some going to different streams—and call them when you need them.
## Getting a Pretty String With pformat()
What if you don’t want to send the pretty output of `pprint()` to a stream? Perhaps you want to do some **regex matching** and replace certain keys. For plain dictionaries, you might find yourself wanting to remove the brackets and quotes to make them look even more human-readable.
Whatever it is that you might want to do with the string pre-output, you can get the string by using `pformat()`:
```
from pprint import pformat
address = pformat(users[0]["address"])
print('type:', type(address))
print(address, '\n------------')
chars_to_remove = ["{", "}", "'"]
for char in chars_to_remove:
address = address.replace(char, "")
print(address)
```
`pformat()` is a tool you can use to get between the pretty printer and the output stream.
Another use case for this might be if you’re building an API and want to send a pretty string representation of the JSON string. Your end users would probably appreciate it!
## Handling Recursive Data Structures
Python’s `pprint()` is recursive, meaning it’ll pretty-print all the contents of a dictionary, all the contents of any child dictionaries, and so on.
Ask yourself what happens when a recursive function runs into a recursive data structure. Imagine that you have dictionary `A` and dictionary `B`:
* `A` has one attribute, `.link`, which points to `B`
* `B` has one attribute, `.link`, which points to `A`
If your imaginary recursive function has no way to handle this circular reference, it’ll never finish printing! It would print `A` and then its child, `B`. But `B` also has `A` as a child, so it would go on into infinity.
Luckily, both the normal `print()` function and the `pprint()` function handle this gracefully:
```
from pprint import pprint
A = {}
B = {"link": A}
A["link"] = B
print(A, '\n----------')
pprint(A)
```
While Python’s regular `print()` just abbreviates the output, `pprint()` explicitly notifies you of recursion and also adds the ID of the dictionary.
| github_jupyter |
# Transformations Tutorial #1: Coordinate Systems
## Introduction
This tutorial is about the transformation packages `LocalCoordinateSystem` class which describes the orientation and position of a Cartesian coordinate system towards another reference coordinate system. The reference coordinate systems origin is always at $(0, 0, 0)$ and its orientation is described by the basis: $e_x = (1, 0, 0)$, $e_y = (0, 1, 0)$, $e_z = (0, 0, 1)$.
## Imports
The packages required in this tutorial are:
```
# if the package is not installed in your python environment, run this to execute the notebook directly from inside the GitHub repository
%cd -q ..
# enable interactive plots on Jupyterlab with ipympl and jupyterlab-matplotlib installed
# %matplotlib widget
# plotting
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
# interactive plots
import ipywidgets as widgets
from ipywidgets import VBox, HBox, IntSlider, Checkbox, interactive_output, FloatSlider
from IPython.display import display
import numpy as np
import pandas as pd
import xarray as xr
import weldx.visualization as vs
import weldx.transformations as tf
```
## Construction
The constructor of the `LocalCoordinateSystem` class takes 2 parameters, the `orientation` and the `coordinates`. `orientation` is a 3x3 matrix. It can either be viewed as a rotation/reflection matrix or a set of normalized column vectors that represent the 3 basis vectors of the coordinate system. The matrix needs to be orthogonal, otherwise, an exception is raised. `coordinates` is the position of the local coordinate systems origin inside the reference coordinate system. The default parameters are the identity matrix and the zero vector. Hence, we get a system that is identical to the reference system if no parameter is passed to the constructor.
```
lcs_ref = tf.LocalCoordinateSystem()
```
We create some coordinate systems and visualize them using the `visualization` package. The coordinate axes are colored as follows:
- x = red
- y = green
- z = blue
```
# create a translated coordinate system
lcs_01 = tf.LocalCoordinateSystem(coordinates=[2, 4, -1])
# create a rotated coordinate system using a rotation matrix as basis
rotation_matrix = tf.WXRotation.from_euler("z",np.pi / 3).as_matrix()
lcs_02 = tf.LocalCoordinateSystem(orientation=rotation_matrix, coordinates=[0, 0, 3])
```
**Plot:**
```
vs.plot_coordinate_systems([(lcs_ref, {"color":"r", "label":"reference_system"}),
(lcs_01, {"color":"g", "label":"system 1"}),
(lcs_02, {"color":"b", "label":"system 2"}) ])
```
> **HINT:** In the jupyter notebook version of this tutorial, you can rotate the plot by pressing the left mouse button and moving the mouse. This helps to understand how the different coordinate systems are positioned in the 3d space.
Apart from the class constructor, there are some factory functions implemented to create a coordinate system. The `from_orientation` provides the same functionality as the class constructor. The `from_xyz` takes 3 basis vectors instead of a matrix. `from_xy_and_orientation`, `from_xz_and_orientation` and `from_yz_and_orientation` create a coordinate system with 2 basis vectors and a `bool` which specifies if the coordinate system should have a positive or negative orientation. Here are some examples:
```
# coordinate system using 3 basis vectors
e_x = [1, 2, 0]
e_y = [-2, 1, 0]
e_z = [0, 0, 5]
lcs_03 = tf.LocalCoordinateSystem.from_xyz(e_x, e_y, e_z, coordinates=[1, 1, 0])
# create a negatively oriented coordinate system with 2 vectors
lcs_04 = tf.LocalCoordinateSystem.from_yz_and_orientation(
e_y, e_z, positive_orientation=False, coordinates=[1, 1, 2]
)
```
**Plot:**
```
vs.plot_coordinate_systems([(lcs_ref, {"color":"r", "label":"reference_system"}),
(lcs_03, {"color":"g", "label":"system 3"}),
(lcs_04, {"color":"b", "label":"system 4"}) ])
```
As you can see, the y- and z-axis of system 3 and 4 are pointing into the same direction, since we used the same basis vectors. The automatically determined x axis of system 4 points into the opposite direction, since we wanted a system with negative orientation.
Another method to create a `LocalCoordinateSystem` is `from_euler`. It utilizes the `scipy.spatial.transform.Rotation.from_euler` function to calculate a rotation matrix from Euler sequences and uses it to describe the orientation of the coordinate system. The parameters `sequence`, `angles`, and `degrees` of the `from_euler` method are directly passed to the SciPy function. `sequence` expects a string that determines the rotation sequence around the coordinate axes. For example `"xyz"`. `angles` is a scalar or list of the corresponding number of angles and `degrees` a `bool` that specifies if the angles are provided in degrees (`degrees=True`) or radians (`degrees=False`). For further details, have a look at the [SciPy documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.Rotation.from_euler.html) of the `from_euler` function. Here is a short example:
```
# create a coordinate system by a 90° rotation around the x axis and subsequent 45° rotation around the y axis
lcs_05 = tf.LocalCoordinateSystem.from_euler(sequence="x", angles=90, degrees=True, coordinates=[1, -1, 0])
lcs_06 = tf.LocalCoordinateSystem.from_euler(
sequence="xy", angles=[90, 45], degrees=True, coordinates=[2, -2, 0]
)
```
**Plot:**
```
# create 3d plot
vs.plot_coordinate_systems([(lcs_ref, {"color":"r", "label":"reference_system"}),
(lcs_05, {"color":"g", "label":"system 5"}),
(lcs_06, {"color":"b", "label":"system 6"}) ])
```
## Coordinate transformations
It is quite common that there exists a chain or tree-like dependency between coordinate systems. We might have a moving object with a local coordinate system that describes its position and orientation towards a fixed reference coordinate system. This object can have another object attached to it, with its position and orientation given in relation to its parent objects coordinate system. If we want to know the attached object coordinate system in relation to the reference coordinate system, we have to perform a coordinate transformation.
To avoid confusion about the reference systems of each coordinate system, we will use the following naming convention for the coordinate systems: `lcs_NAME_in_REFERENCE`. This is a coordinate system with the name "NAME" and its reference system has the name "REFERENCE". The only exception to this convention will be the reference coordinate system "lcs_ref", which has no reference system.
The `LocalCoordinateSystem` class provides the `+` and `-` operators to change the reference system easily. The `+` operator will transform a coordinate system to the reference coordinate system of its current reference system:
~~~ python
lcs_child_in_ref = lcs_child_in_parent + lcs_parent_in_ref
~~~
As the naming of the variables already implies, the `+` operator should only be used if there exists a **child-parent relation** between the left-hand side and right-hand side system.
If two coordinate systems share a **common reference system**, the `-` operator transforms one of those systems into the other:
~~~ python
lcs_child_in_parent = lcs_child_in_ref - lcs_parent_in_ref
~~~
It is important to remember that this operation is in general not commutative since it involves matrix multiplication which is also not commutative. During those operations, the local system that should be transformed into another coordinate system is always located to the left of the `+` or `-` operator. You can also chain multiple transformations, like this:
~~~ python
lcs_A_in_C = lcs_A_in_B + lcs_B_in_ref - lcs_C_in_ref
~~~
Pythons operator associativity ([link](https://www.faceprep.in/python/python-operator-precedence-associativity/)) for the `+` and `-` operator ensures, that all operations are performed from left to right. So in the previously shown example, we first calculate an intermediate coordinate system `lcs_A_in_ref` (`lcs_A_in_B + lcs_B_in_ref`) without actually storing it to a variable and subsequently transform it to the reference coordinate system C (`lcs_A_in_ref - lcs_C_in_ref`). Keep in mind, that the intermediate results and the coordinate system on the right-hand side of the next operator must either have a child-parent relation (`+` operator) or share a common coordinate system (`-` operator), otherwise the transformation chain produces invalid results.
You can think about both operators in the context of a tree-like graph structure where all dependency chains lead to a common root coordinate system. The `+` operator moves a coordinate system 1 level higher and closer to the root. Since its way to the root leads over its parent coordinate system, the parent is the only valid system than can be used on the right-hand side of the `+` operator. The `-` operator pushes a coordinate system one level lower and further away from the root. It can only be pushed one level deeper if there is another coordinate system connected to its parent system.
> TODO: Add pictures
### Interactive examples for the + and - operator
The following small interactive examples should give you a better understanding of how the `+` and `-` operators work. The examples provide several sliders to modify the orientations and positions of 2 coordinate systems. From those, a third coordinate system is calculated using the `+` and `-` operator. Subsequently, the coordinate systems are plotted in relation to each other. The relevant lines of code, which generate the coordinate systems are:
> **Hint:** The interactive plots need the `%matplotlib widget` magic command. Make sure you have the corresponding extensions installed and executed the command at the beginning of the tutorial
```
def coordinate_system_addition(parent_orientation, parent_coordinates, child_orientation, child_coordinates):
lcs_parent_in_ref = tf.LocalCoordinateSystem(orientation=parent_orientation, coordinates=parent_coordinates)
lcs_child_in_parent = tf.LocalCoordinateSystem(orientation=child_orientation, coordinates=child_coordinates)
lcs_child_in_ref = lcs_child_in_parent + lcs_parent_in_ref
return [lcs_parent_in_ref, lcs_child_in_parent, lcs_child_in_ref]
def coordinate_system_subtraction(
sys1_in_ref_orientation, sys1_in_ref_coordinates, sys2_in_ref_orientation, sys2_in_ref_coordinates
):
lcs_sys1_in_ref = tf.LocalCoordinateSystem(orientation=sys1_in_ref_orientation, coordinates=sys1_in_ref_coordinates)
lcs_sys2_in_ref = tf.LocalCoordinateSystem(orientation=sys2_in_ref_orientation, coordinates=sys2_in_ref_coordinates)
lcs_sys2_in_sys1 = lcs_sys2_in_ref - lcs_sys1_in_ref
lcs_sys1_in_sys2 = lcs_sys1_in_ref - lcs_sys2_in_ref
return [lcs_sys1_in_ref, lcs_sys2_in_ref, lcs_sys1_in_sys2, lcs_sys2_in_sys1]
```
Now just execute the following code cells. You don't need to understand them since they just create the sliders and plots:
```
def create_output_widget(window_size=900):
# create output widget that will hold the figure
out = widgets.Output(layout={"border": "2px solid black"})
# create figure inside output widget
with out:
fig = plt.figure()
try:
fig.canvas.layout.height = str(window_size) + "px"
fig.canvas.layout.width = str(window_size) + "px"
except:
pass
gs = fig.add_gridspec(3, 2)
ax_0 = fig.add_subplot(gs[0, 0], projection="3d")
ax_1 = fig.add_subplot(gs[0, 1], projection="3d")
ax_2 = fig.add_subplot(gs[1:, 0:], projection="3d")
return [out, fig, ax_0, ax_1, ax_2]
def setup_axes(axes, limit, title=""):
axes.set_xlim([-limit, limit])
axes.set_ylim([-limit, limit])
axes.set_zlim([-limit, limit])
axes.set_xlabel("x")
axes.set_ylabel("y")
axes.set_zlabel("z")
axes.set_title(title)
axes.legend(loc="lower left")
def get_orientation_and_location(t_x, t_y, t_z, r_x, r_y, r_z):
rot_angles = np.array([r_x, r_y, r_z], float) / 180 * np.pi
rot_x = tf.WXRotation.from_euler("x", rot_angles[0]).as_matrix()
rot_y = tf.WXRotation.from_euler("y", rot_angles[1]).as_matrix()
rot_z = tf.WXRotation.from_euler("z", rot_angles[2]).as_matrix()
orientation = np.matmul(rot_z, np.matmul(rot_y, rot_x))
location = [t_x, t_y, t_z]
return [orientation, location]
def create_slider(limit, step, label):
layout = widgets.Layout(width="200px", height="40px")
style = {"description_width": "initial"}
return FloatSlider(
min=-limit, max=limit, step=step, description=label, continuous_update=True, layout=layout, style=style
)
def create_interactive_plot(function, limit_loc=3, name_sys1="system 1", name_sys2="system 2"):
step_loc = 0.25
w_s1_l = dict(
s1_x=create_slider(limit_loc, step_loc, "x"),
s1_y=create_slider(limit_loc, step_loc, "y"),
s1_z=create_slider(limit_loc, step_loc, "z"),
)
w_s1_r = dict(
s1_rx=create_slider(180, 10, "x"), s1_ry=create_slider(180, 10, "y"), s1_rz=create_slider(180, 10, "z")
)
w_s2_l = dict(
s2_x=create_slider(limit_loc, step_loc, "x"),
s2_y=create_slider(limit_loc, step_loc, "y"),
s2_z=create_slider(limit_loc, step_loc, "z"),
)
w_s2_r = dict(
s2_rx=create_slider(180, 10, "x"), s2_ry=create_slider(180, 10, "y"), s2_rz=create_slider(180, 10, "z")
)
w = {**w_s1_l, **w_s1_r, **w_s2_l, **w_s2_r}
output = interactive_output(function, w)
box_0 = VBox([widgets.Label(name_sys1 + " coordinates"), *w_s1_l.values()])
box_1 = VBox([widgets.Label(name_sys1 + " rotation (deg)"), *w_s1_r.values()])
box_2 = VBox([widgets.Label(name_sys2 + " coordinates"), *w_s2_l.values()])
box_3 = VBox([widgets.Label(name_sys2 + " rotation (deg)"), *w_s2_r.values()])
box = HBox([box_0, box_1, box_2, box_3])
display(box)
axes_lim = 3
window_size = 1000
[out, fig_iadd, ax_iadd_0, ax_iadd_1, ax_iadd_2] = create_output_widget(window_size)
def update_output(s1_x, s1_y, s1_z, s1_rx, s1_ry, s1_rz, s2_x, s2_y, s2_z, s2_rx, s2_ry, s2_rz):
[parent_orientation, parent_coordinates] = get_orientation_and_location(s1_x, s1_y, s1_z, s1_rx, s1_ry, s1_rz)
[child_orientation, child_coordinates] = get_orientation_and_location(s2_x, s2_y, s2_z, s2_rx, s2_ry, s2_rz)
[lcs_parent, lcs_child, lcs_child_ref] = coordinate_system_addition(
parent_orientation, parent_coordinates, child_orientation, child_coordinates
)
coordinates_cr = lcs_child_ref.coordinates
cr_x = coordinates_cr[0]
cr_y = coordinates_cr[1]
cr_z = coordinates_cr[2]
ax_iadd_0.clear()
vs.draw_coordinate_system_matplotlib(lcs_ref, ax_iadd_0, color="r", label="reference")
vs.draw_coordinate_system_matplotlib(lcs_parent, ax_iadd_0, color="g", label="parent")
ax_iadd_0.plot([0, s1_x], [0, s1_y], [0, s1_z], "c--", label="ref -> parent")
setup_axes(ax_iadd_0, axes_lim, "'parent' in reference coordinate system")
ax_iadd_1.clear()
vs.draw_coordinate_system_matplotlib(lcs_ref, ax_iadd_1, color="g", label="parent")
vs.draw_coordinate_system_matplotlib(lcs_child, ax_iadd_1, color="y", label="child")
ax_iadd_1.plot([0, s2_x], [0, s2_y], [0, s2_z], "m--", label="parent -> child")
setup_axes(ax_iadd_1, axes_lim, "'child' in 'parent' coordinate system")
ax_iadd_2.clear()
vs.draw_coordinate_system_matplotlib(lcs_ref, ax_iadd_2, color="r", label="reference")
vs.draw_coordinate_system_matplotlib(lcs_parent, ax_iadd_2, color="g", label="parent")
vs.draw_coordinate_system_matplotlib(lcs_child_ref, ax_iadd_2, color="y", label="parent + child")
ax_iadd_2.plot([0, s1_x], [0, s1_y], [0, s1_z], "c--", label="ref -> parent")
ax_iadd_2.plot([s1_x, cr_x], [s1_y, cr_y], [s1_z, cr_z], "m--", label="parent -> child")
setup_axes(ax_iadd_2, axes_lim * 2, "'parent' and 'child' in reference coordinate system")
create_interactive_plot(update_output, limit_loc=axes_lim, name_sys1="parent", name_sys2="child")
out
axes_lim = 1.5
window_size = 1000
[out_2, fig2, ax_isub_0, ax_isub_1, ax_isub_2] = create_output_widget(window_size)
def update_output2(s1_x, s1_y, s1_z, s1_rx, s1_ry, s1_rz, s2_x, s2_y, s2_z, s2_rx, s2_ry, s2_rz):
[sys1_orientation, sys1_coordinates] = get_orientation_and_location(s1_x, s1_y, s1_z, s1_rx, s1_ry, s1_rz)
[sys2_orientation, sys2_coordinates] = get_orientation_and_location(s2_x, s2_y, s2_z, s2_rx, s2_ry, s2_rz)
[lcs_sys1_in_ref, lcs_sys2_in_ref, lcs_sys1_in_sys2, lcs_sys2_in_sys1] = coordinate_system_subtraction(
sys1_orientation, sys1_coordinates, sys2_orientation, sys2_coordinates
)
sys12_o = lcs_sys1_in_sys2.coordinates
sys12_x = sys12_o[0]
sys12_y = sys12_o[1]
sys12_z = sys12_o[2]
sys21_o = lcs_sys2_in_sys1.coordinates
sys21_x = sys21_o[0]
sys21_y = sys21_o[1]
sys21_z = sys21_o[2]
ax_isub_1.clear()
vs.draw_coordinate_system_matplotlib(lcs_ref, ax_isub_1, color="g", label="system 1 (reference)")
vs.draw_coordinate_system_matplotlib(lcs_sys2_in_sys1, ax_isub_1, color="b", label="system 2 - system 1")
ax_isub_1.plot([0, sys21_x], [0, sys21_y], [0, sys21_z], "y--", label="system 1 -> system 2")
setup_axes(ax_isub_1, axes_lim * 2, "'system 2' in 'system 1'")
ax_isub_0.clear()
vs.draw_coordinate_system_matplotlib(lcs_ref, ax_isub_0, color="b", label="system 2 (reference)")
vs.draw_coordinate_system_matplotlib(lcs_sys1_in_sys2, ax_isub_0, color="g", label="system_1 - system 2")
ax_isub_0.plot([0, sys12_x], [0, sys12_y], [0, sys12_z], "y--", label="system 1 -> system 2")
setup_axes(ax_isub_0, axes_lim * 2, "'system 1' in 'system 2'")
ax_isub_2.clear()
vs.draw_coordinate_system_matplotlib(lcs_ref, ax_isub_2, color="r", label="reference")
vs.draw_coordinate_system_matplotlib(lcs_sys1_in_ref, ax_isub_2, color="g", label="system 1")
vs.draw_coordinate_system_matplotlib(lcs_sys2_in_ref, ax_isub_2, color="b", label="system 2")
ax_isub_2.plot([0, s1_x], [0, s1_y], [0, s1_z], "g--", label="ref -> system 1")
ax_isub_2.plot([0, s2_x], [0, s2_y], [0, s2_z], "b--", label="ref -> system 2")
ax_isub_2.plot([s1_x, s2_x], [s1_y, s2_y], [s1_z, s2_z], "y--", label="system 1 <-> system 2")
setup_axes(ax_isub_2, axes_lim, "'system 1' and 'system 2' in reference coordinate system")
create_interactive_plot(update_output2, limit_loc=axes_lim)
out_2
```
## Invert method
The `invert` method calculates how a parent coordinate system is positioned and oriented in its child coordinate system:
~~~ python
lcs_child_in_parent = lcs_parent_in_child.invert()
~~~
Here is a short example with visualization:
```
lcs_child_in_parent = tf.LocalCoordinateSystem.from_euler(
sequence="xy", angles=[90, 45], degrees=True, coordinates=[2, 3, 0]
)
lcs_parent_in_child = lcs_child_in_parent.invert()
```
**Plot:**
```
_, (ax_invert_0, ax_invert_1) = vs.new_3d_figure_and_axes(num_subplots=2, width=1000)
# left plot
vs.plot_coordinate_systems([(lcs_ref, {"color":"r", "label":"parent"}),
(lcs_child_in_parent, {"color":"g", "label":"child"})],
axes=ax_invert_0,
limits=(-3, 3),
title="child in parent")
# right plot
vs.plot_coordinate_systems([(lcs_parent_in_child, {"color":"r", "label":"parent"}),
(lcs_ref, {"color":"g", "label":"child"})],
axes=ax_invert_1,
limits=(-3, 3),
title="parent in child")
```
## Time dependency
The orientation and position of a local coordinate system towards their reference system might vary in time. For example, in a welding process, the position of the torch towards the specimen is changing constantly. The `LocalCoordinateSystem` provides an interface for such cases. All previously shown construction methods also provide the option to pass a `time` parameter.
> **IMPORTANT HINT:** In the current package version, only the constructors `time` parameter is actually working
> **TODO:** Rewrite examples if factory methods also support time dependency
To create a time-dependent system, you have to provide a list of timestamps that can be converted to a `pandas.DateTimeIndex`. If you do, you also need to provide the extra data for the `orientation` and/or `coordinates` to the constructor or construction method. You do this by adding an extra outer dimension to the corresponding time-dependent function parameter. For example: If you want to create a moving coordinate system with 2 timestamps, you can do it by like this:
~~~ python
time = ["2010-02-01", "2010-02-02"]
# fixed orientation (no extra dimension)
orientation_mov = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
# time dependent coordinates (extra dimension)
coordinates_mov = [[-3, 0, 0], [0, 0, 2]]
lcs_mov_in_ref = tf.LocalCoordinateSystem(orientation=orientation_mov, coordinates=coordinates_mov, time=time)
~~~
A coordinate system with varying orientation between 2 timestamps is defined by:
~~~ python
time = ["2010-02-01", "2010-02-02"]
# time dependent orientation (extra coordinate)
orientation_rot = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, -1, 0], [1, 0, 0], [0, 0, 1]]]
# fixed coordinates (no extra dimension)
coordinates_rot = [1, 0, 2]
lcs_rot_in_ref = tf.LocalCoordinateSystem(orientation=orientation_rot, coordinates=coordinates_rot, time=time)
~~~
You can also create a rotating and moving coordinate system:
~~~ python
time = ["2010-02-01", "2010-02-02"]
coordinates_movrot = [[0, 3, 0], [-2, 3, 2]]
orientation_movrot = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, -1, 0], [1, 0, 0], [0, 0, 1]]]
lcs_movrot_in_ref = tf.LocalCoordinateSystem(orientation=orientation_movrot, coordinates=coordinates_movrot, time=time)
~~~
You have to ensure, that the extra outer dimension has always the same number of entries as a number of timestamps you provided. Otherwise, an exception is raised. In case your coordinate system data is not always providing orientation and coordinates at the same time, you need to interpolate the missing values first.
Here is a visualization of the discussed coordinate systems at the two different times:
```
# define coordinate systems
time = ["2010-02-01", "2010-02-02"]
orientation_mov = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
coordinates_mov = [[-3, 0, 0], [0, 0, 2]]
lcs_mov_in_ref = tf.LocalCoordinateSystem(orientation=orientation_mov, coordinates=coordinates_mov, time=time)
orientation_rot = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, -1, 0], [1, 0, 0], [0, 0, 1]]]
coordinates_rot = [1, 0, 2]
lcs_rot_in_ref = tf.LocalCoordinateSystem(orientation=orientation_rot, coordinates=coordinates_rot, time=time)
coordinates_movrot = [[0, 3, 0], [-2, 3, 2]]
orientation_movrot = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, -1, 0], [1, 0, 0], [0, 0, 1]]]
lcs_movrot_in_ref = tf.LocalCoordinateSystem(orientation=orientation_movrot, coordinates=coordinates_movrot, time=time)
```
**Plot:**
```
# plot coordinate systems
_, axes_array = vs.new_3d_figure_and_axes(num_subplots=2, width=1000)
for i, ax in enumerate(axes_array):
vs.plot_coordinate_systems([(lcs_ref, {"color":"r", "label":"reference"}),
(lcs_mov_in_ref, {"color":"g", "label":"lcs_mov_in_ref"}),
(lcs_rot_in_ref, {"color":"b", "label":"lcs_rot_in_ref"}),
(lcs_movrot_in_ref, {"color":"c", "label":"lcs_movrot_in_ref"})],
axes=ax,
limits=(-3, 3),
title=f"timestep {i}",
time_index=i)
```
## Time interpolation
It is also possible, to interpolate a coordinate system's orientations and coordinates in time by using the `interp_time` function. You have to pass it a single or multiple target times for the interpolation. As for the constructor, you can pass any type that is convertible to a `pandas.DatetimeIndex`. Alternatively, you can pass another `LocalCoordinateSystem` which provides the target timestamps. The return value of this function is a new `LocalCoordinateSystem` with interpolated orientations and coordinates.
In case that a target time for the interpolation lies outside of the `LocalCoordinateSystem`s' time range, the boundary value is broadcasted.
Here is an example:
```
# original coordinate system
time = ["2010-02-02", "2010-02-07"]
coordinates_tdp = [[0, 3, 0], [-2, 3, 2]]
orientation_tdp = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, -1, 0], [1, 0, 0], [0, 0, 1]]]
lcs_tdp_in_ref = tf.LocalCoordinateSystem(orientation=orientation_movrot, coordinates=coordinates_movrot, time=time)
time_interp = pd.DatetimeIndex(["2010-02-01", "2010-02-03", "2010-02-04", "2010-02-05", "2010-02-06", "2010-02-11"])
lcs_interp_in_ref = lcs_tdp_in_ref.interp_time(time_interp)
```
**Plot:**
```
# plot coordinate systems
_, (ax_0_interp, ax_1_interp) = vs.new_3d_figure_and_axes(num_subplots=2, width=1000)
# original systems
vs.plot_coordinate_systems([(lcs_ref, {"color":"r", "label":"reference"}),
(lcs_tdp_in_ref, {"color":"g", "label":"2010-02-01", "time_index":0}),
(lcs_tdp_in_ref, {"color":"b", "label":"2010-02-07", "time_index":1})],
axes=ax_0_interp,
limits=(-3, 3),
title="original system")
# interpolated systems
colors = [[0, 1, 0], [0, 1, 0.5], [0, 1, 1], [0, 0.5, 1], [0, 0, 1], [0.5, 0, 1]]
plot_data = [
(lcs_interp_in_ref, {"color":colors[i], "label":time_interp[i], "time_index":i})
for i in range(len(time_interp))
]
plot_data = [(lcs_ref, {"color":"r", "label":"reference"}), *plot_data]
vs.plot_coordinate_systems(plot_data,
axes=ax_1_interp,
limits=(-3, 3),
title="interpolated system")
```
As you can see, the time values `"2010-02-01"` and `"2010-02-11"`, which lie outside the original range from `"2010-02-02"` and `"2010-02-07"` still get valid values due to the broadcasting across time range boundaries. The intermediate coordinates and orientations are interpolated as expected.
> **TODO:** Mention interpolation behavior of `+` and `*`
## Transformation of spatial data
The `LocalCoordinateSystem` only defines how the different coordinate systems are oriented towards each other. If you want to transform spatial data which is defined in one coordinate system (for example specimen geometry/point cloud) you have to use the `CoordinateSystemManager`, which is discussed in the next tutorial or do the transformation manually.
For the manual transformation, you can get all you need from the `LocalCoordinateSystem` using its accessor properties:
~~~
orientation = lcs_a_in_b.orientation
coordinates = lcs_a_in_b.coordinates
~~~
The returned data is an `xarray.DataFrame`. In case you are not used to work with this data type, you can get a `numpy.ndarray` by simply using their `data` property:
~~~
orientation_numpy = lcs_a_in_b.orientation.data
coordinates_numpy = lcs_a_in_b.coordinates.data
~~~
Keep in mind, that you actually get an array of matrices (`orientation`) and vectors (`coordinates`) if the corresponding component is time dependent. The transformation itself is done by the equation:
$$v_b = O_{ab} \cdot v_a + c_{ab}$$
where $v_a$ is a data point defined in coordinate system `a`, $O_{ab}$ is the orientation matrix of `a` in `b`, $c_{ab}$ the coordinates of `a` in `b` and $v_b$ the transformed data point.
Here is a short example that transforms the points of a square from one coordinate system to another:
```
lcs_target_in_ref = tf.LocalCoordinateSystem.from_euler(
sequence="zy", angles=[90, 45], degrees=True, coordinates=[2, -2, 0]
)
lcs_ref_in_target = lcs_target_in_ref.invert()
points_in_ref = np.array([[-1, 1, 0], [1, 1, 0], [1, -1, 0], [-1, -1, 0], [-1, 1, 0]], dtype=float).transpose()
# Transform points to target system
points_in_target = (
np.matmul(lcs_ref_in_target.orientation.data, points_in_ref) + lcs_ref_in_target.coordinates.data[:, np.newaxis]
)
```
**Plot:**
```
# plot coordinate systems
_, (ax_0_trans, ax_1_trans) = vs.new_3d_figure_and_axes(num_subplots=2, width=1000)
# first plot
vs.plot_coordinate_systems([(lcs_ref, {"color":"r", "label":"original system"}),
(lcs_target_in_ref, {"color":"g", "label":"target system"})],
axes=ax_0_trans,
limits=(-3, 3),
title="Data in original system")
ax_0_trans.plot(points_in_ref[0], points_in_ref[1], points_in_ref[2])
# second plot
vs.plot_coordinate_systems([(lcs_ref_in_target, {"color":"r", "label":"original system"}),
(lcs_ref, {"color":"g", "label":"target system"})],
axes=ax_1_trans,
limits=(-3, 3),
title="Data in original system")
ax_1_trans.plot(points_in_target[0], points_in_target[1], points_in_target[2])
```
## Internal xarray structure
The local coordinate system and many other components of the WeldX package use xarray data frames internally. So it is also possible to pass xarray data frames to a lot of functions and the constructor. However, they need a certain structure which will be described here. If you are not familiar with the xarray package, you should first read the [documentation](http://xarray.pydata.org/en/stable/).
To pass a xarray data frame as coordinate to a `LocalCoordinateSystem`, it must at least have a dimension `c`. It represents the location in 3d space of the coordinate system and must always be of length 3. Those components must be named coordinates of the data frame (`coords={"c": ["x", "y", "z"]}`). An optional dimension is `time`. It can be of arbitrary length, but the timestamps must be added as coordinates.
The same conventions that are used for the coordinates also apply to the orientations. Additionally, they must have another dimension `v` of length 3, which are enumerated (`"v": [0, 1, 2]`). `c` and `v` are the rows and columns of the orientation matrix.
**Example:**
```
time = pd.TimedeltaIndex([0,5],"D")
coordinates_tdp = [[0, 3, 0], [-2, 3, 2]]
orientation_tdp = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, -1, 0], [1, 0, 0], [0, 0, 1]]]
dsx_coordinates = xr.DataArray(data=coordinates_tdp, dims=["time", "c"], coords={"time": time, "c": ["x", "y", "z"]})
dsx_orientation = xr.DataArray(
data=orientation_tdp, dims=["time", "c", "v"], coords={"time": time, "c": ["x", "y", "z"], "v": [0, 1, 2]},
)
lcs_xr = tf.LocalCoordinateSystem(orientation=dsx_orientation, coordinates=dsx_coordinates)
```
**Plot:**
```
# plot coordinate systems
_, ax_dsx = vs.new_3d_figure_and_axes()
# first timestep
vs.plot_coordinate_systems([(lcs_ref, {"color":"r", "label":"reference"}),
(lcs_xr, {"color":"g", "label":str(lcs_xr.time[0]), "time_index":0}),
(lcs_xr, {"color":"b", "label":str(lcs_xr.time[1]), "time_index":1})],
axes=ax_dsx,
limits=(-3, 3))
```
The `weldx.utility` package contains two utility functions to create xarray data frames that can be passed as `orientation` and `coordinates` to an `LocalCoordinateSystem`. They are named `xr_3d_vector` and `xr_3d_matrix`. Please read the API documentation for further information.
| github_jupyter |
```
from py2neo import Graph,Node,Relationship
import pandas as pd
import os
import QUANTAXIS as QA
import datetime
import numpy as np
import statsmodels.formula.api as sml
from QAStrategy.qastockbase import QAStrategyStockBase
import matplotlib.pyplot as plt
import scipy.stats as scs
import matplotlib.mlab as mlab
from easyquant.indicator.base import *
import json
from easyquant import MongoIo
import statsmodels.api as sm
from multiprocessing import Process, Pool, cpu_count, Manager
mongo = MongoIo()
def tdx_base_func(data, code_list = None):
"""
准备数据
"""
# highs = data.high
# start_t = datetime.datetime.now()
# print("begin-tdx_base_func:", start_t)
if len(data) < 10:
data = data.copy()
data['bflg'] = 0
data['sflg'] = 0
return data
CLOSE=data.close
C=data.close
# df_macd = MACD(C,12,26,9)
# mtj1 = IFAND(df_macd.DIFF < 0, df_macd.DEA < 0, 1, 0)
# mtj2 = IFAND(mtj1, df_macd.MACD < 0, 1, 0)
花 = SLOPE(EMA(C, 3), 3)
神 = SLOPE(EMA(C, 7), 7)
买 = IFAND(COUNT(花 < 神, 5)==4 , 花 >= 神,1,0)
卖 = IFAND(COUNT(花 >= 神, 5)==4, 花 < 神,1,0)
钻石 = IFAND(CROSS(花, 神), CLOSE / REF(CLOSE, 1) > 1.03, 1, 0)
买股 = IFAND(买, 钻石,1,0)
# 买股 = IFAND(mtj2, 买股1, 1, 0)
# AND(CROSS(花, 神)
# AND
# CLOSE / REF(CLOSE, 1) > 1.03);
# return pd.DataFrame({'FLG': 后炮}).iloc[-1]['FLG']
# return 后炮.iloc[-1]
# 斜率
data = data.copy()
# data['bflg'] = IF(REF(后炮,1) > 0, 1, 0)
data['bflg'] = 买股
data['sflg'] = 卖
# print("code=%s, bflg=%s" % (code, data['bflg'].iloc[-1]))
# data['beta'] = 0
# data['R2'] = 0
# beta_rsquared = np.zeros((len(data), 2),)
#
# for i in range(N - 1, len(highs) - 1):
# #for i in range(len(highs))[N:]:
# df_ne = data.iloc[i - N + 1:i + 1, :]
# model = sml.ols(formula='high~low', data = df_ne)
# result = model.fit()
#
# # beta = low
# beta_rsquared[i + 1, 0] = result.params[1]
# beta_rsquared[i + 1, 1] = result.rsquared
#
# data[['beta', 'R2']] = beta_rsquared
# 日收益率
data['ret'] = data.close.pct_change(1)
# 标准分
# data['beta_norm'] = (data['beta'] - data.beta.rolling(M).mean().shift(1)) / data.beta.rolling(M).std().shift(1)
#
# beta_norm = data.columns.get_loc('beta_norm')
# beta = data.columns.get_loc('beta')
# for i in range(min(M, len(highs))):
# data.iat[i, beta_norm] = (data.iat[i, beta] - data.iloc[:i - 1, beta].mean()) / data.iloc[:i - 1, beta].std() if (data.iloc[:i - 1, beta].std() != 0) else np.nan
# data.iat[2, beta_norm] = 0
# data['RSRS_R2'] = data.beta_norm * data.R2
# data = data.fillna(0)
#
# # 右偏标准分
# data['beta_right'] = data.RSRS_R2 * data.beta
# if code == '000732':
# print(data.tail(22))
return data
def buy_sell_fun(price, S1=1.0, S2=0.8):
"""
斜率指标交易策略标准分策略
"""
data = price.copy()
data['flag'] = 0 # 买卖标记
data['position'] = 0 # 持仓标记
data['hold_price'] = 0 # 持仓价格
bflag = data.columns.get_loc('bflg')
sflag = data.columns.get_loc('sflg')
# beta = data.columns.get_loc('beta')
flag = data.columns.get_loc('flag')
position_col = data.columns.get_loc('position')
close_col = data.columns.get_loc('close')
high_col = data.columns.get_loc('high')
open_col = data.columns.get_loc('open')
hold_price_col = data.columns.get_loc('hold_price')
position = 0 # 是否持仓,持仓:1,不持仓:0
for i in range(1,data.shape[0] - 1):
# 开仓
if data.iat[i, bflag] > 0 and position == 0:
data.iat[i, flag] = 1
data.iat[i, position_col] = 1
data.iat[i, hold_price_col] = data.iat[i, open_col]
data.iat[i + 1, position_col] = 1
data.iat[i + 1, hold_price_col] = data.iat[i, open_col]
position = 1
print("buy : date=%s code=%s price=%.2f" % (data.iloc[i].name[0], data.iloc[i].name[1], data.iloc[i].close))
code = data.iloc[i].name[1]
price = data.iloc[i].close
# qa_order.send_order('BUY', 'OPEN', code=code, price=price, volume=1000)
# order.send_order('SELL', 'CLOSE', code=code, price=price, volume=1000)
# 平仓
# elif data.iat[i, bflag] == S2 and position == 1:
elif data.iat[i, position_col] > 0 and position == 1:
cprice = data.iat[i, close_col]
# oprice = data.iat[i, open_col]
hole_price = data.iat[i, hold_price_col]
high_price = data.iat[i, high_col]
if cprice < hole_price * 0.95:# or cprice > hprice * 1.2:
data.iat[i, flag] = -1
data.iat[i + 1, position_col] = 0
data.iat[i + 1, hold_price_col] = 0
position = 0
print("sell : code=%s date=%s price=%.2f" % (data.iloc[i].name[0], data.iloc[i].name[1], data.iloc[i].close))
code = data.iloc[i].name[1]
price = data.iloc[i].close
# order.send_order('BUY', 'OPEN', code=code, price=price, volume=1000)
# qa_order.send_order('SELL', 'CLOSE', code=code, price=price, volume=1000)
elif cprice > hole_price * 1.1 and high_price / cprice > 1.05:
data.iat[i, flag] = -1
data.iat[i + 1, position_col] = 0
data.iat[i + 1, hold_price_col] = 0
position = 0
print("sell : code=%s date=%s price=%.2f" % (data.iloc[i].name[0], data.iloc[i].name[1], data.iloc[i].close))
code = data.iloc[i].name[1]
price = data.iloc[i].close
# order.send_order('BUY', 'OPEN', code=code, price=price, volume=1000)
# qa_order.send_order('SELL', 'CLOSE', code=code, price=price, volume=1000)
elif cprice > hole_price * 1.2 and high_price / cprice > 1.06:
data.iat[i, flag] = -1
data.iat[i + 1, position_col] = 0
data.iat[i + 1, hold_price_col] = 0
position = 0
print("sell : code=%s date=%s price=%.2f" % (data.iloc[i].name[0], data.iloc[i].name[1], data.iloc[i].close))
code = data.iloc[i].name[1]
price = data.iloc[i].close
# order.send_order('BUY', 'OPEN', code=code, price=price, volume=1000)
# qa_order.send_order('SELL', 'CLOSE', code=code, price=price, volume=1000)
elif data.iat[i, sflag] > 0:
data.iat[i, flag] = -1
data.iat[i + 1, position_col] = 0
data.iat[i + 1, hold_price_col] = 0
position = 0
print("sell : code=%s date=%s price=%.2f" % (data.iloc[i].name[0], data.iloc[i].name[1], data.iloc[i].close))
code = data.iloc[i].name[1]
price = data.iloc[i].close
# order.send_order('BUY', 'OPEN', code=code, price=price, volume=1000)
# qa_order.send_order('SELL', 'CLOSE', code=code, price=price, volume=1000)
else:
data.iat[i + 1, position_col] = data.iat[i, position_col]
data.iat[i + 1, hold_price_col] = data.iat[i, hold_price_col]
# 保持
else:
data.iat[i + 1, position_col] = data.iat[i, position_col]
data.iat[i + 1, hold_price_col] = data.iat[i, hold_price_col]
data['nav'] = (1+data.close.pct_change(1).fillna(0) * data.position).cumprod()
data['nav1'] = data.close * data.position
return data
df=mongo.get_stock_day('600718')
df.tail()
data1=buy_sell_fun(df1)
df1=tdx_base_func(df)
df1.tail()
data1.loc['2018-04-10':]
a = np.array([10,11,13,15,12,7,14])
ap = np.array([1,1,1,1,1,0,0])
b = np.array([1.2,1.1,1.8,1.5,1.2,0.7,1.4])
# a = np.array([[10,11,13,15,12,7,14],[10,11,18,15,12,7,14]])
dfn=pd.Series(a)
dfb=pd.Series(b)
df=pd.DataFrame()
df['a']=pd.Series(a)
df['ap']=pd.Series(ap)
df
bc1=(1+dfn.pct_change(1).fillna(0)).cumprod()
bc2=(1+dfb.pct_change(1).fillna(0)).cumprod()
bc2
result01=bc2
round(float(max([(result01.iloc[idx] - result01.iloc[idx::].min()) / result01.iloc[idx] for idx in range(len(result01))])), 2)
bc
```
| github_jupyter |
# Integrating TAO Models in DeepStream
In the first of two notebooks, we will be building a 4-class object detection pipeline as shown in the illustration below using Nvidia's TrafficCamNet pretrained model, directly downloaded from NGC.
Note: This notebook has code inspired from a sample application provided by NVIDIA in a GitHub repository. You can find this repository [here](https://github.com/NVIDIA-AI-IOT/deepstream_python_apps).
## The Pipeline

We notice there are multiple DeepStream plugins used in the pipeline , Let us have a look at them and try to understand them.
## NVIDIA DeepStream Plugins
### Nvinfer
The nvinfer plugin provides [TensorRT](https://docs.nvidia.com/deeplearning/tensorrt/developer-guide/index.html)-based inference for detection and tracking. The lowlevel library (libnvds_infer) operates either on float RGB or BGR planar data with dimensions of Network Height and Network Width. The plugin accepts NV12/RGBA data from upstream components like the decoder, muxer, and dewarper.
The Gst-nvinfer plugin also performs preprocessing operations like format conversion, scaling, mean subtraction, and produces final float RGB/BGR planar data which is passed to the low-level library. The low-level library uses the TensorRT engine for inferencing. It outputs each classified object’s class and each detected object’s bounding boxes (Bboxes) after clustering.

### Nvvidconv
We create the nvvidconv plugin that performs color format conversions, which is required to make data ready for the nvosd plugin.

### Nvosd
The nvosd plugin draws bounding boxes, text, and RoI (Regions of Interest) polygons (Polygons are presented as a set of lines). The plugin accepts an RGBA buffer with attached metadata from the upstream component. It
draws bounding boxes, which may be shaded depending on the configuration (e.g. width, color, and opacity) of a given bounding box. It also draws text and RoI polygons at specified locations in the frame. Text and polygon parameters are configurable through metadata.

Now with this idea , let us get started into building the pipeline.
# Building the pipeline

```
# Import Required Libraries
import sys
sys.path.append('../source_code')
import gi
import time
gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst, GLib
from common.bus_call import bus_call
import pyds
# Defining the Class Labels
PGIE_CLASS_ID_VEHICLE = 0
PGIE_CLASS_ID_BICYCLE = 1
PGIE_CLASS_ID_PERSON = 2
PGIE_CLASS_ID_ROADSIGN = 3
# Defining the input output video file
INPUT_VIDEO_NAME = '../videos/sample_720p.h264'
OUTPUT_VIDEO_NAME = "../videos/out.mp4"
```
We define a function `make_elm_or_print_err()` to create our elements and report any errors if the creation fails.
Elements are created using the `Gst.ElementFactory.make()` function as part of Gstreamer library.
```
## Make Element or Print Error and any other detail
def make_elm_or_print_err(factoryname, name, printedname, detail=""):
print("Creating", printedname)
elm = Gst.ElementFactory.make(factoryname, name)
if not elm:
sys.stderr.write("Unable to create " + printedname + " \n")
if detail:
sys.stderr.write(detail)
return elm
```
#### Initialise GStreamer and Create an Empty Pipeline
```
# Standard GStreamer initialization
Gst.init(None)
# Create Gstreamer elements
# Create Pipeline element that will form a connection of other elements
print("Creating Pipeline \n ")
pipeline = Gst.Pipeline()
if not pipeline:
sys.stderr.write(" Unable to create Pipeline \n")
```
#### Create Elements that are required for our pipeline
```
# Creating elements required for the pipeline
# Source element for reading from file
source = make_elm_or_print_err("filesrc", "file-source","Source")
# Parse the data since the input is an elementary .h264 stream
h264parser = make_elm_or_print_err("h264parse", "h264-parser","h264 parse")
# For hardware accelerated decoding of the stream
decoder = make_elm_or_print_err("nvv4l2decoder", "nvv4l2-decoder","Nvv4l2 Decoder")
# Form batches from one or more sources
streammux = make_elm_or_print_err("nvstreammux", "Stream-muxer",'NvStreamMux')
# Run inference on the decoded stream, this property is set through a configuration file later
pgie = make_elm_or_print_err("nvinfer", "primary-inference" ,"pgie")
# Convert output stream to formatted buffer accepted by Nvosd
nvvidconv = make_elm_or_print_err("nvvideoconvert", "convertor","nvvidconv")
# Draw on the buffer
nvosd = make_elm_or_print_err("nvdsosd", "onscreendisplay","nvosd")
# Encode and save the OSD output
queue = make_elm_or_print_err("queue", "queue", "Queue")
# Convert output for saving
nvvidconv2 = make_elm_or_print_err("nvvideoconvert", "convertor2","nvvidconv2")
# Save as video file
encoder = make_elm_or_print_err("avenc_mpeg4", "encoder", "Encoder")
# Parse output from encoder
codeparser = make_elm_or_print_err("mpeg4videoparse", "mpeg4-parser", 'Code Parser')
# Create a container
container = make_elm_or_print_err("qtmux", "qtmux", "Container")
# Create sink for string the output
sink = make_elm_or_print_err("filesink", "filesink", "Sink")
```
Now that we have created the elements ,we can now set various properties for out pipeline at this point.
### Understanding the configuration file
We set an `config-file-path` for our nvinfer ( Interference plugin ) and it points to the file `config_infer_primary_trafficcamnet.txt`
You can have a have a look at the [file](../configs/config_infer_primary_trafficcamnet.txt)
Here are some parts of the configuration file :
```
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
#
# NVIDIA Corporation and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA Corporation is strictly prohibited.
[property]
gpu-id=0
net-scale-factor=0.0039215697906911373
tlt-model-key=tlt_encode
tlt-encoded-model=../models/trafficcamnet/resnet18_trafficcamnet_pruned.etlt
labelfile-path=labels_trafficnet.txt
int8-calib-file=../models/trafficcamnet/trafficnet_int8.bin
model-engine-file=../models/trafficcamnet/resnet18_trafficcamnet_pruned.etlt_b1_gpu0_int8.engine
input-dims=3;544;960;0
uff-input-blob-name=input_1
batch-size=1
process-mode=1
model-color-format=0
## 0=FP32, 1=INT8, 2=FP16 mode
network-mode=2
num-detected-classes=4
interval=0
gie-unique-id=1
output-blob-names=output_bbox/BiasAdd;output_cov/Sigmoid
[class-attrs-all]
pre-cluster-threshold=0.2
group-threshold=1
## Set eps=0.7 and minBoxes for cluster-mode=1(DBSCAN)
eps=0.2
#minBoxes=3
```
Here we define all the parameters of our model. In this example we use model-file `resnet18_trafficcamnet_pruned`. `Nvinfer` creates an TensorRT Engine specific to the Host GPU to accelerate it's inference performance.
```
# Set properties for elements
print("Playing file %s" %INPUT_VIDEO_NAME)
# Set input file
source.set_property('location', INPUT_VIDEO_NAME)
# Set input height, width, and batch size
streammux.set_property('width', 1920)
streammux.set_property('height', 1080)
streammux.set_property('batch-size', 1)
# Set timer (in microseconds) to wait after the first buffer is available
# to push the batch even if batch is never completely formed
streammux.set_property('batched-push-timeout', 4000000)
# Set configuration files for Nvinfer
pgie.set_property('config-file-path', "../configs/config_infer_primary_trafficcamnet.txt")
# Set encoder bitrate for output video
encoder.set_property("bitrate", 2000000)
# Set output file location, disable sync and async
sink.set_property("location", OUTPUT_VIDEO_NAME)
sink.set_property("sync", 0)
sink.set_property("async", 0)
```
We now link all the elements in the order we prefer and create Gstreamer bus to feed all messages through it.
```
# Add and link all elements to the pipeline
# Adding elements
print("Adding elements to Pipeline \n")
pipeline.add(source)
pipeline.add(h264parser)
pipeline.add(decoder)
pipeline.add(streammux)
pipeline.add(pgie)
pipeline.add(nvvidconv)
pipeline.add(nvosd)
pipeline.add(queue)
pipeline.add(nvvidconv2)
pipeline.add(encoder)
pipeline.add(codeparser)
pipeline.add(container)
pipeline.add(sink)
# Linking elements
# Order: source -> h264parser -> decoder -> streammux -> pgie ->
# -> vidconv -> osd -> queue -> vidconv2 -> encoder -> parser ->
# -> container -> sink
print("Linking elements in the Pipeline \n")
source.link(h264parser)
h264parser.link(decoder)
sinkpad = streammux.get_request_pad("sink_0")
if not sinkpad:
sys.stderr.write(" Unable to get the sink pad of streammux \n")
# Create source pad from Decoder
srcpad = decoder.get_static_pad("src")
if not srcpad:
sys.stderr.write(" Unable to get source pad of decoder \n")
srcpad.link(sinkpad)
streammux.link(pgie)
pgie.link(nvvidconv)
nvvidconv.link(nvosd)
nvosd.link(queue)
queue.link(nvvidconv2)
nvvidconv2.link(encoder)
encoder.link(codeparser)
codeparser.link(container)
container.link(sink)
# Create an event loop and feed GStreamer bus messages to it
loop = GLib.MainLoop()
bus = pipeline.get_bus()
bus.add_signal_watch()
bus.connect ("message", bus_call, loop)
```
## Working with the Metadata
Our pipeline now carries the metadata forward but we have not done anything with it until now, but as mentoioned in the above pipeline diagram , we will now create a callback function to write relevant data on the frame once called and create a sink pad in the `nvosd` element to call the function.
```
# Working with metadata
def osd_sink_pad_buffer_probe(pad,info,u_data):
obj_counter = {
PGIE_CLASS_ID_VEHICLE:0,
PGIE_CLASS_ID_PERSON:0,
PGIE_CLASS_ID_BICYCLE:0,
PGIE_CLASS_ID_ROADSIGN:0
}
# Reset frame number and number of rectanges to zero
frame_number=0
num_rects=0
gst_buffer = info.get_buffer()
if not gst_buffer:
print("Unable to get GstBuffer ")
return
# Retrieve metadata from gst_buffer
# Note: since we use the pyds shared object library,
# the input is the C address of gst_buffer
batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer))
l_frame = batch_meta.frame_meta_list
while l_frame is not None:
try:
frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data)
except StopIteration:
break
# Get frame number, number of rectangles to draw and object metadata
frame_number=frame_meta.frame_num
num_rects = frame_meta.num_obj_meta
l_obj=frame_meta.obj_meta_list
while l_obj is not None:
try:
obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data)
except StopIteration:
break
# Increment object class by 1 and set box border color to red
obj_counter[obj_meta.class_id] += 1
obj_meta.rect_params.border_color.set(0.0, 0.0, 1.0, 0.0)
try:
l_obj=l_obj.next
except StopIteration:
break
# Setting metadata display configuration
# Acquire display meta object
display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta)
display_meta.num_labels = 1
py_nvosd_text_params = display_meta.text_params[0]
# Set display text to be shown on screen
py_nvosd_text_params.display_text = "Frame Number={} Number of Objects={} Vehicle_count={} Person_count={}".format(frame_number, num_rects, obj_counter[PGIE_CLASS_ID_VEHICLE], obj_counter[PGIE_CLASS_ID_PERSON])
# Set where the string will appear
py_nvosd_text_params.x_offset = 10
py_nvosd_text_params.y_offset = 12
# Font, font colour and font size
py_nvosd_text_params.font_params.font_name = "Serif"
py_nvosd_text_params.font_params.font_size = 10
# Set color (We used white)
py_nvosd_text_params.font_params.font_color.set(1.0, 1.0, 1.0, 1.0)
# Set text background colour (We used black)
py_nvosd_text_params.set_bg_clr = 1
py_nvosd_text_params.text_bg_clr.set(0.0, 0.0, 0.0, 1.0)
# Print the display text in the console as well
print(pyds.get_string(py_nvosd_text_params.display_text))
pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta)
try:
l_frame=l_frame.next
except StopIteration:
break
return Gst.PadProbeReturn.OK
# Adding probe to sinkpad of the OSD element
osdsinkpad = nvosd.get_static_pad("sink")
if not osdsinkpad:
sys.stderr.write(" Unable to get sink pad of nvosd \n")
osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0)
```
Now with everything defined , we can start the playback and listen the events.
```
# Start the pipeline
print("Starting pipeline \n")
start_time = time.time()
pipeline.set_state(Gst.State.PLAYING)
try:
loop.run()
except:
pass
# Cleanup
pipeline.set_state(Gst.State.NULL)
print("--- %s seconds ---" % (time.time() - start_time))
```
This video output is not compatible to be shown in this Notebook. To circumvent this, we convert the output in a Jupyter Notebook-readable format. For this we use the shell command `ffmpeg`.
```
# Convert video profile to be compatible with the Notebook
!ffmpeg -loglevel panic -y -an -i ../videos/out.mp4 -vcodec libx264 -pix_fmt yuv420p -profile:v baseline -level 3 ../videos/output.mp4
```
Finally, we display the output in the notbook by creating an HTML video element.
```
# Display the Output
from IPython.display import HTML
HTML("""
<video width="640" height="480" controls>
<source src="../videos/output.mp4"
</video>
""".format())
```
In the next notebook , we will learn about object tracking and build an attribute classification pipeline along with the primary inference built in this notebook.
| github_jupyter |
# Customer segmentation using k-means clustering
Below is a demo applying automated feature engineering to a retail dataset to automatically segment customers based on historical behavior
```
import featuretools as ft
import pandas as pd
retail_es = ft.demo.load_retail()
```
## Use Deep Feature Synthesis
The input to DFS is a set of entities and a list of relationships (defined by our EntitySet) and the "target_entity" to calculate features for. We can supply "cutoff times" to specify the that we want to calculate features one year after a customers first invoices.
The ouput of DFS is a feature matrix and the corresponding list of feature defintions
```
from featuretools.primitives import AvgTimeBetween, Mean, Sum, Count, Day
feature_matrix, features = ft.dfs(entityset=retail_es, target_entity="customers",
agg_primitives=[AvgTimeBetween, Mean, Sum, Count],
trans_primitives=[Day], max_depth=5, verbose=True)
feature_matrix, features = ft.encode_features(feature_matrix, features)
from sklearn import decomposition
from sklearn.preprocessing import Imputer, StandardScaler
# Create our imputer to replace missing values with the mean e.g.
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
X = imp.fit_transform(feature_matrix.values)
scale = StandardScaler()
X = scale.fit_transform(X)
pca = decomposition.PCA(n_components=10)
X_pca = pca.fit_transform(X)
from sklearn import preprocessing, manifold
# Reduce dimension to 2-D
tsne = manifold.TSNE(n_components=2)
X_2_dim = tsne.fit_transform(X_pca)
from sklearn import preprocessing, decomposition, cluster
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline
# do kmeans clustering
n_clusters=10
clust = cluster.MiniBatchKMeans(n_clusters=n_clusters,
reassignment_ratio=.03,
batch_size=1000,
n_init=100)
cluster_labels = clust.fit_predict(X_pca)
# plot cluster sizes
plt.hist(cluster_labels, bins=range(n_clusters+1))
plt.title('# Customers per Cluster')
plt.xlabel('Cluster')
plt.ylabel('# Customers')
plt.show()
df = pd.DataFrame(X_2_dim, columns=["x", "y"])
df['color'] = cluster_labels
sns.set(font_scale=1.2)
g = sns.lmplot("x", "y", data=df, hue='color',
fit_reg=False, size=8, palette="hls", legend=False)
g.set(yticks=[], xticks=[], xlabel="", ylabel="")
plt.title("Customer Clusters")
plt.show()
```
| github_jupyter |
```
from IPython.core.display import HTML, display
display(HTML("<style>.container { width:100% !important; }</style>"))
%load_ext autoreload
%autoreload 2
import sys
sys.path.append('..')
import logging
import pytorch_lightning as pl
import warnings
warnings.filterwarnings('ignore')
logging.getLogger("pytorch_lightning").setLevel(logging.ERROR)
```
## Data load
```
! mkdir ../../data
! curl -OL https://storage.googleapis.com/di-datasets/age-prediction-nti-sbebank-2019.zip
! unzip -j -o age-prediction-nti-sbebank-2019.zip 'data/*.csv' -d ../../data
! mv age-prediction-nti-sbebank-2019.zip ../../data/
```
## Data Preproccessing
```
import os
import pandas as pd
data_path = '../../data/'
source_data = pd.read_csv(os.path.join(data_path, 'transactions_train.csv'))
source_data.head(2)
from dltranz.data_preprocessing import PandasDataPreprocessor
preprocessor = PandasDataPreprocessor(
col_id='client_id',
cols_event_time='trans_date',
time_transformation='float',
cols_category=["trans_date", "small_group"],
cols_log_norm=["amount_rur"],
print_dataset_info=False,
)
# Split data into train and finetuning parts:
metric_learn_data, finetune_data = train_test_split(source_data, test_size=0.5, random_state=42)
%%time
import pickle
preproc_fitted = preprocessor.fit(metric_learn_data)
# Save preprocessor:
# with open('preproc_fitted.pickle', 'wb') as handle:
# pickle.dump(preproc_fitted, handle, protocol=pickle.HIGHEST_PROTOCOL)
dataset = preproc_fitted.transform(metric_learn_data)
from sklearn.model_selection import train_test_split
train, test = train_test_split(dataset, test_size=0.2, random_state=42)
print(len(train), len(test))
```
## Embedding training
Model training in our framework organised via pytorch-lightning (pl) framework.
The key parts of neural networks training in pl are:
* model (pl.LightningModule)
* data_module (pl.LightningDataModule)
* pl.trainer (pl.trainer)
For futher details check https://www.pytorchlightning.ai/
### model
```
from dltranz.seq_encoder import SequenceEncoder
from dltranz.models import Head
from dltranz.lightning_modules.emb_module import EmbModule
seq_encoder = SequenceEncoder(
category_features=preprocessor.get_category_sizes(),
numeric_features=["amount_rur"],
trx_embedding_noize=0.003
)
head = Head(input_size=seq_encoder.embedding_size, use_norm_encoder=True)
model = EmbModule(seq_encoder=seq_encoder, head=head)
```
### Data module
```
from dltranz.data_load.data_module.emb_data_module import EmbeddingTrainDataModule
dm = EmbeddingTrainDataModule(
dataset=train,
pl_module=model,
min_seq_len=25,
seq_split_strategy='SampleSlices',
category_names = model.seq_encoder.category_names,
category_max_size = model.seq_encoder.category_max_size,
split_count=5,
split_cnt_min=25,
split_cnt_max=200,
train_num_workers=16,
train_batch_size=256,
valid_num_workers=16,
valid_batch_size=256
)
```
### Trainer
```
import torch
import pytorch_lightning as pl
import logging
# logging.getLogger("lightning").addHandler(logging.NullHandler())
# logging.getLogger("lightning").propagate = False
trainer = pl.Trainer(
# progress_bar_refresh_rate=0,
max_epochs=10,
gpus=1 if torch.cuda.is_available() else 0
)
```
### Training
```
%%time
trainer.fit(model, dm)
```
## FineTuning
```
from pyhocon import ConfigFactory
from dltranz.seq_to_target import SequenceToTarget
class SeqToTargetDemo(SequenceToTarget):
def __init__(self,
seq_encoder = None,
encoder_lr: float = 0.0001,
in_features: int = 256,
out_features: int = 1,
head_lr: float = 0.005,
weight_decay: float = 0.0,
lr_step_size: int = 1,
lr_step_gamma: float = 0.60):
params = {
'score_metric': ['auroc', 'accuracy'],
'encoder_type': 'pretrained',
'pretrained': {
'pl_module_class': 'dltranz.lightning_modules.coles_module.CoLESModule',
'lr': encoder_lr
},
'head_layers': [
['BatchNorm1d', {'num_features': in_features}],
['Linear', {"in_features": in_features, "out_features": out_features}],
['Sigmoid', {}],
['Squeeze', {}]
],
'train': {
'random_neg': 'false',
'loss': 'bce',
'lr': head_lr,
'weight_decay': weight_decay,
},
'lr_scheduler': {
'step_size': lr_step_size,
'step_gamma': lr_step_gamma
}
}
super().__init__(ConfigFactory.from_dict(params), seq_encoder)
pretrained_encoder = model.seq_encoder
downstream_model = SeqToTargetDemo(pretrained_encoder,
encoder_lr=0.0001,
in_features=model.seq_encoder.embedding_size,
out_features=1,
head_lr=0.05,
weight_decay=0.0,
lr_step_size=1,
lr_step_gamma=0.60)
finetune_dataset = preproc_fitted.transform(finetune_data)
finetune_dm = EmbeddingTrainDataModule(
dataset=finetune_dataset,
pl_module=downstream_model,
min_seq_len=25,
seq_split_strategy='SampleSlices',
category_names = model.seq_encoder.category_names,
category_max_size = model.seq_encoder.category_max_size,
split_count=5,
split_cnt_min=25,
split_cnt_max=200,
train_num_workers=16,
train_batch_size=256,
valid_num_workers=16,
valid_batch_size=256
)
# trainer.fit(downstream_model, dm)
```
| github_jupyter |
# Importing libaries
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression, BayesianRidge
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from sklearn import linear_model
```
# Importing first databases
Radars.csv contains all cars, trucks, motorcycles and buses that comes thru São Paulo's radar system
```
df_base = pd.read_csv(r"D:\\Users\\guilh\\Documents\\GitHub\\Dados_CET\\Marco_2018_nAg\\2_nAg.csv", index_col= "Data")
df_base.head()
```
### Reading the columns
* **Radar** is the number of identification of a street section
* **Lane** goes from 1 to 6 in most radars, low lane number are closer to the center of the freeway, high lane numbers are "local" lanes, to the right
* **Register** represents each vehicle
* **Types** are: motorcycle = 0, car = 1, bus = 2 ou truck = 3
* **Classes** are: *light* (motorcycle and car) = 0 ou *heavy* (bus and truck) = 1
* **Speeds** are in kilometer per hour
* **Radar_Lane** comes to identify each lane on a single radar (will be usefull to merge dataframes)
```
# Preprocessing
df = df_base[["Numero Agrupado", "Faixa", "Registro", "Especie", "Classe", "Velocidade"]]
# turns speed from dm/s to km/h
df["Velocidade"] = df["Velocidade"] * 0.36
df.index.names = ["Date"]
df["Radar_Lane"] = df["Numero Agrupado"].astype(str) + df["Faixa"].astype(str)
# renaming columns to english
df.columns = ["Radar", "Lane", "Register", "Type", "Class", "Speed [km/h]", "Radar_Lane"]
df.head()
```
### Lane types database
Helps to tell the **use of each lane** .
"Tipo" contains the information of lanes where all types of vehicycles can use ( *mix_use* ) and other that are for buses only ( *exclusive_bus* )
```
lane_types = pd.read_excel(r"D:\Users\guilh\Documents\[POLI]_6_Semestre\IC\2021\codigos olimpio\\Faixa Tipo.xlsx", usecols = ["Num_agrupado","faixa", "Num_fx","tipo"],engine='openpyxl')
lane_types.head()
```
### Merge dataframes
To identify the type of the lane, if it is exclusive for buses, or multipurpose
```
df_merged = lane_types[["Num_fx", "tipo"]].merge(df, left_on = "Num_fx", right_on = "Radar_Lane", how="right")
df_merged["Lane_use"] = df_merged["tipo"].map({"mista":"mix_use", "onibus": "exclusive_bus"})
df_merged = df_merged[["Radar", "Lane", "Register", "Type", "Class", "Speed [km/h]", "Lane_use"]]
df_merged.head()
```
### Looking for NaNs
As shown below, NaNs are less than 1% (actually, less than 0,2%)
With this information, there will be low loss in dropping NaNs
```
print(df_merged.isna().mean() *100)
df_merged.dropna(inplace=True)
```
### Selection of Lanes
Using only the data from mix_use lanes, select for each lane to create comparison
The max numper of lanes is 6, but only few roads have all 6, so it can be excluded from the analysis
```
lanes = df_merged.loc[df_merged["Lane_use"] == "mix_use"]
lane_1 = lanes.loc[lanes["Lane"] == 1]
lane_2 = lanes.loc[lanes["Lane"] == 2]
lane_3 = lanes.loc[lanes["Lane"] == 3]
lane_4 = lanes.loc[lanes["Lane"] == 4]
lane_5 = lanes.loc[lanes["Lane"] == 5]
lane_6 = lanes.loc[lanes["Lane"] == 6]
print(lane_1.shape, lane_2.shape, lane_3.shape, lane_4.shape, lane_5.shape, lane_6.shape)
```
### Plotting the means
```
means = []
for lane in [lane_1,lane_2,lane_3,lane_4,lane_5]:
means.append(lane["Speed [km/h]"].mean())
means = [ round(elem, 2) for elem in means ]
fig, ax = plt.subplots()
rects = ax.bar([1,2,3,4,5],means, width= 0.5)
ax.set_ylabel("Speed [km/h]")
ax.set_xlabel("Lanes")
ax.set_title('Speeds per lane')
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects)
plt.show()
```
# How can we predicti a new car?
```
df_regression = df_base[["Numero Agrupado", "Faixa", "Registro", "Especie", "Classe", "Velocidade", "Comprimento"]]
df_regression.loc[:,"Comprimento"] = df_regression.loc[:,"Comprimento"] /10
df_regression.loc[:,"Velocidade"] = df_regression.loc[:,"Velocidade"] * 0.36
```
### Reading the columns refazerrrrrrrrrrrrrrrr
* **Radar** is the number of identification of a street section
* **Lane** goes from 1 to 6 in most radars, low lane number are closer to the center of the freeway, high lane numbers are "local" lanes, to the right
* **Register** represents each vehicle
* **Types** are: motorcycle = 0, car = 1, bus = 2 ou truck = 3
* **Classes** are: *light* (motorcycle and car) = 0 ou *heavy* (bus and truck) = 1
* **Speeds** are in kilometer per hour
* **Radar_Lane** comes to identify each lane on a single radar (will be usefull to merge dataframes)
```
df_regression.columns = ["Radar", "Lane", "Register", "Type", "Class", "Speed [km/h]", "Length"]
Validation = df_regression.loc[df_regression["Speed [km/h]"].isna()]
X = df_regression[["Lane", "Type", "Class", "Length"]].dropna()
X = pd.concat([pd.get_dummies(X[["Lane", "Type", "Class"]].astype("object")),X["Length"]], axis=1)
y = df_regression["Speed [km/h]"].dropna()
X.head()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
lr = LinearRegression(normalize=True)
lr.fit(X_train, y_train)
pred = lr.predict(X_test)
print(lr.score(X_train, y_train),lr.score(X_test, y_test))
corrMatrix = df_regression[["Lane", "Type", "Speed [km/h]","Length"]].corr()
display (corrMatrix)
sns.heatmap(corrMatrix, annot=True)
plt.show()
```
| github_jupyter |
```
import matplotlib as mpl
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
import nltk
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from sklearn.metrics import accuracy_score
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
# configuring matplotlib
plt.axes.titlesize : 24
plt.axes.labelsize : 20
plt.figsize = (15, 10)
# plt.cmap.
RANDOM_STATE = 42
np.random.seed(RANDOM_STATE)
```
## For augmenting the dataset
### Random Deletion
```
# random deletion use list.pop()b
import random
p = [1, 23,4 ,5, 34, 35, 23, 54, 645, 53]
random.randrange(len(p))
def delete_random(text):
text = text.split(" ")
random_index = random.randrange(len(text))
text.pop(random_index)
text = " ".join(text)
return text
delete_random('I feel guilty when when I realize that I consider material things more important than caring for my relatives. I feel very self-centered.')
```
### Random swap
```
# Random swap
def swap_random(text):
text = text.split(" ")
idx = range(len(text))
i1, i2 = random.sample(idx, 2)
text[i1], text[i2] = text[i2], text[i1]
text = " ".join(text)
return text
swap_random("I feel guilty when when I realize that I consider material things more important than caring for my relatives. I feel very self-centered.")
```
### Lemmatization
```
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.stem import PorterStemmer
porter = PorterStemmer()
def lemmatize(text):
sentences = sent_tokenize(text)
stem_sentence=[]
for sent in sentences:
token_words=word_tokenize(sent)
for word in token_words:
stem_sentence.append(porter.stem(word))
stem_sentence.append(" ")
return "".join(stem_sentence)
lemmatize("I feel guilty when when I realize that I consider material things more important than caring for my relatives. I feel very self-centered.")
raw_data = pd.read_csv('../data/raw/ISEAR.csv', header=None)
raw_data.head(15)
raw_data.columns = ['index', 'sentiment', 'text']
raw_data.set_index('index')
raw_data.head()
raw_data['text'][6]
```
### Remove newline character
```
raw_data['text'] = raw_data['text'].apply(lambda x: x.replace('\n', ''))
raw_data['text'][6]
```
## Convert text to lowercase
```
raw_data['text'] = raw_data['text'].apply( lambda x: x.lower())
raw_data.head()
```
### Dividing into train and test set
```
# Diving data into train, validation and test set
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = raw_data['text'], raw_data['sentiment']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=RANDOM_STATE, stratify=y)
# X_train, X_test = list(X_train), list(y_train)
X_train.head()
# Lemmatize X_train
X_train = X_train.apply(lemmatize)
# Apply swap random and delet random to X
X_train_original = X_train
y_train_original = y_train
X_train_swapped = X_train.apply(swap_random)
y_train_swapped = y_train
X_train_deleted = X_train.apply(delete_random)
y_train_deleted = y_train
y_train_original.shape, X_train_swapped.shape, X_train_deleted.shape
X_train_combined = X_train_original.append(X_train_swapped)
X_train_combined = X_train_combined.append(X_train_deleted)
y_train_combined = y_train_original.append(y_train_swapped)
y_train_combined = y_train_combined.append(y_train_deleted)
X_train_combined.shape, y_train_combined.shape
```
### Vectorizing the training and testing features separately
```
vectorizer = CountVectorizer(
analyzer = 'word',
stop_words = 'english', # removes common english words
ngram_range = (2, 2), # extracting bigrams
lowercase = True,
)
tfidf_transformer = TfidfTransformer()
features_train = vectorizer.fit_transform(
X_train_combined
)
features_train = tfidf_transformer.fit_transform(features_train)
features_train = features_train.toarray() # for easy usage
# for testing features
features_test = vectorizer.transform(
X_test
)
features_test = tfidf_transformer.transform(features_test)
features_test = features_test.toarray() # for easy usage
```
## Encoding the training and testing labels separately using the same label encoder
```
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
y_train = le.fit_transform(y_train_combined)
# encodeing the labels of test set
y_test = le.transform(y_test)
y_test, y_train
```
## making the classifier
```
from sklearn.linear_model import SGDClassifier
classifier = SGDClassifier(random_state=RANDOM_STATE)
y_pred = classifier.fit(features_train, y_train).predict(features_test)
accuracy = accuracy_score(y_test, y_pred)
accuracy
```
### MNB
```
from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB()
y_pred = classifier.fit(features_train, y_train).predict(features_test)
accuracy = accuracy_score(y_test, y_pred)
accuracy
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*7 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
raw_data['sentiment'].value_counts().plot(kind='bar', stacked=True, color=my_colors)
plt.savefig('../images/sentiment_distribution.png')
```
From above graph it is clear that all classes of sentiment have almost equal number of instances
```
def make_wordcloud(texts, stopwords=STOPWORDS):
texts = texts.lower()
sw = set(stopwords)
wordcloud = WordCloud(stopwords=stopwords, background_color="white").generate(texts)
return wordcloud
# def plot_wordclouds(dataframe, subplot_rows, subplot_columns):
rows = 4
columns = 3
fig = plt.figure()
p = 0
for col in raw_data['sentiment'].unique():
temp_df = raw_data[raw_data['sentiment']==col]
temp_df_texts = " ".join(text for text in temp_df['text'])
wordcloud = make_wordcloud(temp_df_texts)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.title(col)
image_name = '../images/'+ col+ '_wordcloud.png'
plt.savefig(image_name)
plt.show()
```
From above plots it is common that words like friend, mother, felt is common in all the texts. So we will need to remove them.
## Creating a new column that will hold the text as a list of words
```
frequent_words = []
def get_most_common_words(dataframe):
for col in dataframe['sentiment'].unique():
temp_df = dataframe[raw_data['sentiment']==col]
temp_df_texts = " ".join(text for text in temp_df['text'])
temp_df_texts = temp_df_texts.lower()
wordcloud = make_wordcloud(temp_df_texts)
frequent_words.append(list(wordcloud.words_.keys())[:50])
return frequent_words
most_frequent_words = get_most_common_words(raw_data)
print(len(most_frequent_words))
p =set(most_frequent_words[0])
for i in range(1, len(most_frequent_words)):
print(i)
p.intersection_update(set(most_frequent_words[i]))
print(p)
```
The words present above are the most frequent words so they can also be removed from the text.
```
p = " ".join(list(p))
most_frequent_wordcloud = make_wordcloud(p)
plt.imshow(most_frequent_wordcloud, interpolation='bilinear')
plt.axis("off")
plt.title('Most frequent words')
image_name = '../images/'+ 'most_frequent_words'+ '_wordcloud.png'
plt.savefig(image_name)
plt.show()
raw_data['text_length'] = raw_data['text'].apply(lambda x: len(x.split(' ')))
raw_data.head()
raw_data['text_length'].plot.hist()
plt.title('Distribution of text length')
plt.savefig('../images/distribution_of_text_length.png')
stopwords = list(STOPWORDS) + list(p)
```
## Converting all the text to lowercase
```
raw_data['text'] = raw_data['text'].apply( lambda x: x.lower())
raw_data.head()
vectorizer = CountVectorizer(
analyzer = 'word',
stop_words = 'english', # removes common english words
ngram_range = (2, 2), # extracting bigrams
lowercase = True,
)
features = vectorizer.fit_transform(
raw_data['text']
)
tfidf_transformer = TfidfTransformer()
features = tfidf_transformer.fit_transform(features)
```
## Saving countvectorizer
```
import pickle
# Save the label encoder as pickel object
output = open('../models/encoder_and_vectorizer/tf_idf_transformer.pkl', 'wb')
pickle.dump(tfidf_transformer, output)
output.close()
features_nd = features.toarray() # for easy usage
# print(features_nd.shape)
# raw_data['text_vectorized'] = list(features_nd)
# print(raw_data['text_vectorized'].shape)
# raw_data.head()
output = open('../models/encoder_and_vectorizer/vectorizer.pkl', 'wb')
pickle.dump(vectorizer, output)
output.close()
```
The vectorizer will also need to be saved. Because we will need to use the same vectorizer for making new predictions
```
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
raw_data['sentiment_encoded'] = le.fit_transform(raw_data['sentiment'])
# raw_data = raw_data[['sentiment_encoded','text_vectorized']]
```
Save the label encoder as a pickle or in some form. Make a function that takes column names as input, converts the column, saves the label encoder and then returns the new column values.
## Saving label encoder to a file
```
# Save the label encoder as pickel object
output = open('../models/encoder_and_vectorizer/label_encoder.pkl', 'wb')
pickle.dump(le, output)
output.close()
# Saving the processed data
# raw_data.to_csv('../data/processed/sentiment_features.csv')
```
## Making the actual model
```
# Diving data into train, validation and test set
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = features_nd, raw_data['sentiment_encoded']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=RANDOM_STATE, stratify=y)
# X_train, X_test = list(X_train), list(y_train)
```
### knn model
```
from sklearn import neighbors
knn=neighbors.KNeighborsClassifier()
# we create an instance of Neighbours Classifier and fit the data.
knn.fit(X_train, y_train)
predicted_results = knn.predict(X_test)
accuracy = accuracy_score(y_test, predicted_results)
accuracy
```
### naive bayes'
```
gnb = GaussianNB()
y_pred = gnb.fit(X_train, y_train).predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
accuracy
```
### Random Forest
```
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators=100, random_state=RANDOM_STATE)
y_pred = classifier.fit(X_train, y_train).predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
accuracy
```
### SGD
```
from sklearn.linear_model import SGDClassifier
classifier = SGDClassifier(random_state=RANDOM_STATE)
y_pred = classifier.fit(X_train, y_train).predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
accuracy
```
## Random Search with SGD
```
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import uniform
clf = SGDClassifier()
distributions = dict(
loss=['hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron'],
learning_rate=['optimal', 'invscaling', 'adaptive'],
eta0=uniform(loc=1e-7, scale=1e-2)
)
random_search_cv = RandomizedSearchCV(
estimator=clf,
param_distributions=distributions,
cv=5,
n_iter=50
)
random_search_cv.fit(X_train, y_train)
! ls
```
| github_jupyter |
Copyright 2020 Verily Life Sciences LLC
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://developers.google.com/open-source/licenses/bsd
# Trial Specification Demo
The first step to use the Baseline Site Selection Tool is to specify your trial.
All data in the Baseline Site Selection Tool is stored in [xarray.DataArray](http://xarray.pydata.org/en/stable/generated/xarray.DataArray.html) datasets. This is a [convenient datastructure](http://xarray.pydata.org/en/stable/why-xarray.html) for storing multidimensional arrays with different labels, coordinates or attributes. You don't need to have any expertise with xr.Datasets to use the Baseline Site Selection Tool. The goal of this notebook is to walk you through the construction of the dataset that contains the specification of your trial.
This notebook has several sections:
1. **Define the Trial**. In this section you will load all aspects of your trial, including the trial sites, the expected recruitment demographics for each trial site (e.g. from a census) as well as the rules for how the trial will be carried out.
2. **Load Incidence Forecasts**. In this section you will load forecasts for covid incidence at the locations of your trial. We highly recommend using forecasts that are as local as possible for the sites of the trial. There is significant variation in covid incidence among counties in the same state, and taking the state (province) average can be highly misleading. Here we include code to preload forecasts for county level forecasts from the US Center for Disease Control. The trial planner should include whatever forecasts they find most compelling.
3. **Simulate the Trial** Given the incidence forecasts and the trial rules, the third section will simulate the trial.
4. **Optimize the Trial** Given the parameters of the trial within our control, the next section asks whether we can set those parameters to make the trial meet our objective criteria, for example most likely to succeed or to succeed as quickly as possible. We have written a set of optimization routines for optimizing different types of trials.
We write out different trial plans, which you can then examine interactively in the second notebook in the Baseline Site Selection Tool. That notebook lets you visualize how the trial is proceeding at a per site level and experiment with what will happen when you turn up or down different sites.
If you have questions about how to implement these steps for your clinical trial, or there are variations in the trial specification that are not captured with this framework, please contact site-selection-tool@projectbaseline.com for additional help.
## Imports
```
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('ticks')
import functools
import importlib.resources
import numpy as np
import os
import pandas as pd
pd.plotting.register_matplotlib_converters()
import xarray as xr
from IPython.display import display
# bsst imports
from bsst import demo_data
from bsst import io as bsst_io
from bsst import util
from bsst import optimization
from bsst import sim
from bsst import sim_scenarios
from bsst import public_data
```
## Helper methods for visualization
```
def plot_participants(participants):
time = participants.time.values
util.sum_all_but_dims(['time'], participants).cumsum('time').plot()
plt.title('Participants recruited (both control and treatment arm)')
plt.xlim(time[0], time[-1])
plt.ylim(bottom=0)
plt.show()
def plot_events(events):
time = events.time.values
events.cumsum('time').plot.line(x='time', color='k', alpha=.02, add_legend=False)
for analysis, num_events in c.needed_control_arm_events.to_series().items():
plt.axhline(num_events, linestyle='--')
plt.text(time[0], num_events, analysis, ha='left', va='bottom')
plt.ylim(0, 120)
plt.xlim(time[0], time[-1])
plt.title(f'Control arm events\n{events.scenario.size} simulated scenarios')
plt.show()
def plot_success(c, events):
time = c.time.values
success_day = xr.DataArray(util.success_day(c.needed_control_arm_events, events),
coords=(events.scenario, c.analysis))
fig, axes = plt.subplots(c.analysis.size, 1, sharex=True)
step = max(1, int(np.timedelta64(3, 'D') / (time[1] - time[0])))
bins = mpl.units.registry[np.datetime64].convert(time[::step], None, None)
for analysis, ax in zip(c.analysis.values, axes):
success_days = success_day.sel(analysis=analysis).values
np.where(np.isnat(success_days), np.datetime64('2050-06-01'), success_days)
ax.hist(success_days, bins=bins, density=True)
ax.yaxis.set_visible(False)
# subtract time[0] to make into timedelta64s so that we can take a mean/median
median = np.median(success_days - time[0]) + time[0]
median = pd.to_datetime(median).date()
ax.axvline(median, color='r')
ax.text(time[0], 0, f'{analysis}\n{median} median', ha='left', va='bottom')
plt.xlabel('Date when sufficient statistical power is achieved')
plt.xlim(time[0], time[-1])
plt.xticks(rotation=35)
plt.show()
```
# 1. Define the trial
## Choose the sites
A trial specification consists a list of sites, together with various properties of the sites.
For this demo, we read demonstration data embedded in the Baseline Site Selection Tool Python package. Specifically, this information is loaded from the file `demo_data/site_list1.csv`. Each row of this file contains the name of a site, as well as the detailed information about the trial. In this illustrative example, we pick sites in real US counties. Each column contains the following information:
* `opencovid_key` . This is a key that specifies location within [COVID-19 Open Data](https://github.com/GoogleCloudPlatform/covid-19-open-data). It is required by this schema because it is the way we join the incidence forecasts to the site locations.
* `capacity`, the number of participants the site can recruit each week, including both control arm and treatment arms. For simplicity, we assume this is constant over time, but variable recruitment rates are also supported. (See the construction of the `site_capacity` array below).
* `start_date`. This is the first date on which the site can recruit participants.
* The proportion of the population in various demographic categories. For this example, we consider categories for age (`over_60`), ethnicity (`black`, `hisp_lat`), and comorbidities (`smokers`, `diabetes`, `obese`). **Here we just fill in demographic information with random numbers.** We assume different categories are independent, but the data structure supports complex beliefs about how different categories intersect, how much each site can enrich for different categories, and different infection risks for different categories. These are represented in the factors `population_fraction`, `participant_fraction`, `incidence_scaler`, and `incidence_to_event_factor` below. In a practical situation, we recommend that the trial planner uses accurate estimates of the populations for the different sites they are drawing from.
```
with importlib.resources.path(demo_data, 'site_list1.csv') as p:
demo_data_file_path = os.fspath(p)
site_df = pd.read_csv(demo_data_file_path, index_col=0)
site_df.index.name = 'location'
site_df['start_date'] = pd.to_datetime(site_df['start_date'])
display(site_df)
# Add in information we have about each county.
site_df = pd.concat([site_df, public_data.us_county_data().loc[site_df.opencovid_key].set_index(site_df.index)], axis=1)
```
## Choose trial parameters
The trial requires a number of parameters that have to be specified to be able to simulate what will happen in the trial: These include:
* `trial_size_cap`: the maximum number of participants in the trial (includes both control and treatment arms)
* `start_day` and `end_day`: the boundaries of the time period we will simulate.
* `proportion_control_arm`: what proportion of participants are in the control arm. It's assumed that the control arm is as uniformly distributed across locations and time (e.g. at each location on each day, half of the recruited participants are assigned to the control arm).
* `needed_control_arm_events`: the number of events required in the *control* arm of the trial at various intermediate analysis points. For this example we assume intermediate analyses which would demonstrate a vaccine efficacy of about 55%, 65%, 75%, 85%, or 95%.
* `observation_delay`: how long after a participant is recruited before they contribute an event. This is measured in the same time units as your incidence forecasts. Here we assume 28 days.
* `site_capacity` and `site_activation`: the number of participants each site could recruit *if* it were activated, and whether each site is activated at any given time. Here we assume each site as a constant weekly capacity, but time dependence can be included (e.g. to model ramp up of recruitment).
* `population_fraction`, `participant_fraction`, and `incidence_scaler`: the proportion of the general population and the proportion of participants who fall into different demographic categories at each location, and the infection risk factor for each category. These three are required to translate an overall incidence forecast for the population into the incidence forecast for your control arm.
* `incidence_to_event_factor`: what proportion of infections lead to a clinical event. We assume a constant 0.6, but you can specify different values for different demographic categories.
These factors are specified in the datastructure below.
```
start_day = np.datetime64('2021-05-15')
end_day = np.datetime64('2021-10-01')
time_resolution = np.timedelta64(1, 'D')
time = np.arange(start_day, end_day + time_resolution, time_resolution)
c = xr.Dataset(coords=dict(time=time))
c['proportion_control_arm'] = 0.5
# Assume some intermediate analyses.
frac_control = float(c.proportion_control_arm)
efficacy = np.array([.55, .65, .75, .85, .95])
ctrl_events = util.needed_control_arm_events(efficacy, frac_control)
vaccine_events = (1 - efficacy) * ctrl_events * (1 - frac_control) / frac_control
ctrl_events, vaccine_events = np.round(ctrl_events), np.round(vaccine_events)
efficacy = 1 - (vaccine_events / ctrl_events)
total_events = ctrl_events + vaccine_events
analysis_names = [
f'{int(t)} total events @{int(100 * e)}% VE' for t, e in zip(total_events, efficacy)
]
c['needed_control_arm_events'] = xr.DataArray(
ctrl_events, dims=('analysis',)).assign_coords(analysis=analysis_names)
c['recruitment_type'] = 'default'
c['observation_delay'] = int(np.timedelta64(28, 'D') / time_resolution) # 28 days
c['trial_size_cap'] = 30000
# convert weekly capacity to capacity per time step
site_capacity = site_df.capacity.to_xarray() * time_resolution / np.timedelta64(7, 'D')
site_capacity = site_capacity.broadcast_like(c.time).astype('float')
# Can't recruit before the activation date
activation_date = site_df.start_date.to_xarray()
for l in activation_date.location.values:
date = activation_date.loc[l]
site_capacity.loc[site_capacity.time < date, l] = 0.0
c['site_capacity'] = site_capacity.transpose('location', 'time')
c['site_activation'] = xr.ones_like(c.site_capacity)
# For the sake of simplicity, this code assumes black and hisp_lat are
# non-overlapping, and that obese/smokers/diabetes are non-overlapping.
frac_and_scalar = util.fraction_and_incidence_scaler
fraction_scalers = [
frac_and_scalar(site_df, 'age', ['over_60'], [1], 'under_60'),
frac_and_scalar(site_df, 'ethnicity', ['black', 'hisp_lat'], [1, 1],
'other'),
frac_and_scalar(site_df, 'comorbidity', ['smokers', 'diabetes', 'obese'],
[1, 1, 1], 'none')
]
fractions, incidence_scalers = zip(*fraction_scalers)
# We assume that different categories are independent (e.g. the proportion of
# smokers over 60 is the same as the proportion of smokers under 60)
c['population_fraction'] = functools.reduce(lambda x, y: x * y, fractions)
# We assume the participants are drawn uniformly from the population.
c['participant_fraction'] = c['population_fraction']
# Assume some boosted incidence risk for subpopulations. We pick random numbers
# here, but in actual use you'd put your best estimate for the incidence risk
# of each demographic category.
# Since we assume participants are uniformly drawn from the county population,
# this actually doesn't end up affecting the estimated number of clinical events.
c['incidence_scaler'] = functools.reduce(lambda x, y: x * y,
incidence_scalers)
c.incidence_scaler.loc[dict(age='over_60')] = 1 + 2 * np.random.random()
c.incidence_scaler.loc[dict(comorbidity=['smokers', 'diabetes', 'obese'])] = 1 + 2 * np.random.random()
c.incidence_scaler.loc[dict(ethnicity=['black', 'hisp_lat'])] = 1 + 2 * np.random.random()
# We assume a constant incidence_to_event_factor.
c['incidence_to_event_factor'] = 0.6 * xr.ones_like(c.incidence_scaler)
util.add_empty_history(c)
```
# 2. Load incidence forecasts
We load historical incidence data from [COVID-19 Open Data](https://github.com/GoogleCloudPlatform/covid-19-open-data) and forecasts from [COVID-19 Forecast Hub](https://github.com/reichlab/covid19-forecast-hub).
We note that there are a set of caveats when using the CDC models that should be considered when using these for trial planning:
* Forecasts are only available for US counties. Hence, these forecasts will only work for US-only trials. Trials with sites outside the US will need to supplement these forecasts.
* Forecasts only go out for four weeks. Trials take much longer than four weeks to complete, when measured from site selection to logging the required number of cases in the control arm. For simplicity, here we extrapolate incidence as *constant* after the last point of the forecast. Here we extrapolate out to October 1, 2021.
* The forecasts from the CDC are provided with quantile estimates. Our method depends on getting *representative forecasts* from the model: we need a set of sample forecasts for each site which represent the set of scenarios that can occur. Ideally these scenarios will be equally probable so that we can compute probabilities by averaging over samples. To get samples from quantiles, we interpolate/extrapolate to get 100 evenly spaced quantile estimates, which we treat as representative samples.
You can of course replace these forecasts with whatever represents your beliefs and uncertainty about what will happen.
```
# Extrapolate out a bit extra to ensure we're within bounds when we interpolate later.
full_pred = public_data.fetch_cdc_forecasts([('COVIDhub-ensemble', '2021-05-10'),
('COVIDhub-baseline', '2021-05-10')],
end_date=c.time.values[-1] + np.timedelta64(15, 'D'),
num_samples=50)
full_gt = public_data.fetch_opencovid_incidence()
# Suppose we only have ground truth through 2021-05-09.
full_gt = full_gt.sel(time=slice(None, np.datetime64('2021-05-09')))
# Include more historical incidence here for context. It will be trimmed off when
# we construct scenarios to simulate. The funny backwards range is to ensure that if
# we use weekly instead of daily resolution, we use the same day of the week as c.
time = np.arange(c.time.values[-1], np.datetime64('2021-04-01'), -time_resolution)[::-1]
incidence_model = public_data.assemble_forecast(full_gt, full_pred, site_df, time)
locs = np.random.choice(c.location.values, size=5, replace=False)
incidence_model.sel(location=locs).plot.line(x='time', color='k', alpha=.1, add_legend=False, col='location', row='model')
plt.ylim(0.0, 1e-3)
plt.suptitle('Forecast incidence at a sampling of sites', y=1.0)
pass
```
# 3. Simulate the trial
Now that we've specified how the trial works, we can compute how the trial will turn out given the incidence forecasts you've specified. We do this by first imagining what sampling what incidence will be at all locations simultaneously. For any given fully-specified scenario, we compute how many participants will be under observation at any given time in any given location (in any given combination of demographic buckets), then based on the specified local incidence we compute how many will become infected, and how many will produce clinical events.
Here we assume that the incidence trajectories of different locations are drawn at random from the available forecasts. Other scenario-generation methods in `sim_scenarios` support more complex approaches. For example, we may be highly uncertain about the incidence at each site, but believe that if incidence is high at a site, then it will also be high at geographically nearby sites. If this is the case then the simulation should not choose forecasts independently at each site but instead should take these correlations into account. The code scenario-generating methods in `sim_scenarios` allows us to do that.
```
# incidence_flattened: rolls together all the models you've included in your ensemble, treating them as independent samples.
incidence_flattened = sim_scenarios.get_incidence_flattened(incidence_model, c)
# incidence_scenarios: chooses scenarios given the incidence curves and your chosen method of scenario-generation.
incidence_scenarios = sim_scenarios.generate_scenarios_independently(incidence_flattened, num_scenarios=100)
# compute the number of participants recruited under your trial rule
participants = sim.recruitment(c)
# compute the number of control arm events under your trial rules and incidence_scenarios.
events = sim.control_arm_events(c, participants, incidence_scenarios)
plot_participants(participants)
# plot events and label different vaccine efficacies
plot_events(events)
# plot histograms of time to success
plot_success(c, events)
sim.add_stuff_to_ville(c, incidence_model, site_df, num_scenarios=100)
!mkdir -p demo_data
bsst_io.write_ville_to_netcdf(c, 'demo_data/site_list1_all_site_on.nc')
```
# 4. Optimize the trial
The simulations above supposed that all sites are activated as soon as possible (i.e. `site_activation` is identically 1). Now that we have shown the ability to simulate the outcome of the trial, we can turn it into a mathematical optimization problem.
**Given the parameters of the trial within our control, how can we set those parameters to make the trial most likely to succeed or to succeed as quickly as possible?**
We imagine the main levers of control are which sites to activate or which sites to prioritize activating, and this is what is implemented here.
However, the framework we have developed is very general and could be extended to just about anything you control which you can predict the impact of. For example,
* If you can estimate the impact of money spent boosting recruitment of high-risk participants, we could use those estimates to help figure out how to best allocate a fixed budget.
* If you had requirements for the number of people infected in different demographic groups, we could use those to help figure out how to best allocate doses between sites with different population characteristics.
The optimization algorithms are implemented in [JAX](https://github.com/google/jax), a python library that makes it possible to differentiate through native python and numpy functions. The flexibility of the language makes it possible to compose a variety of trial optimization scenarios and then to write algorithms that find optima. There are a number of technical details in how the optimization algorithms are written that will be discussed elsewhere.
### Example: Optimizing Static site activations
Suppose that the only variable we can control is which sites should be activated, and we have to make this decision at the beginning of the trial. This decision is then set in stone for the duration of the trial. To calculate this we proceed as follows:
The optimizer takes in the trial plan, encoded in the xarray `c` as well as the `incidence_scenarios`, and then calls the optimizer to find the sites that should be activated to minimize the time to success of the trial. The algorithm modifies `c` *in place*, so that after the algorithm runs, it returns the trial plan `c` but with the site activations chosen to be on or off in accordance with the optimizion.
```
%time optimization.optimize_static_activation(c, incidence_scenarios)
```
#### Plot the resulting sites
Now we can plot the activations for the resulting sites. Only a subset of the original sites are activated in the optimized plan. Comparing the distributions for the time to success for the optimized sites to those in the original trial plan (all sites activated), the optimized plan will save a bit of time if the vaccine efficacy is low. If the vaccine efficacy is high, then just getting as many participants as possible as quickly as possible is optimal.
```
all_sites = c.location.values
activated_sites = c.location.values[c.site_activation.mean('time') == 1]
# Simulate the results with this activation scheme.
print(f'\n\n{len(activated_sites)} of {len(all_sites)} activated')
participants = sim.recruitment(c)
events = sim.control_arm_events(c, participants, incidence_scenarios)
plot_participants(participants)
plot_events(events)
plot_success(c, events)
df = (participants.sum(['location', 'time', 'comorbidity']) / participants.sum()).to_pandas()
display(df.style.set_caption('Proportion of participants by age and ethnicity'))
sim.add_stuff_to_ville(c, incidence_model, site_df, num_scenarios=100)
!mkdir -p demo_data
bsst_io.write_ville_to_netcdf(c, 'demo_data/site_list1_optimized_static.nc')
```
### Example: Custom loss penalizing site activation and promoting diverse participants
Suppose we want to factor in considerations aside from how quickly the trial succeeds. In this example, we assume that activating sites is expensive, so we'd like to activate as few of them as possible, so long as it doesn't delay the success of the trial too much. Similarly, we assume that it's valuable to have a larger proportion of elderly, black, or hispanic participants, and we're willing to activate sites which can recruit from these demographic groups, even if doing so delays success a bit.
```
def loss_fn(c):
# sum over location, time, comorbidity
# remaining dimensions are [age, ethnicity]
participants = c.participants.sum(axis=0).sum(axis=0).sum(axis=-1)
total_participants = participants.sum()
return (
optimization.negative_mean_successiness(c) # demonstrate efficacy fast
+ 0.2 * c.site_activation.mean() # turning on sites is costly
- 0.5 * participants[1:, :].sum() / total_participants # we want people over 60
- 0.5 * participants[:, 1:].sum() / total_participants # we want blacks and hispanics
)
%time optimization.optimize_static_activation(c, incidence_scenarios, loss_fn)
```
#### Plot the resulting sites
This time only 53 of 146 sites are activated. The slower recruitment costs us 1-2 weeks until the trial succeeds (depending on vaccine efficacy). In exchange, we don't need to activate as many sites, and we end up with a greater proportion of participants who are elderly, black, or hispanic (dropping from 55.7% to 45.6% young white).
```
all_sites = c.location.values
activated_sites = c.location.values[c.site_activation.mean('time') == 1]
# Simulate the results with this activation scheme.
print(f'\n\n{len(activated_sites)} of {len(all_sites)} activated')
participants = sim.recruitment(c)
events = sim.control_arm_events(c, participants, incidence_scenarios)
plot_participants(participants)
plot_events(events)
plot_success(c, events)
df = (participants.sum(['location', 'time', 'comorbidity']) / participants.sum()).to_pandas()
display(df.style.set_caption('Proportion of participants by age and ethnicity'))
```
### Example: prioritizing sites
Suppose we can activate up to 20 sites each week for 10 weeks. How do we prioritize them?
```
# We put all sites in on group. We also support prioritizing sites within groupings.
# For example, if you can activate 2 sites per state per week, sites would be grouped
# according to the state they're in.
site_to_group = pd.Series(['all_sites'] * len(site_df), index=site_df.index)
decision_dates = c.time.values[:70:7]
allowed_activations = pd.DataFrame([[20] * len(decision_dates)], index=['all_sites'], columns=decision_dates)
parameterizer = optimization.PivotTableActivation(c, site_to_group, allowed_activations, can_deactivate=False)
optimization.optimize_params(c, incidence_scenarios, parameterizer)
c['site_activation'] = c.site_activation.round() # each site has to be on or off at each time
df = c.site_activation.to_pandas()
df.columns = [pd.to_datetime(x).date() for x in df.columns]
sns.heatmap(df, cbar=False)
plt.title('Which sites are activated when')
plt.show()
participants = sim.recruitment(c)
events = sim.control_arm_events(c, participants, incidence_scenarios)
plot_participants(participants)
plot_events(events)
plot_success(c, events)
sim.add_stuff_to_ville(c, incidence_model, site_df, num_scenarios=100)
!mkdir -p demo_data
bsst_io.write_ville_to_netcdf(c, 'demo_data/site_list1_prioritized.nc')
```
| github_jupyter |
<h1 class="maintitle">Raster Formats and Libraries</h1>
<blockquote class="objectives">
<h2>Overview</h2>
<div class="row">
<div class="col-md-3">
<strong>Teaching:</strong> 5 min
<br>
<strong>Exercises:</strong> 0 min
</div>
<div class="col-md-9">
<strong>Questions</strong>
<ul>
<li><p>What sorts of formats are available for representing raster datasets?</p>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-9">
<strong>Objectives</strong>
<ul>
<li><p>Understand the high-level data interchange formats for raster datasets.</p>
</li>
</ul>
</div>
</div>
</blockquote>
<h1 id="libraries-and-file-formats-for-raster-datasets">Libraries and file formats for raster datasets</h1>
<p><a href="http://gdal.org">GDAL</a> (Geospatial Data Abstraction Library) is the de facto standard library for
interaction and manipulation of geospatial raster data. The primary purpose of GDAL or a
GDAL-enabled library is to read, write and transform geospatial datasets in a
way that makes sense in the context of its spatial metadata. GDAL also includes
a set of <a href="http://www.gdal.org/gdal_utilities.html">command-line utilities</a> (e.g., gdalinfo, gdal_translate)
for convenient inspection and manipulation of raster data.</p>
<p>Other libraries also exist (we’ll introduce rasterio in the next section of this
tutorial, and even more exist in the fields of geoprocessing (which would
include hydrological routing and other routines needed for Earth Systems
Sciences) and digital signal processing (including image classification,
pattern recognition, and feature extraction).</p>
<p>GDAL’s support for different file formats depends on the format drivers that
have been implemented, and the libraries that are available at compile time.
To find the available formats for your current install of GDAL:</p>
<div class="shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gdalinfo --formats
</code></pre></div></div>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Supported Formats:
VRT -raster- (rw+v): Virtual Raster
GTiff -raster- (rw+vs): GeoTIFF
NITF -raster- (rw+vs): National Imagery Transmission Format
RPFTOC -raster- (rovs): Raster Product Format TOC format
...
# There are lots more, results depend on your build
</code></pre></div></div>
<p>Details about a specific format can be found with the <code class="highlighter-rouge">--format</code> parameter,
or by taking a look at the
<a href="http://www.gdal.org/formats_list.html">formats list on their website</a>.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gdalinfo --format GTiff
</code></pre></div></div>
<p>GDAL can operate on local files or even read files from the web like so:</p>
<div class="shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ SERVER='http://landsat-pds.s3.amazonaws.com/c1/L8/042/034/LC08_L1TP_042034_20170616_20170629_01_T1'
$ IMAGE='LC08_L1TP_042034_20170616_20170629_01_T1_B4.TIF'
$ gdalinfo /vsicurl/$SERVER/$IMAGE
</code></pre></div></div>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Driver: GTiff/GeoTIFF
Files: /vsicurl/http://landsat-pds.s3.amazonaws.com/c1/L8/042/034/LC08_L1TP_042034_20170616_20170629_01_T1/LC08_L1TP_042034_20170616_20170629_01_T1_B4.TIF
/vsicurl/http://landsat-pds.s3.amazonaws.com/c1/L8/042/034/LC08_L1TP_042034_20170616_20170629_01_T1/LC08_L1TP_042034_20170616_20170629_01_T1_B4.TIF.ovr
/vsicurl/http://landsat-pds.s3.amazonaws.com/c1/L8/042/034/LC08_L1TP_042034_20170616_20170629_01_T1/LC08_L1TP_042034_20170616_20170629_01_T1_MTL.txt
Size is 7821, 7951
Coordinate System is:
PROJCS["WGS 84 / UTM zone 11N",
GEOGCS["WGS 84",
DATUM["WGS_1984",
SPHEROID["WGS 84",6378137,298.257223563,
AUTHORITY["EPSG","7030"]],
AUTHORITY["EPSG","6326"]],
PRIMEM["Greenwich",0,
AUTHORITY["EPSG","8901"]],
UNIT["degree",0.0174532925199433,
AUTHORITY["EPSG","9122"]],
AUTHORITY["EPSG","4326"]],
PROJECTION["Transverse_Mercator"],
PARAMETER["latitude_of_origin",0],
PARAMETER["central_meridian",-117],
PARAMETER["scale_factor",0.9996],
PARAMETER["false_easting",500000],
PARAMETER["false_northing",0],
UNIT["metre",1,
AUTHORITY["EPSG","9001"]],
AXIS["Easting",EAST],
AXIS["Northing",NORTH],
AUTHORITY["EPSG","32611"]]
Origin = (204285.000000000000000,4268115.000000000000000)
Pixel Size = (30.000000000000000,-30.000000000000000)
Metadata:
AREA_OR_POINT=Point
METADATATYPE=ODL
Image Structure Metadata:
COMPRESSION=DEFLATE
INTERLEAVE=BAND
Corner Coordinates:
Upper Left ( 204285.000, 4268115.000) (120d23'29.18"W, 38d30'44.39"N)
Lower Left ( 204285.000, 4029585.000) (120d17'44.96"W, 36d21'57.41"N)
Upper Right ( 438915.000, 4268115.000) (117d42' 3.98"W, 38d33'33.76"N)
Lower Right ( 438915.000, 4029585.000) (117d40'52.67"W, 36d24'34.20"N)
Center ( 321600.000, 4148850.000) (119d 1' 2.61"W, 37d28' 9.59"N)
Band 1 Block=512x512 Type=UInt16, ColorInterp=Gray
Overviews: 2607x2651, 869x884, 290x295, 97x99
</code></pre></div></div>
<p>Often you want files in a specific format. GDAL is great for format conversions,
here is an example that saves a reference to a remote file to your local disk
in the <a href="https://www.gdal.org/gdal_vrttut.html">VRT format</a>.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gdal_translate -of VRT /vsicurl/$SERVER/$IMAGE LC08_L1TP_042034_20170616_20170629_01_T1_B4.vrt
</code></pre></div></div>
<p>Now you can forget about the strange ‘/vsicurl/’ syntax and just work directly
with the local file. The command below should give you the same print-out as
earlier.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gdalinfo LC08_L1TP_042034_20170616_20170629_01_T1_B4.vrt
</code></pre></div></div>
<p>Another common task is warping an image to a different coordinate system. The
example command below warps the image from UTM Coordinates to WGS84 lat/lon
coordinates:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gdalwarp -t_srs EPSG:4326 -of VRT /vsicurl/$SERVER/$IMAGE LC08_L1TP_042034_20170616_20170629_01_T1_B4-wgs84.vrt
</code></pre></div></div>
<p>Confirm by looking at the new coordinates:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gdalinfo LC08_L1TP_042034_20170616_20170629_01_T1_B4-wgs84.vrt
</code></pre></div></div>
<p>As you can see, there is a lot you can do with GDAL command line utilities!</p>
<h1 id="programming-model-numpy-arrays">Programming model: NumPy arrays</h1>
<p>Because rasters are images, they are best thought of as 2-dimensional arrays. If we
have multiple bands, we could think of an image as a 3-dimensional array.
Either way, we are working with arrays (matrices) of pixel values, which in the
python programming language are best represented by <a href="http://numpy.org">NumPy</a> arrays.</p>
<p>For this tutorial, we’ll perform basic operations with NumPy arrays extracted
from geospatial rasters. For more information about multidimensional array
analysis, take a look at Thursday’s tutorial on
<a href="https://geohackweek.github.io/nDarrays">N-Dimensional Arrays</a>.</p>
<blockquote class="keypoints">
<h2>Key Points</h2>
<ul>
<li><p>Geospatial libraries such as GDAL are very useful for reading, writing and transforming rasters</p>
</li>
<li><p>Once a raster’s pixel values have been extracted to a NumPy array, they can be processed with more specialized libraries and routines.</p>
</li>
</ul>
</blockquote>
<hr>
This notebook is inspired by the material in the website <a href="https://geohackweewebsite k.github.io/raster/04-workingwithrasters/"> GeoHackWeek </a>
| github_jupyter |
```
# Copyright 2021 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.
```
# AutoML natural language text classification model
## Installation
Install the latest version of AutoML SDK.
```
! pip3 install google-cloud-automl
```
Install the Google *cloud-storage* library as well.
```
! pip3 install google-cloud-storage
```
### Restart the Kernel
Once you've installed the AutoML SDK and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages.
```
import os
if not os.getenv("AUTORUN"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
```
## Before you begin
### GPU run-time
*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**
### Set up your GCP project
**The following steps are required, regardless of your notebook environment.**
1. [Select or create a GCP project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.
2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)
3. [Enable the AutoML APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)
4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in AutoML Notebooks.
5. Enter your project ID in the cell below. Then run the cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.
#### Project ID
**If you don't know your project ID**, try to get your project ID using `gcloud` command by executing the second cell below.
```
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
# Get your GCP project id from gcloud
shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID:", PROJECT_ID)
! gcloud config set project $PROJECT_ID
```
#### Region
You can also change the `REGION` variable, which is used for operations
throughout the rest of this notebook. Below are regions supported for AutoML. We recommend when possible, to choose the region closest to you.
- Americas: `us-central1`
- Europe: `europe-west4`
- Asia Pacific: `asia-east1`
You cannot use a Multi-Regional Storage bucket for training with AutoML. Not all regions provide support for all AutoML services. For the latest support per region, see [Region support for AutoML services]()
```
REGION = "us-central1" # @param {type: "string"}
```
#### Timestamp
If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial.
```
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
```
### Authenticate your GCP account
**If you are using AutoML Notebooks**, your environment is already
authenticated. Skip this step.
*Note: If you are on an AutoML notebook and run the cell, the cell knows to skip executing the authentication steps.*
```
import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your Google Cloud account. This provides access
# to your Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# If on Vertex, then don't execute this code
if not os.path.exists("/opt/deeplearning/metadata/env_version"):
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# If you are running this tutorial in a notebook locally, replace the string
# below with the path to your service account key and run this cell to
# authenticate your Google Cloud account.
else:
%env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json
# Log in to your account on Google Cloud
! gcloud auth login
```
### Create a Cloud Storage bucket
**The following steps are required, regardless of your notebook environment.**
This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.
Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.
```
BUCKET_NAME = "[your-bucket-name]" # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]":
BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP
```
**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.
```
! gsutil mb -l $REGION gs://$BUCKET_NAME
```
Finally, validate access to your Cloud Storage bucket by examining its contents:
```
! gsutil ls -al gs://$BUCKET_NAME
```
### Set up variables
Next, set up some variables used throughout the tutorial.
### Import libraries and define constants
#### Import AutoML SDK
Import the AutoM SDK into our Python environment.
```
import json
import time
from google.cloud import automl
from google.protobuf.json_format import MessageToJson
```
#### AutoML constants
Setup up the following constants for AutoML:
- `PARENT`: The AutoM location root path for dataset, model and endpoint resources.
```
# AutoM location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION
```
## Clients
The AutoML SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (AutoML).
You will use several clients in this tutorial, so set them all up upfront.
```
def automl_client():
return automl.AutoMlClient()
def prediction_client():
return automl.PredictionServiceClient()
def operations_client():
return automl.AutoMlClient()._transport.operations_client
clients = {}
clients["automl"] = automl_client()
clients["prediction"] = prediction_client()
clients["operations"] = operations_client()
for client in clients.items():
print(client)
IMPORT_FILE = "gs://cloud-ml-data/NL-classification/happiness.csv"
! gsutil cat $IMPORT_FILE | head -n 10
```
*Example output*:
```
I went on a successful date with someone I felt sympathy and connection with.,affection
I was happy when my son got 90% marks in his examination,affection
I went to the gym this morning and did yoga.,exercise
We had a serious talk with some friends of ours who have been flaky lately. They understood and we had a good evening hanging out.,bonding
I went with grandchildren to butterfly display at Crohn Conservatory,affection
I meditated last night.,leisure
"I made a new recipe for peasant bread, and it came out spectacular!",achievement
I got gift from my elder brother which was really surprising me,affection
YESTERDAY MY MOMS BIRTHDAY SO I ENJOYED,enjoy_the_moment
Watching cupcake wars with my three teen children,affection
```
## Create a dataset
### [projects.locations.datasets.create](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.datasets/create)
#### Request
```
dataset = {
"display_name": "happiness_" + TIMESTAMP,
"text_classification_dataset_metadata": {"classification_type": "MULTICLASS"},
}
print(
MessageToJson(
automl.CreateDatasetRequest(parent=PARENT, dataset=dataset).__dict__["_pb"]
)
)
```
*Example output*:
```
{
"parent": "projects/migration-ucaip-training/locations/us-central1",
"dataset": {
"displayName": "happiness_20210228224317",
"textClassificationDatasetMetadata": {
"classificationType": "MULTICLASS"
}
}
}
```
#### Call
```
request = clients["automl"].create_dataset(parent=PARENT, dataset=dataset)
```
#### Response
```
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
```
*Example output*:
```
{
"name": "projects/116273516712/locations/us-central1/datasets/TCN2705019056410329088"
}
```
```
# The full unique ID for the dataset
dataset_id = result.name
# The short numeric ID for the dataset
dataset_short_id = dataset_id.split("/")[-1]
print(dataset_id)
```
### [projects.locations.datasets.importData](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.datasets/importData)
#### Request
```
input_config = {"gcs_source": {"input_uris": [IMPORT_FILE]}}
print(
MessageToJson(
automl.ImportDataRequest(name=dataset_id, input_config=input_config).__dict__[
"_pb"
]
)
)
```
*Example output*:
```
{
"name": "projects/116273516712/locations/us-central1/datasets/TCN2705019056410329088",
"inputConfig": {
"gcsSource": {
"inputUris": [
"gs://cloud-ml-data/NL-classification/happiness.csv"
]
}
}
}
```
#### Call
```
request = clients["automl"].import_data(name=dataset_id, input_config=input_config)
```
#### Response
```
result = request.result()
print(MessageToJson(result))
```
*Example output*:
```
{}
```
## Train a model
### [projects.locations.models.create](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/create)
#### Request
```
model = automl.Model(
display_name="happiness_" + TIMESTAMP,
dataset_id=dataset_short_id,
text_classification_model_metadata=automl.TextClassificationModelMetadata(),
)
print(
MessageToJson(automl.CreateModelRequest(parent=PARENT, model=model).__dict__["_pb"])
)
```
*Example output*:
```
{
"parent": "projects/migration-ucaip-training/locations/us-central1",
"model": {
"displayName": "happiness_20210228224317",
"datasetId": "TCN2705019056410329088",
"textClassificationModelMetadata": {}
}
}
```
#### Call
```
request = clients["automl"].create_model(parent=PARENT, model=model)
```
#### Response
```
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
```
*Example output*:
```
{
"name": "projects/116273516712/locations/us-central1/models/TCN5333697920992542720"
}
```
```
# The full unique ID for the training pipeline
model_id = result.name
# The short numeric ID for the training pipeline
model_short_id = model_id.split("/")[-1]
print(model_short_id)
```
## Evaluate the model
### [projects.locations.models.modelEvaluations.list](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models.modelEvaluations/list)
#### Call
```
request = clients["automl"].list_model_evaluations(parent=model_id, filter="")
```
#### Response
```
evaluations_list = [
json.loads(MessageToJson(me.__dict__["_pb"])) for me in request.model_evaluation
]
print(json.dumps(evaluations_list, indent=2))
# The evaluation slice
evaluation_slice = request.model_evaluation[0].name
```
*Example output*:
```
[
{
"name": "projects/116273516712/locations/us-central1/models/TCN5333697920992542720/modelEvaluations/1436745357261371663",
"annotationSpecId": "3130761503557287936",
"createTime": "2021-03-01T02:56:28.878044Z",
"evaluatedExampleCount": 1193,
"classificationEvaluationMetrics": {
"auPrc": 0.99065405,
"confidenceMetricsEntry": [
{
"recall": 1.0,
"precision": 0.01424979,
"f1Score": 0.028099174
},
{
"confidenceThreshold": 0.05,
"recall": 1.0,
"precision": 0.5862069,
"f1Score": 0.73913044
},
{
"confidenceThreshold": 0.94,
"recall": 0.64705884,
"precision": 1.0,
"f1Score": 0.7857143
},
# REMOVED FOR BREVITY
{
"confidenceThreshold": 0.999,
"recall": 0.21372032,
"precision": 1.0,
"f1Score": 0.35217392
},
{
"confidenceThreshold": 1.0,
"recall": 0.0026385225,
"precision": 1.0,
"f1Score": 0.005263158
}
],
"logLoss": 0.14686257
},
"displayName": "achievement"
}
]
```
### [projects.locations.models.modelEvaluations.get](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models.modelEvaluations/get)
#### Call
```
request = clients["automl"].get_model_evaluation(name=evaluation_slice)
```
#### Response
```
print(MessageToJson(request.__dict__["_pb"]))
```
*Example output*:
```
{
"name": "projects/116273516712/locations/us-central1/models/TCN5333697920992542720/modelEvaluations/1436745357261371663",
"annotationSpecId": "3130761503557287936",
"createTime": "2021-03-01T02:56:28.878044Z",
"evaluatedExampleCount": 1193,
"classificationEvaluationMetrics": {
"auPrc": 0.99065405,
"confidenceMetricsEntry": [
{
"recall": 1.0,
"precision": 0.01424979,
"f1Score": 0.028099174
},
{
"confidenceThreshold": 0.05,
"recall": 1.0,
"precision": 0.5862069,
"f1Score": 0.73913044
},
# REMOVED FOR BREVITY
{
"confidenceThreshold": 0.999,
"recall": 0.23529412,
"precision": 1.0,
"f1Score": 0.3809524
},
{
"confidenceThreshold": 1.0,
"precision": 1.0
}
],
"logLoss": 0.005436425
},
"displayName": "exercise"
}
```
## Make batch predictions
### Prepare files for batch prediction
```
test_item = ! gsutil cat $IMPORT_FILE | head -n1
test_item, test_label = str(test_item[0]).split(",")
print(test_item, test_label)
import json
import tensorflow as tf
test_item_uri = "gs://" + BUCKET_NAME + "/test.txt"
with tf.io.gfile.GFile(test_item_uri, "w") as f:
f.write(test_item + "\n")
gcs_input_uri = "gs://" + BUCKET_NAME + "/batch.csv"
with tf.io.gfile.GFile(gcs_input_uri, "w") as f:
f.write(test_item_uri + "\n")
! gsutil cat $gcs_input_uri
! gsutil cat $test_item_uri
```
*Example output*:
```
gs://migration-ucaip-trainingaip-20210228224317/test.txt
I went on a successful date with someone I felt sympathy and connection with.
```
### [projects.locations.models.batchPredict](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/batchPredict)
#### Request
```
input_config = {"gcs_source": {"input_uris": [gcs_input_uri]}}
output_config = {
"gcs_destination": {"output_uri_prefix": "gs://" + f"{BUCKET_NAME}/batch_output/"}
}
print(
MessageToJson(
automl.BatchPredictRequest(
name=model_id, input_config=input_config, output_config=output_config
).__dict__["_pb"]
)
)
```
*Example output*:
```
{
"name": "projects/116273516712/locations/us-central1/models/TCN5333697920992542720",
"inputConfig": {
"gcsSource": {
"inputUris": [
"gs://migration-ucaip-trainingaip-20210228224317/batch.csv"
]
}
},
"outputConfig": {
"gcsDestination": {
"outputUriPrefix": "gs://migration-ucaip-trainingaip-20210228224317/batch_output/"
}
}
}
```
#### Call
```
request = clients["prediction"].batch_predict(
name=model_id, input_config=input_config, output_config=output_config
)
```
#### Response
```
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
```
*Example output*:
```
{}
```
```
destination_uri = output_config["gcs_destination"]["output_uri_prefix"][:-1]
! gsutil ls $destination_uri/*
! gsutil cat $destination_uri/prediction*/*.jsonl
```
*Example output*:
```
gs://migration-ucaip-trainingaip-20210228224317/batch_output/prediction-happiness_20210228224317-2021-03-01T02:57:02.004934Z/text_classification_1.jsonl
gs://migration-ucaip-trainingaip-20210228224317/batch_output/prediction-happiness_20210228224317-2021-03-01T02:57:02.004934Z/text_classification_2.jsonl
{"textSnippet":{"contentUri":"gs://migration-ucaip-trainingaip-20210228224317/test.txt"},"annotations":[{"annotationSpecId":"5436604512770981888","classification":{"score":0.93047273},"displayName":"affection"},{"annotationSpecId":"3707222255860711424","classification":{"score":0.002518793},"displayName":"achievement"},{"annotationSpecId":"7742447521984675840","classification":{"score":1.3182563E-4},"displayName":"enjoy_the_moment"},{"annotationSpecId":"824918494343593984","classification":{"score":0.06613126},"displayName":"bonding"},{"annotationSpecId":"1977839998950440960","classification":{"score":1.5267624E-5},"displayName":"leisure"},{"annotationSpecId":"8318908274288099328","classification":{"score":8.887557E-6},"displayName":"nature"},{"annotationSpecId":"3130761503557287936","classification":{"score":7.2130124E-4},"displayName":"exercise"}]}
```
## Make online predictions
### [projects.locations.models.deploy](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/deploy)
#### Call
```
request = clients["automl"].deploy_model(name=model_id)
```
#### Response
```
result = request.result()
print(MessageToJson(result))
```
*Example output*:
```
{}
```
### [projects.locations.models.predict](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/predict)
### Prepare data item for online prediction
```
test_item = ! gsutil cat $IMPORT_FILE | head -n1
test_item, test_label = str(test_item[0]).split(",")
```
#### Request
```
payload = {"text_snippet": {"content": test_item, "mime_type": "text/plain"}}
request = automl.PredictRequest(name=model_id, payload=payload)
print(MessageToJson(request.__dict__["_pb"]))
```
*Example output*:
```
{
"name": "projects/116273516712/locations/us-central1/models/TCN5333697920992542720",
"payload": {
"textSnippet": {
"content": "I went on a successful date with someone I felt sympathy and connection with.",
"mimeType": "text/plain"
}
}
}
```
#### Call
```
request = clients["prediction"].predict(request=request)
```
#### Response
```
print(MessageToJson(request.__dict__["_pb"]))
```
*Example output*:
```
{
"payload": [
{
"annotationSpecId": "5436604512770981888",
"classification": {
"score": 0.9272586
},
"displayName": "affection"
},
{
"annotationSpecId": "824918494343593984",
"classification": {
"score": 0.068884976
},
"displayName": "bonding"
},
{
"annotationSpecId": "3707222255860711424",
"classification": {
"score": 0.0028119811
},
"displayName": "achievement"
},
{
"annotationSpecId": "3130761503557287936",
"classification": {
"score": 0.0008869726
},
"displayName": "exercise"
},
{
"annotationSpecId": "7742447521984675840",
"classification": {
"score": 0.00013229548
},
"displayName": "enjoy_the_moment"
},
{
"annotationSpecId": "1977839998950440960",
"classification": {
"score": 1.5584701e-05
},
"displayName": "leisure"
},
{
"annotationSpecId": "8318908274288099328",
"classification": {
"score": 9.5975e-06
},
"displayName": "nature"
}
]
}
```
# Cleaning up
To clean up all GCP resources used in this project, you can [delete the GCP
project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial.
```
delete_dataset = True
delete_model = True
delete_bucket = True
# Delete the dataset using the AutoML fully qualified identifier for the dataset
try:
if delete_dataset:
clients["automl"].delete_dataset(name=dataset_id)
except Exception as e:
print(e)
# Delete the model using the AutoML fully qualified identifier for the model
try:
if delete_model:
clients["automl"].delete_model(name=model_id)
except Exception as e:
print(e)
if delete_bucket and "BUCKET_NAME" in globals():
! gsutil rm -r gs://$BUCKET_NAME
```
| github_jupyter |
#### Copyright 2017 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.
```
# 신경망 소개
**학습 목표:**
* 텐서플로우의 `DNNRegressor` 클래스를 사용하여 신경망(NN) 및 히든 레이어를 정의한다
* 비선형성을 갖는 데이터 세트를 신경망에 학습시켜 선형 회귀 모델보다 우수한 성능을 달성한다
이전 실습에서는 모델에 비선형성을 통합하는 데 도움이 되는 합성 특성을 사용했습니다.
비선형성을 갖는 대표적인 세트는 위도와 경도였지만 다른 특성도 있을 수 있습니다.
일단 이전 실습의 로지스틱 회귀 작업이 아닌 표준 회귀 작업으로 돌아가겠습니다. 즉, `median_house_value`를 직접 예측할 것입니다.
## 설정
우선 데이터를 로드하고 준비하겠습니다.
```
from __future__ import print_function
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging.set_verbosity(tf.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
california_housing_dataframe = pd.read_csv("https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv", sep=",")
california_housing_dataframe = california_housing_dataframe.reindex(
np.random.permutation(california_housing_dataframe.index))
def preprocess_features(california_housing_dataframe):
"""Prepares input features from California housing data set.
Args:
california_housing_dataframe: A Pandas DataFrame expected to contain data
from the California housing data set.
Returns:
A DataFrame that contains the features to be used for the model, including
synthetic features.
"""
selected_features = california_housing_dataframe[
["latitude",
"longitude",
"housing_median_age",
"total_rooms",
"total_bedrooms",
"population",
"households",
"median_income"]]
processed_features = selected_features.copy()
# Create a synthetic feature.
processed_features["rooms_per_person"] = (
california_housing_dataframe["total_rooms"] /
california_housing_dataframe["population"])
return processed_features
def preprocess_targets(california_housing_dataframe):
"""Prepares target features (i.e., labels) from California housing data set.
Args:
california_housing_dataframe: A Pandas DataFrame expected to contain data
from the California housing data set.
Returns:
A DataFrame that contains the target feature.
"""
output_targets = pd.DataFrame()
# Scale the target to be in units of thousands of dollars.
output_targets["median_house_value"] = (
california_housing_dataframe["median_house_value"] / 1000.0)
return output_targets
# Choose the first 12000 (out of 17000) examples for training.
training_examples = preprocess_features(california_housing_dataframe.head(12000))
training_targets = preprocess_targets(california_housing_dataframe.head(12000))
# Choose the last 5000 (out of 17000) examples for validation.
validation_examples = preprocess_features(california_housing_dataframe.tail(5000))
validation_targets = preprocess_targets(california_housing_dataframe.tail(5000))
# Double-check that we've done the right thing.
print("Training examples summary:")
display.display(training_examples.describe())
print("Validation examples summary:")
display.display(validation_examples.describe())
print("Training targets summary:")
display.display(training_targets.describe())
print("Validation targets summary:")
display.display(validation_targets.describe())
```
## 신경망 구축
NN은 [DNNRegressor](https://www.tensorflow.org/api_docs/python/tf/estimator/DNNRegressor) 클래스에 의해 정의됩니다.
**`hidden_units`**를 사용하여 NN의 구조를 정의합니다. `hidden_units` 인수는 정수의 목록을 제공하며, 각 정수는 히든 레이어에 해당하고 포함된 노드의 수를 나타냅니다. 예를 들어 아래 대입식을 살펴보세요.
`hidden_units=[3,10]`
위 대입식은 히든 레이어 2개를 갖는 신경망을 지정합니다.
* 1번 히든 레이어는 노드 3개를 포함합니다.
* 2번 히든 레이어는 노드 10개를 포함합니다.
레이어를 늘리려면 목록에 정수를 더 추가하면 됩니다. 예를 들어 `hidden_units=[10,20,30,40]`은 각각 10개, 20개, 30개, 40개의 유닛을 갖는 4개의 레이어를 만듭니다.
기본적으로 모든 히든 레이어는 ReLu 활성화를 사용하며 완전 연결성을 갖습니다.
```
def construct_feature_columns(input_features):
"""Construct the TensorFlow Feature Columns.
Args:
input_features: The names of the numerical input features to use.
Returns:
A set of feature columns
"""
return set([tf.feature_column.numeric_column(my_feature)
for my_feature in input_features])
def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
"""Trains a neural net regression model.
Args:
features: pandas DataFrame of features
targets: pandas DataFrame of targets
batch_size: Size of batches to be passed to the model
shuffle: True or False. Whether to shuffle the data.
num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely
Returns:
Tuple of (features, labels) for next data batch
"""
# Convert pandas data into a dict of np arrays.
features = {key:np.array(value) for key,value in dict(features).items()}
# Construct a dataset, and configure batching/repeating.
ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit
ds = ds.batch(batch_size).repeat(num_epochs)
# Shuffle the data, if specified.
if shuffle:
ds = ds.shuffle(10000)
# Return the next batch of data.
features, labels = ds.make_one_shot_iterator().get_next()
return features, labels
def train_nn_regression_model(
learning_rate,
steps,
batch_size,
hidden_units,
training_examples,
training_targets,
validation_examples,
validation_targets):
"""Trains a neural network regression model.
In addition to training, this function also prints training progress information,
as well as a plot of the training and validation loss over time.
Args:
learning_rate: A `float`, the learning rate.
steps: A non-zero `int`, the total number of training steps. A training step
consists of a forward and backward pass using a single batch.
batch_size: A non-zero `int`, the batch size.
hidden_units: A `list` of int values, specifying the number of neurons in each layer.
training_examples: A `DataFrame` containing one or more columns from
`california_housing_dataframe` to use as input features for training.
training_targets: A `DataFrame` containing exactly one column from
`california_housing_dataframe` to use as target for training.
validation_examples: A `DataFrame` containing one or more columns from
`california_housing_dataframe` to use as input features for validation.
validation_targets: A `DataFrame` containing exactly one column from
`california_housing_dataframe` to use as target for validation.
Returns:
A `DNNRegressor` object trained on the training data.
"""
periods = 10
steps_per_period = steps / periods
# Create a DNNRegressor object.
my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)
dnn_regressor = tf.estimator.DNNRegressor(
feature_columns=construct_feature_columns(training_examples),
hidden_units=hidden_units,
optimizer=my_optimizer
)
# Create input functions.
training_input_fn = lambda: my_input_fn(training_examples,
training_targets["median_house_value"],
batch_size=batch_size)
predict_training_input_fn = lambda: my_input_fn(training_examples,
training_targets["median_house_value"],
num_epochs=1,
shuffle=False)
predict_validation_input_fn = lambda: my_input_fn(validation_examples,
validation_targets["median_house_value"],
num_epochs=1,
shuffle=False)
# Train the model, but do so inside a loop so that we can periodically assess
# loss metrics.
print("Training model...")
print("RMSE (on training data):")
training_rmse = []
validation_rmse = []
for period in range (0, periods):
# Train the model, starting from the prior state.
dnn_regressor.train(
input_fn=training_input_fn,
steps=steps_per_period
)
# Take a break and compute predictions.
training_predictions = dnn_regressor.predict(input_fn=predict_training_input_fn)
training_predictions = np.array([item['predictions'][0] for item in training_predictions])
validation_predictions = dnn_regressor.predict(input_fn=predict_validation_input_fn)
validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])
# Compute training and validation loss.
training_root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(training_predictions, training_targets))
validation_root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(validation_predictions, validation_targets))
# Occasionally print the current loss.
print(" period %02d : %0.2f" % (period, training_root_mean_squared_error))
# Add the loss metrics from this period to our list.
training_rmse.append(training_root_mean_squared_error)
validation_rmse.append(validation_root_mean_squared_error)
print("Model training finished.")
# Output a graph of loss metrics over periods.
plt.ylabel("RMSE")
plt.xlabel("Periods")
plt.title("Root Mean Squared Error vs. Periods")
plt.tight_layout()
plt.plot(training_rmse, label="training")
plt.plot(validation_rmse, label="validation")
plt.legend()
print("Final RMSE (on training data): %0.2f" % training_root_mean_squared_error)
print("Final RMSE (on validation data): %0.2f" % validation_root_mean_squared_error)
return dnn_regressor
```
## 작업 1: NN 모델 학습
**RMSE를 110 미만으로 낮추는 것을 목표로 초매개변수를 조정합니다.**
다음 블록을 실행하여 NN 모델을 학습시킵니다.
많은 특성을 사용한 선형 회귀 실습에서 RMSE이 110 정도면 상당히 양호하다고 설명한 바 있습니다. 더 우수한 모델을 목표로 해 보겠습니다.
이번에 수행할 작업은 다양한 학습 설정을 수정하여 검증 데이터에 대한 정확성을 높이는 것입니다.
NN에는 과적합이라는 위험이 도사리고 있습니다. 학습 데이터에 대한 손실과 검증 데이터에 대한 손실의 격차를 조사하면 모델에서 과적합이 시작되고 있는지를 판단하는 데 도움이 됩니다. 일반적으로 격차가 증가하기 시작하면 과적합의 확실한 증거가 됩니다.
매우 다양한 설정이 가능하므로, 각 시도에서 설정을 잘 기록하여 개발 방향을 잡는 데 참고하는 것이 좋습니다.
또한 괜찮은 설정을 발견했다면 여러 번 실행하여 결과의 재현성을 확인하시기 바랍니다. NN 가중치는 일반적으로 작은 무작위 값으로 초기화되므로 실행 시마다 약간의 차이를 보입니다.
```
dnn_regressor = train_nn_regression_model(
learning_rate=0.01,
steps=500,
batch_size=10,
hidden_units=[10, 2],
training_examples=training_examples,
training_targets=training_targets,
validation_examples=validation_examples,
validation_targets=validation_targets)
```
### 해결 방법
가능한 해결 방법을 보려면 아래를 클릭하세요.
**참고:** 이 매개변수 선택은 어느 정도 임의적인 것입니다. 여기에서는 오차가 목표치 아래로 떨어질 때까지 점점 복잡한 조합을 시도하면서 학습 시간을 늘렸습니다. 이 조합은 결코 최선의 조합이 아니며, 다른 조합이 더 낮은 RMSE를 달성할 수도 있습니다. 오차를 최소화하는 모델을 찾는 것이 목표라면 매개변수 검색과 같은 보다 엄밀한 절차를 사용해야 합니다.
```
dnn_regressor = train_nn_regression_model(
learning_rate=0.001,
steps=2000,
batch_size=100,
hidden_units=[10, 10],
training_examples=training_examples,
training_targets=training_targets,
validation_examples=validation_examples,
validation_targets=validation_targets)
```
## 작업 2: 테스트 데이터로 평가
**검증 성능 결과가 테스트 데이터에 대해서도 유지되는지 확인합니다.**
만족할 만한 모델이 만들어졌으면 테스트 데이터로 평가하고 검증 성능과 비교해 봅니다.
테스트 데이터 세트는 [여기](https://download.mlcc.google.com/mledu-datasets/california_housing_test.csv)에 있습니다.
```
california_housing_test_data = pd.read_csv("https://download.mlcc.google.com/mledu-datasets/california_housing_test.csv", sep=",")
# YOUR CODE HERE
```
### 해결 방법
가능한 해결 방법을 보려면 아래를 클릭하세요.
위 코드에서 수행하는 작업과 마찬가지로 적절한 데이터 파일을 로드하고 전처리한 후 predict 및 mean_squared_error를 호출해야 합니다.
모든 레코드를 사용할 것이므로 테스트 데이터를 무작위로 추출할 필요는 없습니다.
```
california_housing_test_data = pd.read_csv("https://download.mlcc.google.com/mledu-datasets/california_housing_test.csv", sep=",")
test_examples = preprocess_features(california_housing_test_data)
test_targets = preprocess_targets(california_housing_test_data)
predict_testing_input_fn = lambda: my_input_fn(test_examples,
test_targets["median_house_value"],
num_epochs=1,
shuffle=False)
test_predictions = dnn_regressor.predict(input_fn=predict_testing_input_fn)
test_predictions = np.array([item['predictions'][0] for item in test_predictions])
root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(test_predictions, test_targets))
print("Final RMSE (on test data): %0.2f" % root_mean_squared_error)
```
| github_jupyter |
# Job Search - On-the-Job Search
<a id='index-1'></a>
```
import numpy as np
import scipy.stats as stats
from interpolation import interp
from numba import njit, prange
import matplotlib.pyplot as plt
%matplotlib inline
from math import gamma
class JVWorker:
r"""
A Jovanovic-type model of employment with on-the-job search.
"""
def __init__(self,
A=1.4,
α=0.6,
β=0.96, # Discount factor
π=np.sqrt, # Search effort function
a=2, # Parameter of f
b=2, # Parameter of f
grid_size=50,
mc_size=100,
ɛ=1e-4):
self.A, self.α, self.β, self.π = A, α, β, π
self.mc_size, self.ɛ = mc_size, ɛ
self.g = njit(lambda x, ϕ: A * (x * ϕ)**α) # Transition function
self.f_rvs = np.random.beta(a, b, mc_size)
# Max of grid is the max of a large quantile value for f and the
# fixed point y = g(y, 1)
ɛ = 1e-4
grid_max = max(A**(1 / (1 - α)), stats.beta(a, b).ppf(1 - ɛ))
# Human capital
self.x_grid = np.linspace(ɛ, grid_max, grid_size)
def operator_factory(jv, parallel_flag=True):
"""
Returns a jitted version of the Bellman operator T
jv is an instance of JVWorker
"""
π, β = jv.π, jv.β
x_grid, ɛ, mc_size = jv.x_grid, jv.ɛ, jv.mc_size
f_rvs, g = jv.f_rvs, jv.g
@njit
def state_action_values(z, x, v):
s, ϕ = z
v_func = lambda x: interp(x_grid, v, x)
integral = 0
for m in range(mc_size):
u = f_rvs[m]
integral += v_func(max(g(x, ϕ), u))
integral = integral / mc_size
q = π(s) * integral + (1 - π(s)) * v_func(g(x, ϕ))
return x * (1 - ϕ - s) + β * q
@njit(parallel=parallel_flag)
def T(v):
"""
The Bellman operator
"""
v_new = np.empty_like(v)
for i in prange(len(x_grid)):
x = x_grid[i]
# Search on a grid
search_grid = np.linspace(ɛ, 1, 15)
max_val = -1
for s in search_grid:
for ϕ in search_grid:
current_val = state_action_values((s, ϕ), x, v) if s + ϕ <= 1 else -1
if current_val > max_val:
max_val = current_val
v_new[i] = max_val
return v_new
@njit
def get_greedy(v):
"""
Computes the v-greedy policy of a given function v
"""
s_policy, ϕ_policy = np.empty_like(v), np.empty_like(v)
for i in range(len(x_grid)):
x = x_grid[i]
# Search on a grid
search_grid = np.linspace(ɛ, 1, 15)
max_val = -1
for s in search_grid:
for ϕ in search_grid:
current_val = state_action_values((s, ϕ), x, v) if s + ϕ <= 1 else -1
if current_val > max_val:
max_val = current_val
max_s, max_ϕ = s, ϕ
s_policy[i], ϕ_policy[i] = max_s, max_ϕ
return s_policy, ϕ_policy
return T, get_greedy
def solve_model(jv,
use_parallel=True,
tol=1e-4,
max_iter=1000,
verbose=True,
print_skip=25):
"""
Solves the model by value function iteration
* jv is an instance of JVWorker
"""
T, _ = operator_factory(jv, parallel_flag=use_parallel)
# Set up loop
v = jv.x_grid * 0.5 # Initial condition
i = 0
error = tol + 1
while i < max_iter and error > tol:
v_new = T(v)
error = np.max(np.abs(v - v_new))
i += 1
if verbose and i % print_skip == 0:
print(f"Error at iteration {i} is {error}.")
v = v_new
if i == max_iter:
print("Failed to converge!")
if verbose and i < max_iter:
print(f"\nConverged in {i} iterations.")
return v_new
jv = JVWorker()
T, get_greedy = operator_factory(jv)
v_star = solve_model(jv)
s_star, ϕ_star = get_greedy(v_star)
plots = [s_star, ϕ_star, v_star]
titles = ["s policy", "ϕ policy", "value function"]
fig, axes = plt.subplots(3, 1, figsize=(12, 12))
for ax, plot, title in zip(axes, plots, titles):
ax.plot(jv.x_grid, plot)
ax.set(title=title)
ax.grid()
axes[-1].set_xlabel("x")
plt.show()
jv = JVWorker(grid_size=25, mc_size=50)
π, g, f_rvs, x_grid = jv.π, jv.g, jv.f_rvs, jv.x_grid
T, get_greedy = operator_factory(jv)
v_star = solve_model(jv, verbose=False)
s_policy, ϕ_policy = get_greedy(v_star)
# Turn the policy function arrays into actual functions
s = lambda y: interp(x_grid, s_policy, y)
ϕ = lambda y: interp(x_grid, ϕ_policy, y)
def h(x, b, u):
return (1 - b) * g(x, ϕ(x)) + b * max(g(x, ϕ(x)), u)
plot_grid_max, plot_grid_size = 1.2, 100
plot_grid = np.linspace(0, plot_grid_max, plot_grid_size)
fig, ax = plt.subplots(figsize=(8, 8))
ticks = (0.25, 0.5, 0.75, 1.0)
ax.set(xticks=ticks, yticks=ticks,
xlim=(0, plot_grid_max),
ylim=(0, plot_grid_max),
xlabel='$x_t$', ylabel='$x_{t+1}$')
ax.plot(plot_grid, plot_grid, 'k--', alpha=0.6) # 45 degree line
for x in plot_grid:
for i in range(jv.mc_size):
b = 1 if np.random.uniform(0, 1) < π(s(x)) else 0
u = f_rvs[i]
y = h(x, b, u)
ax.plot(x, y, 'go', alpha=0.25)
plt.show()
jv = JVWorker()
def xbar(ϕ):
A, α = jv.A, jv.α
return (A * ϕ**α)**(1 / (1 - α))
ϕ_grid = np.linspace(0, 1, 100)
fig, ax = plt.subplots(figsize=(9, 7))
ax.set(xlabel='$\phi$')
ax.plot(ϕ_grid, [xbar(ϕ) * (1 - ϕ) for ϕ in ϕ_grid], label='$w^*(\phi)$')
ax.legend()
plt.show()
```
| github_jupyter |
##### Copyright 2018 The TF-Agents 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.
```
# REINFORCE agent
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/agents/tutorials/6_reinforce_tutorial">
<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/agents/blob/master/docs/tutorials/6_reinforce_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/agents/blob/master/docs/tutorials/6_reinforce_tutorial.ipynb">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />
View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/agents/docs/tutorials/6_reinforce_tutorial.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
## Introduction
This example shows how to train a [REINFORCE](http://www-anw.cs.umass.edu/~barto/courses/cs687/williams92simple.pdf) agent on the Cartpole environment using the TF-Agents library, similar to the [DQN tutorial](1_dqn_tutorial.ipynb).

We will walk you through all the components in a Reinforcement Learning (RL) pipeline for training, evaluation and data collection.
## Setup
If you haven't installed the following dependencies, run:
```
!sudo apt-get install -y xvfb ffmpeg
!pip install gym
!pip install 'imageio==2.4.0'
!pip install PILLOW
!pip install pyvirtualdisplay
!pip install tf-agents
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import base64
import imageio
import IPython
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import PIL.Image
import pyvirtualdisplay
import tensorflow as tf
from tf_agents.agents.reinforce import reinforce_agent
from tf_agents.drivers import dynamic_step_driver
from tf_agents.environments import suite_gym
from tf_agents.environments import tf_py_environment
from tf_agents.eval import metric_utils
from tf_agents.metrics import tf_metrics
from tf_agents.networks import actor_distribution_network
from tf_agents.replay_buffers import tf_uniform_replay_buffer
from tf_agents.trajectories import trajectory
from tf_agents.utils import common
tf.compat.v1.enable_v2_behavior()
# Set up a virtual display for rendering OpenAI gym environments.
display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start()
```
## Hyperparameters
```
env_name = "CartPole-v0" # @param {type:"string"}
num_iterations = 250 # @param {type:"integer"}
collect_episodes_per_iteration = 2 # @param {type:"integer"}
replay_buffer_capacity = 2000 # @param {type:"integer"}
fc_layer_params = (100,)
learning_rate = 1e-3 # @param {type:"number"}
log_interval = 25 # @param {type:"integer"}
num_eval_episodes = 10 # @param {type:"integer"}
eval_interval = 50 # @param {type:"integer"}
```
## Environment
Environments in RL represent the task or problem that we are trying to solve. Standard environments can be easily created in TF-Agents using `suites`. We have different `suites` for loading environments from sources such as the OpenAI Gym, Atari, DM Control, etc., given a string environment name.
Now let us load the CartPole environment from the OpenAI Gym suite.
```
env = suite_gym.load(env_name)
```
We can render this environment to see how it looks. A free-swinging pole is attached to a cart. The goal is to move the cart right or left in order to keep the pole pointing up.
```
#@test {"skip": true}
env.reset()
PIL.Image.fromarray(env.render())
```
The `time_step = environment.step(action)` statement takes `action` in the environment. The `TimeStep` tuple returned contains the environment's next observation and reward for that action. The `time_step_spec()` and `action_spec()` methods in the environment return the specifications (types, shapes, bounds) of the `time_step` and `action` respectively.
```
print('Observation Spec:')
print(env.time_step_spec().observation)
print('Action Spec:')
print(env.action_spec())
```
So, we see that observation is an array of 4 floats: the position and velocity of the cart, and the angular position and velocity of the pole. Since only two actions are possible (move left or move right), the `action_spec` is a scalar where 0 means "move left" and 1 means "move right."
```
time_step = env.reset()
print('Time step:')
print(time_step)
action = np.array(1, dtype=np.int32)
next_time_step = env.step(action)
print('Next time step:')
print(next_time_step)
```
Usually we create two environments: one for training and one for evaluation. Most environments are written in pure python, but they can be easily converted to TensorFlow using the `TFPyEnvironment` wrapper. The original environment's API uses numpy arrays, the `TFPyEnvironment` converts these to/from `Tensors` for you to more easily interact with TensorFlow policies and agents.
```
train_py_env = suite_gym.load(env_name)
eval_py_env = suite_gym.load(env_name)
train_env = tf_py_environment.TFPyEnvironment(train_py_env)
eval_env = tf_py_environment.TFPyEnvironment(eval_py_env)
```
## Agent
The algorithm that we use to solve an RL problem is represented as an `Agent`. In addition to the REINFORCE agent, TF-Agents provides standard implementations of a variety of `Agents` such as [DQN](https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf), [DDPG](https://arxiv.org/pdf/1509.02971.pdf), [TD3](https://arxiv.org/pdf/1802.09477.pdf), [PPO](https://arxiv.org/abs/1707.06347) and [SAC](https://arxiv.org/abs/1801.01290).
To create a REINFORCE Agent, we first need an `Actor Network` that can learn to predict the action given an observation from the environment.
We can easily create an `Actor Network` using the specs of the observations and actions. We can specify the layers in the network which, in this example, is the `fc_layer_params` argument set to a tuple of `ints` representing the sizes of each hidden layer (see the Hyperparameters section above).
```
actor_net = actor_distribution_network.ActorDistributionNetwork(
train_env.observation_spec(),
train_env.action_spec(),
fc_layer_params=fc_layer_params)
```
We also need an `optimizer` to train the network we just created, and a `train_step_counter` variable to keep track of how many times the network was updated.
```
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate)
train_step_counter = tf.compat.v2.Variable(0)
tf_agent = reinforce_agent.ReinforceAgent(
train_env.time_step_spec(),
train_env.action_spec(),
actor_network=actor_net,
optimizer=optimizer,
normalize_returns=True,
train_step_counter=train_step_counter)
tf_agent.initialize()
```
## Policies
In TF-Agents, policies represent the standard notion of policies in RL: given a `time_step` produce an action or a distribution over actions. The main method is `policy_step = policy.step(time_step)` where `policy_step` is a named tuple `PolicyStep(action, state, info)`. The `policy_step.action` is the `action` to be applied to the environment, `state` represents the state for stateful (RNN) policies and `info` may contain auxiliary information such as log probabilities of the actions.
Agents contain two policies: the main policy that is used for evaluation/deployment (agent.policy) and another policy that is used for data collection (agent.collect_policy).
```
eval_policy = tf_agent.policy
collect_policy = tf_agent.collect_policy
```
## Metrics and Evaluation
The most common metric used to evaluate a policy is the average return. The return is the sum of rewards obtained while running a policy in an environment for an episode, and we usually average this over a few episodes. We can compute the average return metric as follows.
```
#@test {"skip": true}
def compute_avg_return(environment, policy, num_episodes=10):
total_return = 0.0
for _ in range(num_episodes):
time_step = environment.reset()
episode_return = 0.0
while not time_step.is_last():
action_step = policy.action(time_step)
time_step = environment.step(action_step.action)
episode_return += time_step.reward
total_return += episode_return
avg_return = total_return / num_episodes
return avg_return.numpy()[0]
# Please also see the metrics module for standard implementations of different
# metrics.
```
## Replay Buffer
In order to keep track of the data collected from the environment, we will use the TFUniformReplayBuffer. This replay buffer is constructed using specs describing the tensors that are to be stored, which can be obtained from the agent using `tf_agent.collect_data_spec`.
```
replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer(
data_spec=tf_agent.collect_data_spec,
batch_size=train_env.batch_size,
max_length=replay_buffer_capacity)
```
For most agents, the `collect_data_spec` is a `Trajectory` named tuple containing the observation, action, reward etc.
## Data Collection
As REINFORCE learns from whole episodes, we define a function to collect an episode using the given data collection policy and save the data (observations, actions, rewards etc.) as trajectories in the replay buffer.
```
#@test {"skip": true}
def collect_episode(environment, policy, num_episodes):
episode_counter = 0
environment.reset()
while episode_counter < num_episodes:
time_step = environment.current_time_step()
action_step = policy.action(time_step)
next_time_step = environment.step(action_step.action)
traj = trajectory.from_transition(time_step, action_step, next_time_step)
# Add trajectory to the replay buffer
replay_buffer.add_batch(traj)
if traj.is_boundary():
episode_counter += 1
# This loop is so common in RL, that we provide standard implementations of
# these. For more details see the drivers module.
```
## Training the agent
The training loop involves both collecting data from the environment and optimizing the agent's networks. Along the way, we will occasionally evaluate the agent's policy to see how we are doing.
The following will take ~3 minutes to run.
```
#@test {"skip": true}
try:
%%time
except:
pass
# (Optional) Optimize by wrapping some of the code in a graph using TF function.
tf_agent.train = common.function(tf_agent.train)
# Reset the train step
tf_agent.train_step_counter.assign(0)
# Evaluate the agent's policy once before training.
avg_return = compute_avg_return(eval_env, tf_agent.policy, num_eval_episodes)
returns = [avg_return]
for _ in range(num_iterations):
# Collect a few episodes using collect_policy and save to the replay buffer.
collect_episode(
train_env, tf_agent.collect_policy, collect_episodes_per_iteration)
# Use data from the buffer and update the agent's network.
experience = replay_buffer.gather_all()
train_loss = tf_agent.train(experience)
replay_buffer.clear()
step = tf_agent.train_step_counter.numpy()
if step % log_interval == 0:
print('step = {0}: loss = {1}'.format(step, train_loss.loss))
if step % eval_interval == 0:
avg_return = compute_avg_return(eval_env, tf_agent.policy, num_eval_episodes)
print('step = {0}: Average Return = {1}'.format(step, avg_return))
returns.append(avg_return)
```
## Visualization
### Plots
We can plot return vs global steps to see the performance of our agent. In `Cartpole-v0`, the environment gives a reward of +1 for every time step the pole stays up, and since the maximum number of steps is 200, the maximum possible return is also 200.
```
#@test {"skip": true}
steps = range(0, num_iterations + 1, eval_interval)
plt.plot(steps, returns)
plt.ylabel('Average Return')
plt.xlabel('Step')
plt.ylim(top=250)
```
### Videos
It is helpful to visualize the performance of an agent by rendering the environment at each step. Before we do that, let us first create a function to embed videos in this colab.
```
def embed_mp4(filename):
"""Embeds an mp4 file in the notebook."""
video = open(filename,'rb').read()
b64 = base64.b64encode(video)
tag = '''
<video width="640" height="480" controls>
<source src="data:video/mp4;base64,{0}" type="video/mp4">
Your browser does not support the video tag.
</video>'''.format(b64.decode())
return IPython.display.HTML(tag)
```
The following code visualizes the agent's policy for a few episodes:
```
num_episodes = 3
video_filename = 'imageio.mp4'
with imageio.get_writer(video_filename, fps=60) as video:
for _ in range(num_episodes):
time_step = eval_env.reset()
video.append_data(eval_py_env.render())
while not time_step.is_last():
action_step = tf_agent.policy.action(time_step)
time_step = eval_env.step(action_step.action)
video.append_data(eval_py_env.render())
embed_mp4(video_filename)
```
| github_jupyter |
# Ordering by metrics and retraining phase
## Dataset: Intel
## Configuration 2
2. Incremental guided retraining starting from the original model using the new adversarial inputs and original training set.
```
pip install --user tensorflow==2.5
import argparse
import numpy as np
import tensorflow as tf
import keras.backend as K
import matplotlib.pyplot as plt
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from keras.regularizers import l2
import glob
import os
import cv2
import keras
import time
import argparse
from tqdm import tqdm
from keras.models import load_model, Model
cd '../utils'
# utils for project
import utils_guided_retraining as utils
cd '../notebooks/'
x_train,y_train = utils.get_data("intel","Train")
x_val,y_val = utils.get_data("intel","Val")
x_test,y_test = utils.get_data("intel","Test")
x_train_and_adversary,y_train_and_adversary = utils.get_data("intel","Train_and_adversary")
x_adversary_training = x_train_and_adversary[len(x_train):]
print(len(x_adversary_training))
y_adversary_training = y_train_and_adversary[len(y_train):]
print(len(y_adversary_training))
# Obtaining adversarial examples for testing
x_test_and_adversary,y_test_and_adversary = utils.get_adversarial_data("intel",'Test_fgsm')
x_adversary_test_fgsm = x_test_and_adversary[len(x_test):]
print(len(x_adversary_test_fgsm))
y_adversary_test_fgsm = y_test_and_adversary[len(y_test):]
print(len(y_adversary_test_fgsm))
```
## ----
```
# Original model
model_dir = "C:/Users/fjdur/Desktop/upc/project_notebooks/github_project/DL_notebooks/models/intel_model_21_10/"
model_original = utils.My_model("intel",True, model_dir)
model_original.evaluate(x_test,y_test)
model_original.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm)
model_original.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm)
```
## Obtaining new LSA and DSA values
```
save_dir_lsa = "C:/Users/fjdur/Desktop/upc/project_notebooks/github_project/DL_notebooks/SA_values/intel_lsa_values_2.npy"
save_dir_dsa = "C:/Users/fjdur/Desktop/upc/project_notebooks/github_project/DL_notebooks/SA_values/intel_dsa_values_2.npy"
target_lsa = np.load(save_dir_lsa)
target_dsa = np.load(save_dir_dsa)
lsa_values = target_lsa
dsa_values = target_dsa
# Obtaining top n images by LSA values
top_images_by_lsa = utils.get_x_of_indexes(list(np.flip(np.argsort(lsa_values))),x_train_and_adversary)
top_labels_by_lsa = utils.get_x_of_indexes(list(np.flip(np.argsort(lsa_values))),y_train_and_adversary)
top_images_by_dsa = utils.get_x_of_indexes(list(np.flip(np.argsort(dsa_values))),x_train_and_adversary)
top_labels_by_dsa = utils.get_x_of_indexes(list(np.flip(np.argsort(dsa_values))),y_train_and_adversary)
len(top_images_by_lsa)//20
top_images_by_lsa_5000 = np.array(top_images_by_lsa[:5000])
top_labels_by_lsa_5000 = np.array(top_labels_by_lsa[:5000])
m = 700
n = 0
image_sets_lsa = []
label_sets_lsa = []
for i in range(len(top_images_by_lsa)//m):
print(i,":")
if (i+1 >= len(top_images_by_lsa)//m):
print("Last")
print(0," -> ",n+m+(len(top_images_by_lsa)%m))
top_images_by_lsa_n = np.array(top_images_by_lsa[:n+m+(len(top_images_by_lsa)%m)])
top_labels_by_lsa_n = np.array(top_labels_by_lsa[:n+m+(len(top_images_by_lsa)%m)])
else:
print(0," -> ",m+n)
top_images_by_lsa_n = np.array(top_images_by_lsa[:n+m])
top_labels_by_lsa_n = np.array(top_labels_by_lsa[:n+m])
image_sets_lsa.append(top_images_by_lsa_n)
label_sets_lsa.append(top_labels_by_lsa_n)
print(len(top_images_by_lsa_n))
n += m
```
## Training guided by LSA
```
dataset = 'intel'
model_lsa_5000 = utils.My_model(dataset,True,model_dir)
model_lsa_5000.compile_model()
model_lsa_5000.fit_model(top_images_by_lsa_5000,top_labels_by_lsa_5000,x_val,y_val)
for i in range(7):
print(i)
models_lsa[i] = utils.My_model('intel',True,model_dir)
models_lsa[i].compile_model()
models_lsa[1].evaluate(x_test,y_test)
print(model_dir)
models_lsa = []
for i in range(len(label_sets_lsa)):
print(i,":")
model = utils.My_model('intel',True,model_dir)
model.compile_model()
models_lsa.append(model)
print(len(models_lsa))
n = 0
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 1
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 2
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 3
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 4
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 5
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 6
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 7
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 8
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 9
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 10
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 11
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 12
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
models_lsa[13] = utils.My_model('intel',True,model_dir)
models_lsa[13].compile_model()
models_lsa[14] = utils.My_model('intel',True,model_dir)
models_lsa[14].compile_model()
n = 13
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 14
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 15
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 16
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 17
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 18
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = 19
models_lsa[n].fit_model(image_sets_lsa[n],label_sets_lsa[n],x_val,y_val,epochs=20,batch_size = 128)
loading = True
models_lsa = []
if loading:
for i in range(20):
model_lsa_dir = "D:/models/intel_models/C2/intel_model_c2_sep_lsa_e2_"+str(i)
print(model_lsa_dir)
model =utils.My_model('intel',True,model_lsa_dir)
model.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
models_lsa.append(model)
```
## Training guided by DSA
```
top_images_by_dsa_5000 = np.array(top_images_by_dsa[:5000])
top_labels_by_dsa_5000 = np.array(top_labels_by_dsa[:5000])
model_dsa_5000 = utils.My_model(dataset,True,model_dir)
model_dsa_5000.compile_model()
model_dsa_5000.fit_model(top_images_by_dsa_5000,top_labels_by_dsa_5000,x_val,y_val)
m = 700
n = 0
image_sets_dsa = []
label_sets_dsa = []
for i in range(len(top_images_by_dsa)//m):
print(i,":")
if (i+1 >= len(top_images_by_dsa)//m):
print("Last")
print(0," -> ",n+m+(len(top_images_by_dsa)%m))
top_images_by_dsa_n = np.array(top_images_by_dsa[:n+m+(len(top_images_by_dsa)%m)])
top_labels_by_dsa_n = np.array(top_labels_by_dsa[:n+m+(len(top_images_by_dsa)%m)])
else:
print(0," -> ",m+n)
top_images_by_dsa_n = np.array(top_images_by_dsa[:n+m])
top_labels_by_dsa_n = np.array(top_labels_by_dsa[:n+m])
image_sets_dsa.append(top_images_by_dsa_n)
label_sets_dsa.append(top_labels_by_dsa_n)
print(len(top_images_by_dsa_n))
n += m
print(model_dir)
models_dsa = []
for i in range(len(label_sets_dsa)):
print(i,":")
model = utils.My_model('intel',True,model_dir)
model.compile_model()
models_dsa.append(model)
n=0
for i in range(7):
print(i)
models_dsa[i] = utils.My_model('intel',True,model_dir)
models_dsa[i].compile_model()
print(models_dsa[0].evaluate(x_test,y_test))
print(models_dsa[1].evaluate(x_test,y_test))
n=0
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#4
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
for i in range(7):
print(i)
loading = True
models_dsa = []
if loading:
for i in range(7):
model_dsa_dir = "D:/models/intel/C3/intel_model_c3_sep_dsa_e2_"+str(i)
print(model_dsa_dir)
model =utils.My_model('intel',True,model_dsa_dir)
model.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
models_lsa.append(model)
n=7
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#9
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#14
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#19
models_dsa[n].fit_model(image_sets_dsa[n],label_sets_dsa[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
loading = True
models_dsa = []
if loading:
for i in range(20):
model_dsa_dir = "D:/models/intel_models/C2/intel_model_c2_sep_dsa_e2_"+str(i)
print(model_dsa_dir)
model =utils.My_model('intel',True,model_dsa_dir)
model.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
models_dsa.append(model)
```
## Training guided by Random
```
import random
random_indexes =list(range(len(x_train_and_adversary)))
random.shuffle(random_indexes)
print(random_indexes[:10])
print(len(random_indexes))
save_dir = "C:/Users/fjdur/Desktop/upc/project_notebooks/github_project/DL_notebooks/SA_values/intel_random_values_e2.npy"
#np.save(save_dir,np.array(random_indexes))
random_indexes = np.load(save_dir)
# Obtaining top n images by LSA values
top_images_by_random = utils.get_x_of_indexes(list(np.flip(np.argsort(random_indexes))),x_train_and_adversary)
top_labels_by_random = utils.get_x_of_indexes(list(np.flip(np.argsort(random_indexes))),y_train_and_adversary)
top_images_by_random_5000 = np.array(top_images_by_random[:5000])
top_labels_by_random_5000 = np.array(top_labels_by_random[:5000])
model_random_5000 = utils.My_model(dataset,True,model_dir)
model_random_5000.compile_model()
model_random_5000.fit_model(top_images_by_random_5000,top_labels_by_random_5000,x_val,y_val)
m = 700
n = 0
image_sets_random = []
label_sets_random = []
for i in range(len(top_images_by_random)//m):
print(i,":")
if (i+1 >= len(top_images_by_random)//m):
print("Last")
print(0," -> ",n+m+(len(top_images_by_random)%m))
top_images_by_random_n = np.array(top_images_by_random[:n+m+(len(top_images_by_random)%m)])
top_labels_by_random_n = np.array(top_labels_by_random[:n+m+(len(top_images_by_random)%m)])
else:
print(0," -> ",m+n)
top_images_by_random_n = np.array(top_images_by_random[:n+m])
top_labels_by_random_n = np.array(top_labels_by_random[:n+m])
image_sets_random.append(top_images_by_random_n)
label_sets_random.append(top_labels_by_random_n)
print(len(top_images_by_random_n))
n += m
print(model_dir)
models_random = []
for i in range(len(label_sets_random)):
print(i,":")
model = utils.My_model('intel',True,model_dir)
model.compile_model()
models_random.append(model)
n=0
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
n=2
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#4
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#9
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#14
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#19
models_random[n].fit_model(image_sets_random[n],label_sets_random[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
loading = True
models_random = []
if loading:
for i in range(20):
model_random_dir = "D:/models/intel_models/C2/intel_model_c2_sep_random_e2_"+str(i)
print(model_random_dir)
model =utils.My_model('intel',True,model_random_dir)
model.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
models_random.append(model)
```
## Training guided by NC
```
# NC
nc_values = []
for i in range(1,15):
save_dir_rand = "C:/Users/fjdur/Desktop/upc/project_notebooks/github_project/DL_notebooks/NC_values/intel_nc_values_"+str(i)+".npy"
#print(save_dir_rand)
tmp_values = np.load(save_dir_rand)
#print(tmp_values.shape)
nc_values = np.append(nc_values,tmp_values)
top_images_by_nc = utils.get_x_of_indexes(list(np.flip(np.argsort(nc_values))),x_train_and_adversary)
top_labels_by_nc = utils.get_x_of_indexes(list(np.flip(np.argsort(nc_values))),y_train_and_adversary)
top_images_by_nc_5000 = np.array(top_images_by_nc[:5000])
top_labels_by_nc_5000 = np.array(top_labels_by_nc[:5000])
model_nc_5000 = utils.My_model(dataset,True,model_dir)
model_nc_5000.compile_model()
model_nc_5000.fit_model(top_images_by_nc_5000,top_labels_by_nc_5000,x_val,y_val)
m = 700
n = 0
image_sets_nc = []
label_sets_nc = []
for i in range(len(top_images_by_nc)//m):
print(i,":")
if (i+1 >= len(top_images_by_nc)//m):
print("Last")
print(0," -> ",n+m+(len(top_images_by_nc)%m))
top_images_by_nc_n = np.array(top_images_by_nc[:n+m+(len(top_images_by_nc)%m)])
top_labels_by_nc_n = np.array(top_labels_by_nc[:n+m+(len(top_images_by_nc)%m)])
else:
print(0," -> ",m+n)
top_images_by_nc_n = np.array(top_images_by_nc[:n+m])
top_labels_by_nc_n = np.array(top_labels_by_nc[:n+m])
image_sets_nc.append(top_images_by_nc_n)
label_sets_nc.append(top_labels_by_nc_n)
print(len(top_images_by_nc_n))
n += m
print(model_dir)
models_nc = []
for i in range(len(label_sets_nc)):
print(i,":")
model = utils.My_model('intel',True,model_dir)
model.compile_model()
models_nc.append(model)
n=0
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
n=1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#4
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#9
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#14
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
print(n)#19
models_nc[n].fit_model(image_sets_nc[n],label_sets_nc[n],x_val,y_val,epochs=20,batch_size = 128)
n = n+1
loading = True
models_nc = []
if loading:
for i in range(20):
model_nc_dir = "D:/models/intel_models/C2/intel_model_c2_sep_nc_e2_"+str(i)
print(model_nc_dir)
model =utils.My_model('intel',True,model_nc_dir)
model.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
models_nc.append(model)
```
## Evaluating
```
model_lsa_5000.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
model_dsa_5000.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
model_random_5000.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
model_nc_5000.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
model_original.model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy',tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
evaluate_lsa_5k_0 = []
evaluate_dsa_5k_0 = []
evaluate_nc_5k_0 = []
evaluate_random_5k_0 = []
evaluate_lsa_5k_0.append(model_lsa_5000.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
evaluate_dsa_5k_0.append(model_dsa_5000.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
evaluate_random_5k_0.append(model_random_5000.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
evaluate_nc_5k_0.append(model_nc_5000.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
# Metrics using adversarial test
evaluate_lsa_0 = []
evaluate_dsa_0 = []
evaluate_nc_0 = []
evaluate_random_0 = []
evaluate_lsa_0.append(model_original.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
evaluate_dsa_0.append(model_original.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
evaluate_nc_0.append(model_original.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
evaluate_random_0.append(model_original.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
for model in models_lsa:
evaluate_lsa_0.append(model.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
for model in models_dsa:
evaluate_dsa_0.append(model.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
for model in models_random:
evaluate_random_0.append(model.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
for model in models_nc:
evaluate_nc_0.append(model.evaluate(x_adversary_test_fgsm,y_adversary_test_fgsm))
print(len(evaluate_lsa_0))
print(len(evaluate_dsa_0))
print(len(evaluate_random_0))
print(len(evaluate_nc_0))
evaluate_lsa_5k_1 = []
evaluate_dsa_5k_1 = []
evaluate_nc_5k_1 = []
evaluate_random_5k_1 = []
evaluate_lsa_5k_1.append(model_lsa_5000.evaluate(x_test,y_test))
evaluate_dsa_5k_1.append(model_dsa_5000.evaluate(x_test,y_test))
evaluate_nc_5k_1.append(model_random_5000.evaluate(x_test,y_test))
evaluate_random_5k_1.append(model_nc_5000.evaluate(x_test,y_test))
# Metrics using original test
evaluate_lsa_1 = []
evaluate_dsa_1 = []
evaluate_nc_1 = []
evaluate_random_1 = []
evaluate_lsa_1.append(model_original.evaluate(x_test,y_test))
evaluate_dsa_1.append(model_original.evaluate(x_test,y_test))
evaluate_nc_1.append(model_original.evaluate(x_test,y_test))
evaluate_random_1.append(model_original.evaluate(x_test,y_test))
print("lsa---")
for model in models_lsa:
evaluate_lsa_1.append(model.evaluate(x_test,y_test))
print("dsa---")
for model in models_dsa:
evaluate_dsa_1.append(model.evaluate(x_test,y_test))
print("random---")
for model in models_random:
evaluate_random_1.append(model.evaluate(x_test,y_test))
print("nc---")
for model in models_nc:
evaluate_nc_1.append(model.evaluate(x_test,y_test))
print(len(evaluate_lsa_1))
print(len(evaluate_dsa_1))
print(len(evaluate_random_1))
print(len(evaluate_nc_1))
import pandas as pd
df_evaluate_lsa_5k_0 = pd.DataFrame(np.array(evaluate_lsa_5k_0),columns=["loss","accuracy","precision","recall"])
df_evaluate_lsa_5k_1 = pd.DataFrame(np.array(evaluate_lsa_5k_1),columns=["loss","accuracy","precision","recall"])
df_evaluate_dsa_5k_0 = pd.DataFrame(np.array(evaluate_dsa_5k_0),columns=["loss","accuracy","precision","recall"])
df_evaluate_dsa_5k_1 = pd.DataFrame(np.array(evaluate_dsa_5k_1),columns=["loss","accuracy","precision","recall"])
df_evaluate_random_5k_0 = pd.DataFrame(np.array(evaluate_random_5k_0),columns=["loss","accuracy","precision","recall"])
df_evaluate_random_5k_1 = pd.DataFrame(np.array(evaluate_random_5k_1),columns=["loss","accuracy","precision","recall"])
df_evaluate_nc_5k_0 = pd.DataFrame(np.array(evaluate_nc_5k_0),columns=["loss","accuracy","precision","recall"])
df_evaluate_nc_5k_1 = pd.DataFrame(np.array(evaluate_nc_5k_1),columns=["loss","accuracy","precision","recall"])
import pandas as pd
df_evaluate_lsa_0 = pd.DataFrame(np.array(evaluate_lsa_0),columns=["loss","accuracy","precision","recall"])
df_evaluate_lsa_1 = pd.DataFrame(np.array(evaluate_lsa_1),columns=["loss","accuracy","precision","recall"])
df_evaluate_dsa_0 = pd.DataFrame(np.array(evaluate_dsa_0),columns=["loss","accuracy","precision","recall"])
df_evaluate_dsa_1 = pd.DataFrame(np.array(evaluate_dsa_1),columns=["loss","accuracy","precision","recall"])
df_evaluate_random_0 = pd.DataFrame(np.array(evaluate_random_0),columns=["loss","accuracy","precision","recall"])
df_evaluate_random_1 = pd.DataFrame(np.array(evaluate_random_1),columns=["loss","accuracy","precision","recall"])
df_evaluate_nc_0 = pd.DataFrame(np.array(evaluate_nc_0),columns=["loss","accuracy","precision","recall"])
df_evaluate_nc_1 = pd.DataFrame(np.array(evaluate_nc_1),columns=["loss","accuracy","precision","recall"])
# Original test set + adversarial set
metric ="accuracy"
accuracy_c3_lsa_5k_3 = (np.array(df_evaluate_lsa_5k_0[metric])+np.array(df_evaluate_lsa_5k_1[metric]))/2
accuracy_c3_dsa_5k_3 = (np.array(df_evaluate_dsa_5k_0[metric])+np.array(df_evaluate_dsa_5k_1[metric]))/2
accuracy_c3_nc_5k_3 = (np.array(df_evaluate_nc_5k_0[metric])+np.array(df_evaluate_nc_5k_1[metric]))/2
accuracy_c3_random_5k_3 = (np.array(df_evaluate_random_5k_0[metric])+np.array(df_evaluate_random_5k_1[metric]))/2
# Original test set + adversarial set
metric ="accuracy"
accuracy_c3_lsa_3 = (np.array(df_evaluate_lsa_0[metric])+np.array(df_evaluate_lsa_1[metric]))/2
accuracy_c3_dsa_3 = (np.array(df_evaluate_dsa_0[metric])+np.array(df_evaluate_dsa_1[metric]))/2
accuracy_c3_nc_3 = (np.array(df_evaluate_nc_0[metric])+np.array(df_evaluate_nc_1[metric]))/2
accuracy_c3_random_3 = (np.array(df_evaluate_random_0[metric])+np.array(df_evaluate_random_1[metric]))/2
```
## Charts
```
n_inputs = [700*i for i in range(20)]
n_inputs.append(len(x_train_and_adversary))
cd "C:/Users/fjdur/Desktop/intel_graphs/e2_graphs_dec/"
linestyles = ['solid','dotted','dashed','dashdot']
colors =['k','k','k','k']
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
#metric = "accuracy" # accuracy loss
my_metrics =["accuracy","loss","precision","recall"]
for metric in my_metrics:
plt.clf()
plt.plot(n_inputs,df_evaluate_lsa_0[metric],colors[0],linestyle=linestyles[0])
plt.plot(n_inputs,df_evaluate_dsa_0[metric],colors[1],linestyle=linestyles[1])
plt.plot(n_inputs,df_evaluate_random_0[metric],colors[2],linestyle=linestyles[2])
plt.plot(n_inputs,df_evaluate_nc_0[metric],colors[3],linestyle=linestyles[3])
legend_elements = [Line2D([0], [0], color='k', label='LSA',ls = linestyles[0]),
Line2D([0], [0], color='k', label='DSA',ls = linestyles[1]),
Line2D([0], [0], color='k', label='Random',ls = linestyles[2]),
Line2D([0], [0], color='k', label='NC',ls = linestyles[3])]
plt.legend(handles=legend_elements)#
plt.title(metric + " with test set of adversarial examples FGSM")
plt.xlim([0, 15000])
#plt.ylim([0, 1])
plt.xlabel('number of inputs')
plt.ylabel(metric)
plt.savefig("intel_c2_"+metric + "_0.svg")
plt.show()
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
my_metrics =["accuracy","loss","precision","recall"]
for metric in my_metrics:
#metric = "accuracy" # accuracy loss
plt.clf()
plt.plot(n_inputs,df_evaluate_lsa_1[metric],colors[0],linestyle=linestyles[0])
plt.plot(n_inputs,df_evaluate_dsa_1[metric],colors[1],linestyle=linestyles[1])
plt.plot(n_inputs,df_evaluate_random_1[metric],colors[2],linestyle=linestyles[2])
plt.plot(n_inputs,df_evaluate_nc_1[metric],colors[3],linestyle=linestyles[3])
legend_elements = [Line2D([0], [0], color='k', label='LSA',ls = linestyles[0]),
Line2D([0], [0], color='k', label='DSA',ls = linestyles[1]),
Line2D([0], [0], color='k', label='Random',ls = linestyles[2]),
Line2D([0], [0], color='k', label='NC',ls = linestyles[3])]
plt.legend(handles=legend_elements)#
plt.title(metric + " with original set")
plt.xlim([0, 15000])
#plt.ylim([0, 1])
plt.xlabel('number of inputs')
plt.ylabel(metric)
plt.savefig("intel_c2_"+metric + "_1.svg")
plt.show()
#adversarial jsma test set
#configuration 3
"""
6) Incremental guided retraining starting from the original model using only the new adversarial inputs.
Incremental training, starting with the previous trained model. Using at each iteration a subset of the new inputs.
"""
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
plt.plot(n_inputs,accuracy_c3_lsa_3,colors[0],linestyle=linestyles[0])
plt.plot(n_inputs,accuracy_c3_dsa_3,colors[1],linestyle=linestyles[1])
plt.plot(n_inputs,accuracy_c3_random_3,colors[2],linestyle=linestyles[2])
plt.plot(n_inputs,accuracy_c3_nc_3,colors[3],linestyle=linestyles[3])
legend_elements = [Line2D([0], [0], color='k', label='LSA',ls = linestyles[0]),
Line2D([0], [0], color='k', label='DSA',ls = linestyles[1]),
Line2D([0], [0], color='k', label='Random',ls = linestyles[2]),
Line2D([0], [0], color='k', label='NC',ls = linestyles[3])]
plt.legend(handles=legend_elements)#
plt.title("accuracy with both sets")
print(n_inputs[np.argmax(accuracy_c3_lsa_3)],accuracy_c3_lsa_3.max())
print(n_inputs[np.argmax(accuracy_c3_dsa_3)],accuracy_c3_dsa_3.max())
print(n_inputs[np.argmax(accuracy_c3_random_3)],accuracy_c3_random_3.max())
print(n_inputs[np.argmax(accuracy_c3_nc_3)],accuracy_c3_nc_3.max())
plt.plot(n_inputs[np.argmax(accuracy_c3_lsa_3)],accuracy_c3_lsa_3.max(),'-kD')
plt.plot(n_inputs[np.argmax(accuracy_c3_dsa_3)],accuracy_c3_dsa_3.max(),'-ko')
plt.plot(n_inputs[np.argmax(accuracy_c3_random_3)],accuracy_c3_random_3.max(),'-kv')
plt.plot(n_inputs[np.argmax(accuracy_c3_nc_3)],accuracy_c3_nc_3.max(),'-kp')
plt.xlabel('number of inputs')
plt.ylabel('accuracy')
plt.xlim([0, 15000])
#plt.ylim([0, 1])
plt.savefig("intel_c2_"+"accuracy" + "_both.svg")
plt.show()
print(accuracy_c3_lsa_5k_3)
print(accuracy_c3_dsa_5k_3)
print(accuracy_c3_random_5k_3)
print(accuracy_c3_nc_5k_3)
```
## Saving models
```
new_model_lsa_dir = "D:/models/intel_models/C2/intel_model_c2_sep_lsa_e2"
i=0
for model in models_lsa:
model.save(new_model_lsa_dir+"_"+str(i))
i+=1
new_model_dsa_dir = "D:/models/intel_models/C2/intel_model_c2_sep_dsa_e2"
i=0
for model in models_dsa:
model.save(new_model_dsa_dir+"_"+str(i))
i+=1
new_model_random_dir = "D:/models/intel_models/C2/intel_model_c2_sep_random_e2"
i=0
for model in models_random:
model.save(new_model_random_dir+"_"+str(i))
i+=1
new_model_nc_dir = "D:/models/intel_models/C2/intel_model_c2_sep_nc_e2"
i=0
for model in models_nc:
model.save(new_model_nc_dir+"_"+str(i))
i+=1
```
| github_jupyter |
<img style="float: right;" src="./images/DataReading.png" width="120"/>
# Reading Data
* Python has a large number of different ways to read data from external files.
* Python supports almost any type of file you can think of, from simple text files to complex binary formats.
* In this class we are going to mainly use the package **`pandas`** to load external files into `DataFrames`.
* Most of our datafiles will be `csv` files (comma separated values)
```
import pandas as pd
import numpy as np
```
##### Let us read-in the file: `./Data/Planets.csv`
```
Name,a,
Mercury,0.3871,0.2056
Earth,0.9991,0.0166
Jupiter,5.2016,0.0490
Neptune,29.9769,0.0088
```
```
planet_table = pd.read_csv('./Data/Planets.csv')
planet_table
```
## Renaming columns
```
planet_table.rename(columns={'Unnamed: 2': 'ecc'}, inplace=True)
planet_table
planet_table['ecc']
```
## Adding a column - `insert`
`.insert(loc, column, value, allow_duplicates = False)`
#### perihelion distance [AU] = `semi_major axis * ( 1 - eccentricity )`
```
def find_perihelion(semi_major, eccentricity):
result = semi_major * (1.0 - eccentricity)
return result
```
#### Use `DataFrame` columns as arguments to the `find_perihelion` function
```
my_perihelion = find_perihelion(planet_table['a'], planet_table['ecc'])
my_perihelion
# Add column in position 1 (2nd column)
planet_table.insert(1, 'Perihelion', my_perihelion, allow_duplicates = False)
planet_table
```
## Removing a column - `drop`
```
planet_table.drop(columns='Perihelion', inplace = True)
planet_table
```
## Adding a column (quick) - always to the end of the table
```
planet_table['Perihelion'] = my_perihelion
planet_table
```
## Rearranging columns
```
planet_table.columns
my_new_order = ['a', 'Perihelion', 'Name', 'ecc']
planet_table = planet_table[my_new_order]
planet_table
```
## Adding a row `.append`
* The new row has to be a `dictionary` or another `DataFrame`
* Almost always need to use: `ignore_index=True`
```
my_new_row = {'Name': 'Venus',
'a': 0.723,
'ecc': 0.007}
my_new_row
planet_table.append(my_new_row, ignore_index=True)
planet_table
planet_table = planet_table.append(my_new_row, ignore_index=True)
planet_table
```
#### `NaN` = Not_A_Number, python's null value
----
<img style="float: right;" src="./images/Lore.jpg" width="200"/>
# Reading (bad) Data
## Different Delimiters
Some people just want to watch the world burn, so they create datasets where the columns are separted by something other than a comma.
#### Bad - Using another delimiter like `:`
##### `./Data/Planets_Ver2.txt`
```
Name:a:
Mercury:0.3871:0.2056
Earth:0.9991:0.0166
Jupiter:5.2016:0.0490
Neptune:29.9769:0.0088
```
```
planet_table_2 = pd.read_csv('./Data/Planets_Ver2.txt', delimiter = ":")
planet_table_2
```
#### Worse - Using whitespace as a delimiter
##### `./Data/Planets_Ver3.txt`
```
Name a
Mercury 0.3871 0.2056
Earth 0.9991 0.0166
Jupiter 5.2016 0.0490
Neptune 29.9769 0.0088
```
```
planet_table_3 = pd.read_csv('./Data/Planets_Ver3.txt', delimiter = " ")
planet_table_3
```
#### WORST! - Using inconsistent whitespace as a delimiter!
##### `./Data/Planets_Ver4.txt`
```
Name a
Mercury 0.3871 0.2056
Earth 0.9991 0.0166
Jupiter 5.2016 0.0490
Neptune 29.9769 0.0088
```
```
planet_table_4 = pd.read_csv('./Data/Planets_Ver4.txt', delimiter = " ", skipinitialspace=True)
planet_table_4
```
---
<img style="float: right;" src="./images/MessyData.jpg" width="230"/>
# Messy Data
* `pandas` is a good choice when working with messy data files.
* In the "real world" all data is messy.
##### Let us read-in the file: `./Data/Mess.csv`
```
#######################################################
#
# Col 1 - Name
# Col 2 - Size (km)
#
#######################################################
"Sample 1",10
"",23
,
"Another Sample",
```
### This is not going to end well ... (errors galore!)
```
messy_table = pd.read_csv('./Data/Mess.csv')
```
### Tell `pandas` about the comments:
```
messy_table = pd.read_csv('./Data/Mess.csv', comment = "#")
messy_table
```
## Not quite correct ...
### Turn off the header
```
messy_table = pd.read_csv('./Data/Mess.csv', comment = "#", header= None)
messy_table
```
### Add the column names
```
my_column_name = ['Name', 'Size']
messy_table = pd.read_csv('./Data/Mess.csv', comment = "#", header= None, names = my_column_name)
messy_table
```
### Deal with the missing data with `.fillna()`
```
messy_table['Name'].fillna("unknown", inplace=True)
messy_table['Size'].fillna(999.0, inplace=True)
messy_table
```
----
# Fixed-Width Data Tables
* These types of data tables are **VERY** common in astronomy
* The columns have a fixed-widths
* Whitespace is used to seperate columns **AND** used within columns
#### Trying to read this in with `pd.read_csv()` is a mess!
```
standard_table = pd.read_csv('./Data/StdStars.dat', header= None, delimiter = " ", skipinitialspace=True)
standard_table
```
## `pd.read_fwf()` - fixed-width-format
* You can set the beginning to end of a column: `colspecs`
* Or you can set the width of the columns: `widths`
`colspecs` uses the same format as a slice
* 0-based indexing
* First number is the first element you want
* Second number is the first element you DON'T want
```
my_colspecs = [(0,12), (12,14), (15,17), (18,20)]
standard_table = pd.read_fwf('./Data/StdStars.dat', colspecs = my_colspecs)
standard_table
my_column_name = ['Star', 'RAh', 'RAm', 'RAs']
standard_table = pd.read_fwf('./Data/StdStars.dat', colspecs = my_colspecs, header= None, names = my_column_name)
standard_table
```
----
# Real World Example

[Landolt Paper SIMBAD page](http://simbad.u-strasbg.fr/simbad/sim-basic?Ident=1992AJ....104..340L)
[Mirror](http://simbad.cfa.harvard.edu/simbad/sim-basic?Ident=1992AJ....104..340L)
#### Set the column names
```
my_column_name = ['Star',
'RAh', 'RAm','RAs',
'DEd', 'DEm','DEs',
'Vmag', 'B-V', 'U-B', 'V-R', 'R-I', 'V-I',
'o_Vmag', 'Nd',
'e_Vmag', 'e_B-V', 'e_U-B', 'e_V-R', 'e_R-I', 'e_V-I']
```
#### Set the column widths
* include leading whitespace
* pandas will trim off surrounding whitespace
```
my_column_width = [12, 2, 3, 3, 4, 3, 3, 8, 7, 7, 7, 7, 7, 5, 4, 8, 7, 7, 7, 7, 7]
```
#### Set the URL for the data
```
my_url = 'https://cdsarc.unistra.fr/ftp/II/183A/table2.dat'
#my_url = 'Data/table2.dat'
standard_table = pd.read_fwf(my_url, header=None, widths=my_column_width, names = my_column_name)
standard_table.head(10)
```
----
<img style="float: right;" src="./images/LotsData.jpg" width="230"/>
# Lots of Data
* `pandas` will cutoff the display of really long tables
* You can change this with:
* `pd.set_option('display.max_rows', # of rows)`
* `pd.set_option('display.max_columns', # of columns)`
```
standard_table.info()
pd.set_option('display.max_columns', 21)
standard_table.head(10)
pd.set_option('display.max_rows', 526)
standard_table
```
----
# Bonus Content: Reading HTML tables (Wikipedia)
* `pandas` can (sort-of) easily import HTML tables - `read_html()`
* This is great for pulling in data from Wikipedia
* The results are often far from perfect
# [List of impact craters in North America](https://en.wikipedia.org/wiki/List_of_impact_craters_in_North_America)
* There are 4 tables on this page
* Plus a bunch of other table-ish-looking content
* Let us see how this works out ....
```
crater_wiki = 'https://en.wikipedia.org/wiki/List_of_impact_craters_in_North_America'
crater_table = pd.read_html(crater_wiki)
```
### What did we get?
```
type(crater_table)
```
### A list (array), close but not a `pandas` DataFrame
```
len(crater_table)
```
### And 7 of them. OK, what do we have at index 0?
```
crater_table[0]
```
### Garbage
```
type(crater_table[0])
```
### ... But is it a DataFrame!
### And at index 1?
```
crater_table[1]
```
### Sweet! A DataFrame of the first table (Impact Craters in Canada)
### Index 2 is the Mexican table
```
crater_table[2]
```
### Index 3 is the US Table
```
crater_table[3]
```
### Index 4 is the Unconfirmed impact craters
```
crater_table[4]
```
### The last two [5 and 6] are garbage
### The DataFrames are not perfect, and will need some cleaning, but is great starting point
| github_jupyter |
```
from matplotlib_venn import venn2, venn3
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
isaacs = pd.read_json('isaacs-reach.json', typ='series')
setA = set(isaacs)
mathias = pd.read_json('mathias-reach.json', typ='series')
setB = set(mathias)
packages = pd.read_json('latestPackages.json', typ='series')
setC = set(packages)
# print(setA,setB,setC)
plt.figure(figsize=(8,6), dpi=100)
venn3([setA, setB, setC], ('isaacs', 'mathias', 'All packages'))
plt.savefig("top2_reach_maintainer.png")
import matplotlib.ticker as mtick
import pandas as pd
import matplotlib.pyplot as plt
ranking = pd.read_json('optimal_ranking_2018_all.json', typ='series')
# for i, x in to100Percent.iteritems():
# if i > 5:
# amountTop5 = x
# break
# print(amountTop5, amountTop5 / 667224)
# max = 0
# index = 0
# for i, x in to100Percent.iteritems():
# if x > max:
# max = x
# index = i
# print('full reach at maintainer count {} with {} packages'.format(index, max))
plt.rcParams.update({'font.size': 14})
print(len(ranking["IntersectionCounts"]))
plt.figure(figsize=(10,6), dpi=100)
plt.plot(ranking["IntersectionCounts"])
# plt.axvline(index, color='r', linestyle='--')
plt.ylim(0,500000)
plt.xlabel('Number of maintainers ordered by optimal reach to reach all packages with a dependency')
plt.ylabel('Reached packages')
# plt.annotate("Full reach", (index, max), xytext=(+10, +30), textcoords='offset points', fontsize=10,
# arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.gca().set_yticklabels(['{:.0f}%'.format(x/667224*100) for x in plt.gca().get_yticks()])
plt.savefig("complete_reach_maintainer.png")
import matplotlib.ticker as mtick
import pandas as pd
import matplotlib.pyplot as plt
ranking = pd.read_json('optimalRanking_2018_top100.json', typ='series')
plt.figure(figsize=(8,6), dpi=100)
plt.plot(ranking["IntersectionCounts"], '.')
plt.ylim(0,400000)
plt.xlabel('Number of maintainers ordered by optimal reach')
plt.ylabel('Reached packages')
plt.gca().set_yticklabels(['{:.0f}%'.format(x/667224*100) for x in plt.gca().get_yticks()])
plt.savefig("top100_reach_maintainer.png")
import matplotlib.pyplot as plt
x = [2012,2013,2014,2015,2016,2017,2018]
packageCount = [5165, 18574, 50393, 112373, 218744, 390190, 605079]
reachCount = [2261, 9462, 27216, 63555, 124638, 210433, 322578]
percentage = []
for i in range(7):
percentage.append(reachCount[i] / packageCount[i])
plt.figure(figsize=(8,6), dpi=100)
plt.plot(x, percentage, '--bo')
plt.xlabel('Year')
plt.ylabel('Reach of Top 20 Maintainers (% of All Packages)')
plt.rcParams.update({'font.size': 14})
plt.gca().set_yticklabels(['{:.2f}%'.format(x*100) for x in plt.gca().get_yticks()])
plt.savefig("top20_maintainer_reach_evolution.png")
```
| github_jupyter |
```
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
import random
import backwardcompatibilityml.loss as bcloss
import backwardcompatibilityml.scores as scores
# Initialize random seed
random.seed(123)
torch.manual_seed(456)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
%matplotlib inline
n_epochs = 3
batch_size_train = 64
batch_size_test = 1000
learning_rate = 0.01
momentum = 0.5
log_interval = 10
torch.backends.cudnn.enabled = False
train_loader = list(torch.utils.data.DataLoader(
torchvision.datasets.MNIST('datasets/', train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])),
batch_size=batch_size_train, shuffle=True))
test_loader = list(torch.utils.data.DataLoader(
torchvision.datasets.MNIST('datasets/', train=False, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])),
batch_size=batch_size_test, shuffle=True))
train_loader_a = train_loader[:int(len(train_loader)/2)]
train_loader_b = train_loader[int(len(train_loader)/2):]
fig = plt.figure()
for i in range(6):
plt.subplot(2,3,i+1)
plt.tight_layout()
plt.imshow(train_loader_a[0][0][i][0], cmap='gray', interpolation='none')
plt.title("Ground Truth: {}".format(train_loader_a[0][1][i]))
plt.xticks([])
plt.yticks([])
fig
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return x, F.softmax(x, dim=1), F.log_softmax(x, dim=1)
network = Net()
optimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum)
train_losses = []
train_counter = []
test_losses = []
test_counter = [i*len(train_loader_a)*batch_size_train for i in range(n_epochs + 1)]
def train(epoch):
network.train()
for batch_idx, (data, target) in enumerate(train_loader_a):
optimizer.zero_grad()
_, _, output = network(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader_a)*batch_size_train,
100. * batch_idx / len(train_loader_a), loss.item()))
train_losses.append(loss.item())
train_counter.append(
(batch_idx*64) + ((epoch-1)*len(train_loader_a)*batch_size_train))
def test():
network.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
_, _, output = network(data)
test_loss += F.nll_loss(output, target, reduction="sum").item()
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(target.data.view_as(pred)).sum()
test_loss /= len(train_loader_a)*batch_size_train
test_losses.append(test_loss)
print('\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(train_loader_a)*batch_size_train,
100. * correct / (len(train_loader_a)*batch_size_train)))
test()
for epoch in range(1, n_epochs + 1):
train(epoch)
test()
fig = plt.figure()
plt.plot(train_counter, train_losses, color='blue')
plt.scatter(test_counter, test_losses, color='red')
plt.legend(['Train Loss', 'Test Loss'], loc='upper right')
plt.xlabel('number of training examples seen')
plt.ylabel('negative log likelihood loss')
fig
with torch.no_grad():
_, _, output = network(test_loader[0][0])
fig = plt.figure()
for i in range(6):
plt.subplot(2,3,i+1)
plt.tight_layout()
plt.imshow(test_loader[0][0][i][0], cmap='gray', interpolation='none')
plt.title("Prediction: {}".format(
output.data.max(1, keepdim=True)[1][i].item()))
plt.xticks([])
plt.yticks([])
fig
import copy
import importlib
importlib.reload(bcloss)
h1 = copy.deepcopy(network)
h2 = copy.deepcopy(network)
h1.eval()
new_optimizer = optim.SGD(h2.parameters(), lr=learning_rate, momentum=momentum)
lambda_c = 1.0
si_loss = bcloss.StrictImitationCrossEntropyLoss(h1, h2, lambda_c)
update_train_losses = []
update_train_counter = []
update_test_losses = []
update_test_counter = [i*len(train_loader_b)*batch_size_train for i in range(n_epochs + 1)]
def train_update(epoch):
for batch_idx, (data, target) in enumerate(train_loader_b):
new_optimizer.zero_grad()
loss = si_loss(data, target)
loss.backward()
new_optimizer.step()
if batch_idx % log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader_b)*batch_size_train,
100. * batch_idx / len(train_loader_b), loss.item()))
update_train_losses.append(loss.item())
update_train_counter.append(
(batch_idx*64) + ((epoch-1)*len(train_loader_b)*batch_size_train))
def test_update():
h2.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
_, _, output = h2(data)
test_loss += F.nll_loss(output, target, reduction="sum").item()
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(target.data.view_as(pred)).sum()
test_loss /= len(train_loader_b)*batch_size_train
update_test_losses.append(test_loss)
print('\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(train_loader_b)*batch_size_train,
100. * correct / (len(train_loader_b)*batch_size_train)))
test_update()
for epoch in range(1, n_epochs + 1):
train_update(epoch)
test_update()
fig = plt.figure()
plt.plot(update_train_counter, update_train_losses, color='blue')
plt.scatter(update_test_counter, update_test_losses, color='red')
plt.legend(['Train Loss', 'Test Loss'], loc='upper right')
plt.xlabel('number of training examples seen')
plt.ylabel('negative log likelihood loss')
fig
h2.eval()
h1.eval()
test_index = 5
with torch.no_grad():
_, _, h1_output = h1(test_loader[test_index][0])
_, _, h2_output = h2(test_loader[test_index][0])
h1_labels = h1_output.data.max(1)[1]
h2_labels = h2_output.data.max(1)[1]
expected_labels = test_loader[test_index][1]
fig = plt.figure()
for i in range(6):
plt.subplot(2,3,i+1)
plt.tight_layout()
plt.imshow(test_loader[test_index][0][i][0], cmap='gray', interpolation='none')
plt.title("Prediction: {}".format(
h2_labels[i].item()))
plt.xticks([])
plt.yticks([])
fig
trust_compatibility = scores.trust_compatibility_score(h1_labels, h2_labels, expected_labels)
error_compatibility = scores.error_compatibility_score(h1_labels, h2_labels, expected_labels)
print(f"Error Compatibility Score: {error_compatibility}")
print(f"Trust Compatibility Score: {trust_compatibility}")
```
| github_jupyter |
# 一等函数
函数是一等对象。
## 一等对象
一等对象:
- 在运行时创建
- 能赋值给变量或数据结构中的元素
- 能作为参数传给函数
- 能作为函数的返回结果
```
def factorial(n):
'''return n!'''
return 1 if n < 2 else n * factorial(n-1)
# 将函数看作是对象传入方法中:
list(map(factorial, range(11)))
dir(factorial)
```
## 可调用对象 Callable Object
### 一共7种:
- 用户定义的函数 : def或lambda
- 内置函数
- 内置方法
- 方法:在类的定义体内定义的函数
- 类:\_\_new\_\_:创建一个实例;\_\_init\_\_初始化实例。\_\_call\_\_实例可以作为函数调用
- 类的实例:\_\_call\_\_实例可以作为函数调用
- 生成器函数: yield的函数或方法,返回生成器对象(14章)
```
# callable
import random
class BingoCage:
def __init__(self, items):
self._items = list(items)
random.shuffle(self._items)
def pick(self):
try:
return self._items.pop()
except IndexError:
raise LookupError('pick from an empty BingCage')
def __call__(self):
'''
The class is callable only on defined the __call__ function
'''
return self.pick()
bingo = BingoCage(range(3))
bingo.pick()
bingo()
callable(bingo)
dir(BingoCage)
```
## 函数内省
```
class C:pass #自定义类
obj = C() #自定义类实例
def func():pass #自定义函数
sorted( set(dir(func)) - set(dir(obj))) #求差集
```
### 函数专有的属性
| 名称 | 类型 | 说明 |
|:--------------------|:----|:----|
| \_\_annotations\_\_ | dict |参数和返回值的注解 |
|\_\_call\_\_ |method-wrapper|实现()运算符;即可调用对象协议|
|\_\_closure\_\_ |tuple|函数闭包,即自由变量的绑定(通常是None)|
|\_\_code\_\_ |code|编译成字节码的函数元数据和函数定义体
|\_\_defaults\_\_ |tuple|形式参数的默认值
|\_\_get\_\_ |method-wrapper|实现只读描述符协议(20章)
|\_\_globals\_\_ |dict|函数所在模块中的全局变量
|\_\_kwdefaults\_\_ |dict|仅限关键字形式参数的默认值
|\_\_name\_\_ |str|函数名称
|\_\_qualname\_\_ |str|函数的限定名称
## 函数参数
- 仅限关键字参数
- 使用\*存无变量名的一个或以上个参数到元组中
- 使用\**存有变量名的一个或以上个参数到字典中
```
def tag(name, *content, cls=None, **attrs):
"""生成一个或多个HTML标签"""
if cls is not None:
attrs['class'] = cls
if attrs:
attr_str = ''.join(' %s="%s"'%(attr, value)
for attr, value
in sorted(attrs.items()))
else:
attr_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>'%(name, attr_str, c, name)
for c in content)
else:
return '<%s%s />'%(name, attr_str)
# 传入单个定位参数,生成一个指定名称的空标签。
# name = 'br'
tag('br')
# 第一个参数后面的任意个参数会被 *content 捕获,存入一个元组。
# name = 'p'
# content = ('hello')
tag('p', 'hello')
# name = 'p'
# content = ('hello', 'world')
tag('p', 'hello', 'world')
# tag 函数签名中没有明确指定名称的关键字参数会被 **attrs 捕 获,存入一个字典。
# name = 'p'
# content = ('hello')
# attrs['id'] = 33
tag('p', 'hello', id=33)
# cls 参数只能作为关键字参数传入。
# name = 'p'
# content = ('hello', 'world')
# cls = 'sidebar'
print(tag('p', 'hello', 'world', cls='sidebar'))
# 调用 tag 函数时,即便第一个定位参数也能作为关键字参数传入。
# name = 'img'
# attrs['content'] = 'testing'
tag(content='testing', name="img")
# 在 my_tag 前面加上 **,字典中的所有元素作为单个参数传入,
# 同名键会绑定到对应的具名参数上,余下的则被 **attrs 捕获。
# name = 'img'
# attrs['title'] = 'Sunset Buolevard'
# attrs['src'] = 'sunset.jpg'
# cls = 'framed'
my_tag = {'name':'img', 'title':'Sunset Buolevard',
'src':'sunset.jpg', 'cls':'framed'}
tag(**my_tag)
```
定义函数 时若想指定仅限关键字参数(如上面参数中的 *cls*),要把它们放到前面有 \* 的参数后面。如果不想支持数量不定的定位参数,但是想支持仅限关键字参数,在签名中 放一个 \*,如下所示:
```
def f(a, *, b):
return a,b
f(1, b=2) # b参数必须指定设置了
```
# 获取关于参数的信息
```
def clip(text, max_len = 80):
"""
在max_len前面或后面的第一个空格处截断文本
"""
end = None
if len(text) > max_len:
space_before = text.rfind(' ', 0, max_len)
if space_before >= 0:
end = space_before
else:
space_after = text.rfind(' ', max_len)
if space_after >= 0:
end = space_after
if end == None:
end = len(text)
return text[:end].rstrip()
clip('I will learn python by myself every night.', 18)
'''
函数对象:
__defaults__: 定位参数和关键字参数的默认值元组
__kwdefaults__:仅限关键字参数默认值元组
参数的默认值只能通过它们在 __defaults__ 元组中的位置确定,
因此要从后向前扫描才能把参数和默认值对应起来。
在这个示例中 clip 函数有两个参数,text 和 max_len,
其中一个有默认值,即 80,因此它必然属于最后一个参数,即max_len。这有违常理。
'''
clip.__defaults__
"""
__code__.varname:函数参数名称,但也包含了局部变量名
"""
clip.__code__.co_varnames
"""
__code__.co_argcount:结合上面的变量,可以获得参数变量
需要注意,这里返回的数量是不包括前缀*或**参数的。
"""
clip.__code__.co_argcount
```
## 使用inspect模块提取函数签名
```
from inspect import signature
sig = signature(clip)
sig
for name, param in sig.parameters.items():
print (param.kind, ":", name, "=", param.default)
```
如果没有默认值,返回的是inspect.\_empty,因为None本身也是一个值。
| kind | meaning |
| :--- | ------: |
|POSITIONAL_OR_KEYWORD | 可以通过定位参数和关键字参数传入的形参(多数) |
|VAR_POSITIONAL| 定位参数元组 |
|VAR_KEYWORD| 关键字参数字典 |
|KEYWORD_ONLY| 仅限关键字参数(python3新增) |
|POSITIONAL_ONLY| 仅限定位参数,python声明函数的句法不支持 |
# 函数注解
```
"""
没有设置函数注解时,返回一个空字典
"""
clip.__annotations__
def clip_ann(text:str, max_len:'int > 0' = 80) -> str:
"""
在max_len前面或后面的第一个空格处截断文本
"""
end = None
if len(text) > max_len:
space_before = text.rfind(' ', 0, max_len)
if space_before >= 0:
end = space_before
else:
space_after = text.rfind(' ', max_len)
if space_after >= 0:
end = space_after
if end == None:
end = len(text)
return text[:end].rstrip()
clip_ann.__annotations__
```
Python 对注解所做的唯一的事情是,把它们存储在函数的
__annotations__ 属性里。仅此而已,Python 不做检查、不做强制、
不做验证,什么操作都不做。换句话说,注解对 Python 解释器没有任何 意义。注解只是元数据,可以供 IDE、框架和装饰器等工具使用。
# 函数式编程
涉及到两个包:
- operator
- functools
## operator
### 使用mul替代* (相乘)运算符
```
# 如何将运算符当作函数使用
# 传统做法:
from functools import reduce
def fact(n):
return reduce(lambda a,b: a*b, range(1,n+1))
fact(5)
# 如果使用operator库,就可以避免使用匿名函数
from functools import reduce
from operator import mul
def fact_op(n):
return reduce(mul, range(1,n+1))
fact_op(5)
```
### 使用itemgetter来代表[ ]序号运算符
```
metro_data = [
('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
from operator import itemgetter
for city in sorted(metro_data, key = itemgetter(1)):
print(city)
# 这里的itemgetter(1)等价于 lambda fields:fields[1]
cc_name = itemgetter(1,0) # 将返回提取的值构成的元组
for city in metro_data:
print( cc_name(city) )
```
### 使用attrgetter获取指定的属性,类似ver.attr(点运算符)
```
from collections import namedtuple
metro_data = [
('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
LatLog = namedtuple('LatLong','lat long')
Metropolis = namedtuple('Metropolis', 'name cc pop coord')
metro_areas = [Metropolis(name, cc, pop, LatLog(lat, long)) for name, cc
, pop, (lat, long) in metro_data]
# 点运算符
metro_areas[0].coord.lat
# 使用operator函数来代替操作符
from operator import attrgetter
name_lat = attrgetter('name', 'coord.lat')
# 用坐标lat排序
for city in sorted(metro_areas, key = attrgetter('coord.lat')):
print(name_lat(city))
```
### methodcaller为参数调用指定的方法
```
from operator import methodcaller
s = 'The time has come'
# 可以把upcase看作是一个创建出来的函数
upcase = methodcaller('upper')# 指定方法
upcase(s)
# 冻结参数:replace(str, ' ', '-')--->部分应用
hiphenate = methodcaller('replace', ' ','-')
hiphenate(s)
```
### operator 中的函数列表
```
import operator
funcs = [name for name in dir(operator) if not name.startswith('_')]
for func in funcs:
print(func)
```
## functools
### functools.partial 冻结参数
partial 的第一个参数是一个可调用对象,后面跟着任意个要绑定的 定位参数和关键字参数。
```
from operator import mul
from functools import partial
# 将mul(a,b)的一个参数冻结为3
triple = partial(mul, 3)
triple(7)
# 当参数只接受只有一个参数的函数时
list(map(triple,range(1,10)))
```
### functools.partial 规范化函数
```
# 在需要经常使用的一些函数时,我们可以将其作为一个冻结变量,会更加方便
import unicodedata, functools
# 提炼常用函数 unicodedata.normalize('NFC',s)
nfc = functools.partial(unicodedata.normalize, 'NFC')
s1 ='café'
s2 = 'cafe\u0301'
s1 == s2
nfc(s1) == nfc(s2)
def tag(name, *content, cls=None, **attrs):
"""生成一个或多个HTML标签"""
if cls is not None:
attrs['class'] = cls
if attrs:
attr_str = ''.join(' %s="%s"'%(attr, value)
for attr, value
in sorted(attrs.items()))
else:
attr_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>'%(name, attr_str, c, name)
for c in content)
else:
return '<%s%s />'%(name, attr_str)
# 将tag函数参数进行部分冻结,使用将更方便:
from functools import partial
picture = partial(tag, 'img', cls='pic-frame')
picture(src = 'wum.jpeg')
picture
picture.func
tag
picture.args
picture.keywords
def clip
```
| github_jupyter |
## Dependencies
```
import json, warnings, shutil, glob
from jigsaw_utility_scripts import *
from scripts_step_lr_schedulers import *
from transformers import TFXLMRobertaModel, XLMRobertaConfig
from tensorflow.keras.models import Model
from tensorflow.keras import optimizers, metrics, losses, layers
SEED = 0
seed_everything(SEED)
warnings.filterwarnings("ignore")
```
## TPU configuration
```
strategy, tpu = set_up_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync)
AUTO = tf.data.experimental.AUTOTUNE
```
# Load data
```
database_base_path = '/kaggle/input/jigsaw-data-split-roberta-192-ratio-2-clean-tail6/'
k_fold = pd.read_csv(database_base_path + '5-fold.csv')
valid_df = pd.read_csv("/kaggle/input/jigsaw-multilingual-toxic-comment-classification/validation.csv",
usecols=['comment_text', 'toxic', 'lang'])
print('Train samples: %d' % len(k_fold))
display(k_fold.head())
print('Validation samples: %d' % len(valid_df))
display(valid_df.head())
base_data_path = 'fold_1/'
fold_n = 1
# Unzip files
!tar -xf /kaggle/input/jigsaw-data-split-roberta-192-ratio-2-clean-tail6/fold_1.tar.gz
```
# Model parameters
```
base_path = '/kaggle/input/jigsaw-transformers/XLM-RoBERTa/'
config = {
"MAX_LEN": 192,
"BATCH_SIZE": 128,
"EPOCHS": 4,
"LEARNING_RATE": 1e-5,
"ES_PATIENCE": None,
"base_model_path": base_path + 'tf-xlm-roberta-large-tf_model.h5',
"config_path": base_path + 'xlm-roberta-large-config.json'
}
with open('config.json', 'w') as json_file:
json.dump(json.loads(json.dumps(config)), json_file)
```
## Learning rate schedule
```
lr_min = 1e-7
lr_start = 1e-7
lr_max = config['LEARNING_RATE']
step_size = len(k_fold[k_fold[f'fold_{fold_n}'] == 'train']) // config['BATCH_SIZE']
total_steps = config['EPOCHS'] * step_size
hold_max_steps = 0
warmup_steps = step_size * 1
decay = .9997
rng = [i for i in range(0, total_steps, config['BATCH_SIZE'])]
y = [exponential_schedule_with_warmup(tf.cast(x, tf.float32), warmup_steps, hold_max_steps,
lr_start, lr_max, lr_min, decay) for x in rng]
sns.set(style="whitegrid")
fig, ax = plt.subplots(figsize=(20, 6))
plt.plot(rng, y)
print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))
```
# Model
```
module_config = XLMRobertaConfig.from_pretrained(config['config_path'], output_hidden_states=False)
def model_fn(MAX_LEN):
input_ids = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask')
base_model = TFXLMRobertaModel.from_pretrained(config['base_model_path'], config=module_config)
last_hidden_state, _ = base_model({'input_ids': input_ids, 'attention_mask': attention_mask})
cls_token = last_hidden_state[:, 0, :]
output = layers.Dense(1, activation='sigmoid', name='output')(cls_token)
model = Model(inputs=[input_ids, attention_mask], outputs=output)
return model
```
# Train
```
# Load data
x_train = np.load(base_data_path + 'x_train.npy')
y_train = np.load(base_data_path + 'y_train_int.npy').reshape(x_train.shape[1], 1).astype(np.float32)
x_valid_ml = np.load(database_base_path + 'x_valid.npy')
y_valid_ml = np.load(database_base_path + 'y_valid.npy').reshape(x_valid_ml.shape[1], 1).astype(np.float32)
#################### ADD TAIL ####################
x_train_tail = np.load(base_data_path + 'x_train_tail.npy')
y_train_tail = np.load(base_data_path + 'y_train_int_tail.npy').reshape(x_train_tail.shape[1], 1).astype(np.float32)
x_train = np.hstack([x_train, x_train_tail])
y_train = np.vstack([y_train, y_train_tail])
step_size = x_train.shape[1] // config['BATCH_SIZE']
valid_step_size = x_valid_ml.shape[1] // config['BATCH_SIZE']
# Build TF datasets
train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(x_train, y_train, config['BATCH_SIZE'], AUTO, seed=SEED))
valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(x_valid_ml, y_valid_ml, config['BATCH_SIZE'], AUTO, repeated=True, seed=SEED))
train_data_iter = iter(train_dist_ds)
valid_data_iter = iter(valid_dist_ds)
# Step functions
@tf.function
def train_step(data_iter):
def train_step_fn(x, y):
with tf.GradientTape() as tape:
probabilities = model(x, training=True)
loss = loss_fn(y, probabilities)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_auc.update_state(y, probabilities)
train_loss.update_state(loss)
for _ in tf.range(step_size):
strategy.experimental_run_v2(train_step_fn, next(data_iter))
@tf.function
def valid_step(data_iter):
def valid_step_fn(x, y):
probabilities = model(x, training=False)
loss = loss_fn(y, probabilities)
valid_auc.update_state(y, probabilities)
valid_loss.update_state(loss)
for _ in tf.range(valid_step_size):
strategy.experimental_run_v2(valid_step_fn, next(data_iter))
# Train model
with strategy.scope():
model = model_fn(config['MAX_LEN'])
optimizer = optimizers.Adam(learning_rate=lambda:
exponential_schedule_with_warmup(tf.cast(optimizer.iterations, tf.float32),
warmup_steps, hold_max_steps, lr_start,
lr_max, lr_min, decay))
loss_fn = losses.binary_crossentropy
train_auc = metrics.AUC()
valid_auc = metrics.AUC()
train_loss = metrics.Sum()
valid_loss = metrics.Sum()
metrics_dict = {'loss': train_loss, 'auc': train_auc,
'val_loss': valid_loss, 'val_auc': valid_auc}
history = custom_fit(model, metrics_dict, train_step, valid_step, train_data_iter, valid_data_iter,
step_size, valid_step_size, config['BATCH_SIZE'], config['EPOCHS'],
config['ES_PATIENCE'], save_last=False)
# model.save_weights('model.h5')
# Make predictions
x_train = np.load(base_data_path + 'x_train.npy')
x_valid = np.load(base_data_path + 'x_valid.npy')
x_valid_ml_eval = np.load(database_base_path + 'x_valid.npy')
train_preds = model.predict(get_test_dataset(x_train, config['BATCH_SIZE'], AUTO))
valid_preds = model.predict(get_test_dataset(x_valid, config['BATCH_SIZE'], AUTO))
valid_ml_preds = model.predict(get_test_dataset(x_valid_ml_eval, config['BATCH_SIZE'], AUTO))
k_fold.loc[k_fold[f'fold_{fold_n}'] == 'train', f'pred_{fold_n}'] = np.round(train_preds)
k_fold.loc[k_fold[f'fold_{fold_n}'] == 'validation', f'pred_{fold_n}'] = np.round(valid_preds)
valid_df[f'pred_{fold_n}'] = valid_ml_preds
# Fine-tune on validation set
#################### ADD TAIL ####################
x_valid_ml_tail = np.hstack([x_valid_ml, np.load(database_base_path + 'x_valid_tail.npy')])
y_valid_ml_tail = np.vstack([y_valid_ml, y_valid_ml])
valid_step_size_tail = x_valid_ml_tail.shape[1] // config['BATCH_SIZE']
# Build TF datasets
train_ml_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(x_valid_ml_tail, y_valid_ml_tail,
config['BATCH_SIZE'], AUTO, seed=SEED))
train_ml_data_iter = iter(train_ml_dist_ds)
history_ml = custom_fit(model, metrics_dict, train_step, valid_step, train_ml_data_iter, valid_data_iter,
valid_step_size_tail, valid_step_size, config['BATCH_SIZE'], 1,
config['ES_PATIENCE'], save_last=False)
# Join history
for key in history_ml.keys():
history[key] += history_ml[key]
model.save_weights('model_ml.h5')
# Make predictions
valid_ml_preds = model.predict(get_test_dataset(x_valid_ml_eval, config['BATCH_SIZE'], AUTO))
valid_df[f'pred_ml_{fold_n}'] = valid_ml_preds
### Delete data dir
shutil.rmtree(base_data_path)
```
## Model loss graph
```
plot_metrics(history)
```
# Model evaluation
```
display(evaluate_model_single_fold(k_fold, fold_n, label_col='toxic_int').style.applymap(color_map))
```
# Confusion matrix
```
train_set = k_fold[k_fold[f'fold_{fold_n}'] == 'train']
validation_set = k_fold[k_fold[f'fold_{fold_n}'] == 'validation']
plot_confusion_matrix(train_set['toxic_int'], train_set[f'pred_{fold_n}'],
validation_set['toxic_int'], validation_set[f'pred_{fold_n}'])
```
# Model evaluation by language
```
display(evaluate_model_single_fold_lang(valid_df, fold_n).style.applymap(color_map))
# ML fine-tunned preds
display(evaluate_model_single_fold_lang(valid_df, fold_n, pred_col='pred_ml').style.applymap(color_map))
```
# Visualize predictions
```
pd.set_option('max_colwidth', 120)
print('English validation set')
display(k_fold[['comment_text', 'toxic'] + [c for c in k_fold.columns if c.startswith('pred')]].head(10))
print('Multilingual validation set')
display(valid_df[['comment_text', 'toxic'] + [c for c in valid_df.columns if c.startswith('pred')]].head(10))
```
# Test set predictions
```
x_test = np.load(database_base_path + 'x_test.npy')
test_preds = model.predict(get_test_dataset(x_test, config['BATCH_SIZE'], AUTO))
submission = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv')
submission['toxic'] = test_preds
submission.to_csv('submission.csv', index=False)
display(submission.describe())
display(submission.head(10))
```
| github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.

# How to use EstimatorStep in AML Pipeline
This notebook shows how to use the EstimatorStep with Azure Machine Learning Pipelines. Estimator is a convenient object in Azure Machine Learning that wraps run configuration information to help simplify the tasks of specifying how a script is executed.
## Prerequisite:
* Understand the [architecture and terms](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture) introduced by Azure Machine Learning
* If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration notebook](https://aka.ms/pl-config) to:
* install the AML SDK
* create a workspace and its configuration file (`config.json`)
Let's get started. First let's import some Python libraries.
```
import azureml.core
# check core SDK version number
print("Azure ML SDK Version: ", azureml.core.VERSION)
```
## Initialize workspace
Initialize a [Workspace](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#workspace) object from the existing workspace you created in the Prerequisites step. `Workspace.from_config()` creates a workspace object from the details stored in `config.json`.
```
from azureml.core import Workspace
ws = Workspace.from_config()
print('Workspace name: ' + ws.name,
'Azure region: ' + ws.location,
'Subscription id: ' + ws.subscription_id,
'Resource group: ' + ws.resource_group, sep = '\n')
```
## Create or Attach existing AmlCompute
You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.
If we could not find the cluster with the given name, then we will create a new cluster here. We will create an `AmlCompute` cluster of `STANDARD_NC6` GPU VMs. This process is broken down into 3 steps:
1. create the configuration (this step is local and only takes a second)
2. create the cluster (this step will take about **20 seconds**)
3. provision the VMs to bring the cluster to the initial size (of 1 in this case). This step will take about **3-5 minutes** and is providing only sparse output in the process. Please make sure to wait until the call returns before moving to the next cell
```
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# choose a name for your cluster
cluster_name = "cpu-cluster"
try:
cpu_cluster = ComputeTarget(workspace=ws, name=cluster_name)
print('Found existing compute target')
except ComputeTargetException:
print('Creating a new compute target...')
compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_NC6', max_nodes=4)
# create the cluster
cpu_cluster = ComputeTarget.create(ws, cluster_name, compute_config)
# can poll for a minimum number of nodes and for a specific timeout.
# if no min node count is provided it uses the scale settings for the cluster
cpu_cluster.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)
# use get_status() to get a detailed status for the current cluster.
print(cpu_cluster.get_status().serialize())
```
Now that you have created the compute target, let's see what the workspace's `compute_targets` property returns. You should now see one entry named 'cpu-cluster' of type `AmlCompute`.
## Use a simple script
We have already created a simple "hello world" script. This is the script that we will submit through the estimator pattern. It prints a hello-world message, and if Azure ML SDK is installed, it will also logs an array of values ([Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number)).
## Build an Estimator object
Estimator by default will attempt to use Docker-based execution. You can also enable Docker and let estimator pick the default CPU image supplied by Azure ML for execution. You can target an AmlCompute cluster (or any other supported compute target types). You can also customize the conda environment by adding conda and/or pip packages.
> Note: The arguments to the entry script used in the Estimator object should be specified as *list* using
'estimator_entry_script_arguments' parameter when instantiating EstimatorStep. Estimator object's parameter
'script_params' accepts a dictionary. However 'estimator_entry_script_arguments' parameter expects arguments as
a list.
> Estimator object initialization involves specifying a list of DataReference objects in its 'inputs' parameter.
In Pipelines, a step can take another step's output or DataReferences as input. So when creating an EstimatorStep,
the parameters 'inputs' and 'outputs' need to be set explicitly and that will override 'inputs' parameter
specified in the Estimator object.
> The best practice is to use separate folders for scripts and its dependent files for each step and specify that folder as the `source_directory` for the step. This helps reduce the size of the snapshot created for the step (only the specific folder is snapshotted). Since changes in any files in the `source_directory` would trigger a re-upload of the snapshot, this helps keep the reuse of the step when there are no changes in the `source_directory` of the step.
```
from azureml.core import Datastore
from azureml.data.data_reference import DataReference
from azureml.pipeline.core import PipelineData
def_blob_store = Datastore(ws, "workspaceblobstore")
input_data = DataReference(
datastore=def_blob_store,
data_reference_name="input_data",
path_on_datastore="20newsgroups/20news.pkl")
output = PipelineData("output", datastore=def_blob_store)
source_directory = 'estimator_train'
from azureml.train.estimator import Estimator
est = Estimator(source_directory=source_directory,
compute_target=cpu_cluster,
entry_script='dummy_train.py',
conda_packages=['scikit-learn'])
```
## Create an EstimatorStep
[EstimatorStep](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.estimator_step.estimatorstep?view=azure-ml-py) adds a step to run Estimator in a Pipeline.
- **name:** Name of the step
- **estimator:** Estimator object
- **estimator_entry_script_arguments:**
- **runconfig_pipeline_params:** Override runconfig properties at runtime using key-value pairs each with name of the runconfig property and PipelineParameter for that property
- **inputs:** Inputs
- **outputs:** Output is list of PipelineData
- **compute_target:** Compute target to use
- **allow_reuse:** Whether the step should reuse previous results when run with the same settings/inputs. If this is false, a new run will always be generated for this step during pipeline execution.
- **version:** Optional version tag to denote a change in functionality for the step
```
from azureml.pipeline.steps import EstimatorStep
est_step = EstimatorStep(name="Estimator_Train",
estimator=est,
estimator_entry_script_arguments=["--datadir", input_data, "--output", output],
runconfig_pipeline_params=None,
inputs=[input_data],
outputs=[output],
compute_target=cpu_cluster)
```
## Build and Submit the Experiment
```
from azureml.pipeline.core import Pipeline
from azureml.core import Experiment
pipeline = Pipeline(workspace=ws, steps=[est_step])
pipeline_run = Experiment(ws, 'Estimator_sample').submit(pipeline)
```
## View Run Details
```
from azureml.widgets import RunDetails
RunDetails(pipeline_run).show()
```
| github_jupyter |
# 3rd Homework of ADM
### Group members
#### 1. Mehrdad Hassanzadeh, 1961575, hassanzadeh.1961575@studenti.uniroma1.it
#### 2. Vahid Ghanbarizadeh, 2002527, ghanbarizdehv@gmail.com
#### 3. Andrea Giordano , 1871786, giordano.1871786@studenti.uniroma1.it
# Importing useful packages
```
import requests
from bs4 import BeautifulSoup
from collections import defaultdict, Counter
import os
from pathlib import Path
import re
import multiprocessing as mp
from math import ceil
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import json
import pandas as pd
from math import log
from copy import deepcopy
from heapq import heappop, heappush
```
# 1. Data collection
We are asked to collect some information about the anime in a spcific website. Here is the link to that site. 'https://myanimelist.net/topanime.php'
Here we send a request to get the content of a specific webpage. We wanted the content of the main page of the TopAnime website.
```
TopAnime = requests.get('https://myanimelist.net/topanime.php')
```
Now we check if we have successfully received the content of the desired webpage or not.
```
TopAnime
```
As we have the code '200' as the status of the reponse, so it means that we have successfully received the desired page.
Then we take a brief look at the content of this page.
```
#TopAnime.content
```
As we can see in the output, we have the HTML code of the webpage. Now we should parse this HTML code in order to get the data we want. To do so, we will be using **BeautifulSoap** library which is designed to parse HTML codes.
```
TopAnimeSoup = BeautifulSoup(TopAnime.content, 'html.parser')
```
Now we look at the produced HTML code of the webpage in nice and more readable format using BeautifulSoup.
```
#print(TopAnimeSoup.prettify())
```
# 1.1. Get the list of animes
### Steps to extract the url for just one anime.
Here we will go through the required steps to extract the url and the name of just the first anime in the list. We can then expand this idea to all the anime in the page.
### 1.1.1 Getting all the rows (anime) in a page
After chekcing the HTML code, we saw that the information related to each anime is stored in a table which its class is "top-ranking-table" and the animes' information are stored in trs of this table.
Let's take a look at how many tables we have in the webpage.
```
len(list(TopAnimeSoup.find_all('table')))
```
As we have only one table in the webpage, so every tr that we have in the webpage belongs to this table.
Here we will take a look at how many tr tags we have in the webpage.
```
#print(list(TopAnimeSoup.find_all('tr')))
#len(list(TopAnimeSoup.find_all('tr')))
```
We know that in each page, we have the information related to 50 animes. But why we have 51 tr tags here? <br/>
Because the first row corresponds to the name of table's column and the rest store the inramtion related to each anime.
So in order to get the rows which contain the information of each anime, we should go through the tr tags that we have in the webpage except the first one which contains the information of the columns' name of of the table.
```
Rows = list(TopAnimeSoup.find_all('tr'))[1:]
len(Rows)
```
Here we have all the information of the anime in a specific page. As we know the number of anime in each page is 50.
### 1.1.2 Extracting the name and url of an anime
Now we should get the name and the url correspond to each anime. We found out that this information can be found in 'a' tag of each row which its class name is "hoverinfo_trigger fl-l ml12 mr8" and is included in the second 'td' tag of each 'tr'.
We get all the 'td' tags of the second 'tr' the first 'tr' tag contains the columns' name.
```
Tds = Rows[0].find_all('td')
```
Then we will go to the second 'td' tag's information. The first one contains just the ranking number.
```
SecondTD = Tds[1]
```
Then inside this 'td' tag we look for the 'a' tag which its class is "hoverinfo_trigger fl-l ml12 mr8"
```
TagA = SecondTD.find('class' == "hoverinfo_trigger fl-l ml12 mr8")
TagA
```
The url of an anime is the value of 'href' property of this tag. Let's take a look at it.
```
URL = TagA['href']
URL
```
Here to extract the name of the anime we have two options. 1. To split the 'href' and get the last value of it. 2. Get the value of 'alt' property of the 'img' tag in the 'a' tag. Here we will go for the second approach.
```
Image = TagA.find('img')
AnimeName = Image['alt'].replace('Anime: ', '')
AnimeName
```
### 1.1.3 Getting the information for all anime in a page
Now here we want to get the name and url of all the animes in this specific page.
```
# Dictionary to store the url or each anime in the page
MyDict = defaultdict(str)
# Going through all the rows in the page
for Row in Rows:
# Take the second column of the row
TDs = Row.find_all('td')
# Take the tag a which consists the anime name and the url of that anime
TagA = TDs[1].find('class' == "hoverinfo_trigger fl-l ml12 mr8")
# Extract the anime name and url of the anime
AnimeName, URL = TagA.find('img')['alt'].replace('Anime: ', ''), TagA['href']
# Store the url of the anime in the dictionary
MyDict[AnimeName] = URL
```
Now we will check the information for five animes.
```
for anime in list(MyDict.keys())[:5]:
print('Name of anime: ' + anime+'\nURL: ' + MyDict[anime], end = '\n\n')
```
Here we want to check if we have all the 50 animes' URL in the dictionay.
```
print('Number of animes ', len(MyDict))
```
# 1.2 Crawl animes
### 1.2.1 Function Crawl urls in a webpage
In order to have more readable implementation we will write a function which receives the URL of the webpage that we want to scrap and writes the urls to the URLs.txt file.
```
def GetAnimeInfo(webpage):
# Opening the file that we want to write our information in
File = open('URLs.txt', mode = 'a')
# Send a request to get the webpage
Request = requests.get(webpage)
# Parse the HTML code of the webpage
TopAnimeSoup = BeautifulSoup(Request.content, 'html.parser')
# Take all the tr tags in the webpage which contain all the anime information in the given webpage
Rows = TopAnimeSoup.find_all('tr')
# Going throguh all the anime
for Row in Rows[1:]:
# Get the td tags of each anime
TDs = Row.find_all('td')
# Take the tag A which its class is equal to 'hoverinfo_trigger fl-l ml12 mr8'
TagA = TDs[1].find('class' == "hoverinfo_trigger fl-l ml12 mr8")
# Extract the URL of the anime
URL = TagA['href']
# Write the URL to the file
File.write(URL+'\n')
# Close the file we have just written it
File.close()
```
Now at each time we should pass the function the URL of the webpage that we want to scrap.
After checking the URL of the next pages, we understood that there is a pattern in URL of the pages. <br/>
For example the 2nd webpage's URL is 'https://myanimelist.net/topanime.php?limit=50' and we can see the only difference between this URL and the main page URL (which is 'https://myanimelist.net/topanime.php') is that there is '?limit=50' string at the end. <br/><br/>
* So we can use this pattern the find the next pages URL.
### 1.2.2 Main Function to extract all the URLs
```
# This is the root webpage of the website
MainPageURL = 'https://myanimelist.net/topanime.php'
# We go through first 400 pages
for i in range(400):
# This is the address that we want for the first page
if i == 0:
GetAnimeInfo(MainPageURL)
# For the next pages, we should use the address of the webpage and put the limit
# at the end to reach to the next pages
else:
GetAnimeInfo(MainPageURL+'?limit='+str(50*i))
```
### 1.2.3 Function Get HTML code
Now we want to download the HTML file for each anime. <br/>
In order to do this we are going to write a function that passes a number of URLs which their HTML file should be downloaded and stored in a folder.<br/>
These URLS are given in a list of list which correspond to a number of webpages in the website and a number of anime's URL which are in a specific webpage.
* **Note:** We will download the HTML codes in parallel by using all the processors in the system.
As this function will be called from all the processors in the system, we should find a way so that all the processors can download their own given pages' HTML code.
```
# The parameters of the function:
# URLS: A list of a list which each element in the first list is the pages and each element in the list
# of each page is the anime's URL in that page that we should get their HTML code.
# GroupIndex: Specifies which processor is calling this function
# NumPageGroup: Number of the pages that was given to each processor
# Start: Start the downloading from which page? Start = 50 -> Starting extracting the HTML code of the anime
# in the page 50
def GetHTML(URLS, GroupIndex, NumPageGroup, Start):
# Going through each page
for index, ListURLs in enumerate(URLS):
# If the page number that we are considering at this moment lower than Start, we will ignore it
if index < Start:
continue
# For each page we create a new folder to store its anime HTML code in it.
FolderName = 'page' + str(GroupIndex*NumPageGroup + index +1)
Path = os.path.join(os.getcwd(),'HTMLS', FolderName)
os.mkdir(Path)
# Iterating over all the anime URL in a specific page
for i, url in enumerate(ListURLs):
# Request to get the webpage of that anime's URL
AnimePage = requests.get(url)
# Get the HTML code of that webpage
AnimePageSoup = BeautifulSoup(AnimePage.content, 'html.parser')
# Create a html file to store the HTML code of the webpage in it
file = open(Path + '/' + 'anime_' + str(i) + '.html',"w")
file.write(str(AnimePageSoup))
file.close()
```
### 1.2.4 Parallelizing the Crawling process
So first we check how many processors we have in the system:
```
print("The number of processors:", mp.cpu_count())
```
So in this case we should distribute our URLS over these processors. We read all the URLs that we have stored in the 'URLs.txt' file.
```
AllURLs = []
with open('URLs.txt') as f:
for row in f:
AllURLs.append(row.strip())
```
Now we want to check how many URLs we have:
```
print('The total number of URLs is:', len(AllURLs))
```
* **Note:** We know that we should store all the anime's webpage HTML code in a single folder for the ones that have been appeared in the same wepbage, so all of these URLs should be entirely given to a processor.
* **Note:** We know that we extracted the URLs in order, so if we take the URLs 50 by 50 we will have the anime URLs that are in the same page.
Now we group each 50 URLs to construct the pages.
```
EachPageURLs = [AllURLs[i*50:(i+1)*50] for i in range(len(AllURLs)//50+1)]
```
Here we will take a look at how many pages that we have here:
```
print("Number of webpages in the website:", len(EachPageURLs))
```
Now we check how many pages should be given to each of the processors.
```
NumOfPage = ceil(ceil(len(AllURLs)/50)/mp.cpu_count())
print('Number of pages to be given to each processor: ', NumOfPage)
```
* Each processor is responsible to download the anime's HTML code that are in 96 pages.
Now we group the pages that should be given to each of the processors.
```
GroupPage = [EachPageURLs[i*NumOfPage:(i+1)*NumOfPage] for i in range(mp.cpu_count())]
```
Let's check the number of pages in each group:
```
print(list(map(len , GroupPage)))
```
As we can see all the processors have been assigned 96 pages to download except the last one. We remind that we have 383 page which couldn't be distributed evenly between all the processors.
### Downloading HTMLs in parallel
As we saw before, we have 4 processors in the system and we want to distribute the work among these 4 processors.<br/>
We will give a subsets of pages to each of these processors to download their anime HTMl code.
```
# How many processors we want to pool handle
pool = mp.Pool(mp.cpu_count())
# Call the GetHTML function for each of the processors given their assigned pages
results = [pool.apply_async(GetHTML, args = (GroupPage[i],i, NumOfPage, 5)) for i in range(mp.cpu_count())]
pool.close()
```
# 1.3 Parse downloaded pages
Now in this question we should produce a .tsv file for each anime which contains some information extracted from their webpage.
In order to do this, first we check how we can get the information for just one anime and then we will expand the idea to other anime that we have.
The information that we should extract for each anime are:
1- **Anime Name** (to save as animeTitle): String <br/>
2- **Anime Type** (to save as animeType): String<br/>
3- **Number of episode** (to save as animeNumEpisode): Integer<br/>
4- **Release and End Dates of anime** (to save as releaseDate and endDate): Convert both release and end date into datetime format.<br/>
5- **Number of members** (to save as animeNumMembers): Integer<br/>
6- **Score** (to save as animeScore): Float<br/>
7- **Users** (to save as animeUsers): Integer<br/>
8- **Rank** (to save as animeRank): Integer<br/>
9- **Popularity** (to save as animePopularity): Integer<br/>
10- **Synopsis** (to save as animeDescription): String<br/>
11- **Related Anime** (to save as animeRelated): Extract all the related animes, but only keep unique values and those that have a hyperlink associated to them. List of strings.<br/>
12- **Characters** (to save as animeCharacters): List of strings.<br/>
13- **Voices** (to save as animeVoices): List of strings<br/>
14- **Staff** (to save as animeStaff): Include the staff name and their responsibility/task in a list of lists.<br/>
* For getting each of the information that we need, we write a function to have a better understanding of how we should extract each of these information.
### 1.3.1 Function AnimeName
We know that the name of the anime can be extracted from the title of the webpage. So we send the html code of the webpage to this function, and we will return the name of the anime extracted from the title of the page.
```
def GetAnimeName(webpage):
return webpage.title.getText().strip().replace(' - MyAnimeList.net', '')
```
### 1.3.2 Function GetAnimeType
This information can be extracted from the values stored in a specific 'div' tag. In order do this we will send that specific tag to this function and receive the type of the anime.
```
def GetAnimeType(Tag):
Temp = Tag.getText().split()
return Temp[-1] if len(Temp) >1 else ""
```
### 1.3.3 Function Episode
This information can be extracted from the values stored in a specific 'div' tag. In order do this we will send that specific tag to this function and receive the type of the anime.
```
def GetNumOfEpisode(Tag):
Temp = Tag.getText().strip().split()[-1]
return int(Temp) if Temp.isdigit() else ''
```
### 1.3.4 Function DateTime
This information can be extracted from the values stored in a specific 'div' tag. In order do this we will send that specific tag to this function and receive the type of the anime. <br/><br/>
* Some of the animes may have just the release date. So we should be careful about this.
```
def GetDates(Tag):
Release, End = '', ''
Temp = Tag.getText().strip().replace('Aired:\n ', '').split('to')
Release = Temp[0] if len(Temp) else ''
End = Temp[1] if len(Temp) == 2 else ''
return Release, End
```
### 1.3.5 Function Members
This information can be extracted from the values stored in a specific 'div' tag. In order do this we will send that specific tag to this function and receive the type of the anime.
```
def GetMembers(Tag):
return int(Tag.getText().replace('\n', '').split()[1].replace(',', ''))
```
### 1.3.6 Function ScoreAndUsers
This information can be extracted from the values stored in a specific 'div' tag. In order do this we will send that specific tag to this function and receive the type of the anime.
```
def GetScoreAndUsers(Tag):
Rank = re.findall('[0-9|,]+ users', str(Tag))
RankValue = int(Rank[0].split()[0].replace(',', '')) if len(Rank) else ''
Score = re.findall('Score:[0-9|.]+', Tag.getText().replace("\n", ''))
ScoreValue = float(Score[0].split(":")[1]) if len(Score) else ''
return ScoreValue, RankValue
```
### 1.3.7 Function Rank
This information can be extracted from the values stored in a specific 'div' tag. In order do this we will send that specific tag to this function and receive the type of the anime.
```
def GetRank(Tag):
Temp = re.findall('#[0-9|,]+', str(Tag))
return int(Temp[0][1:]) if len(Temp) else ''
```
### 1.3.8 Function Popularity
This information can be extracted from the values stored in a specific 'div' tag. In order do this we will send that specific tag to this function and receive the type of the anime.
```
def GetPopularity(Tag):
Temp = re.findall('#[0-9|,]+', str(Tag))
return int(Temp[0][1:]) if len(Temp) else ''
```
### 1.3.9 Function Synopsis
In order to get the description of the anime, there is a specific tag which can be easily identified by its 'itemprop' property. So we will give the whole html to this function and get back the description.
```
def GetSynopsis(webpage):
Temp = webpage.find('p', {'itemprop': "description"})
if not Temp:
return ''
Temp = Temp.getText().replace('\n', '')
return Temp
```
### 1.3.10 Function Related Anime
To get the related animes, there is a table which its 'class' is equal to 'anime_detail_related_anime'. So to get the table we should give the function the whole html file to this function.
```
def GetRelatedAnime(webpage):
Related = webpage.find('table', {'class': "anime_detail_related_anime"})
if not Related:
return ""
Related = Related.find_all('a')
UniqueRelated = set(i.getText() for i in Related)
return list(UniqueRelated)
```
### 1.3.11 Function Characters
We can find this information in tag 'a' that are included in a div which is its class is equal to 'detail-characters-list clearfix'. When we go for the first div that have this feature we will be received the table which is the characters and their original voices is there.
```
def GetCharacters(webpage):
Characters = []
Tags = webpage.find_all('div', {'class': "detail-characters-list clearfix"})
for tag in Tags:
if str(tag).count('character') >1:
# We can get the name of the character in the 'href' value of the tag 'a' property
AllTagA = tag.find_all('a')
# Filter the hrefs to of the characters
CharactersHrefs = list(set([i['href'] for i in AllTagA if 'character' in i['href']]))
# Filter the names of the characters
Characters = [i.split('/')[-1].replace('_', ' ') for i in CharactersHrefs]
return Characters
```
### 1.3.12 Function Voices
With the same approach as previous, now we just extract the voices.
```
def GetVoices(webpage):
Voices = []
Tags = webpage.find_all('div', {'class': "detail-characters-list clearfix"})
for tag in Tags:
if str(tag).count('character') > 1:
# We can get the name of the person in charge for the voice in the 'href' value in tag 'a' property
AllTagA = tag.find_all('a')
# Filter the hrefs for voices
VoicesHrefs = list(set([i['href'] for i in AllTagA if 'people' in i['href']]))
# Filter the names of the people
Voices = [i.split('/')[-1].replace('_', ' ') for i in VoicesHrefs]
return Voices
```
### 1.3.13 Function Staff
Here in this function we will look for the other div tha its 'class' is equal to 'detail-characters-list clearfix'. Then the name of the staff can be extracted from 'img' tags and also their duties can be found in the 'small' tags which are in the same 'row' as their image.
```
def GetStaff(webpage):
StaffDuty = []
Tags = webpage.find_all('div', {'class': "detail-characters-list clearfix"})
for tag in Tags:
if str(tag).count('character') == 1:
Staff = tag.find_all('tr')
for i in Staff:
NewStaff = [i.find('a')['href'].split('/')[-1].replace('_', ' ')] # Extracting the name of the staff
Duties = list(i.find('small').getText().split(',')) # Getting the duties of the staff
NewStaff += [i.strip() for i in Duties]
StaffDuty.append(NewStaff)
return StaffDuty
```
### 1.3.14 Function Write to TSV
With the help of this function, we can write the information that we extracted from a page to its corresponded .tsv file.
```
def WriteToTSV(AnimeInfo, Path):
# Open the corresponded file
File = open(Path, mode = 'w')
# Writing the header.
File.write("\t".join(Keys))
File.write('\n')
# Going through all the information for that specific anime
for i in AnimeInfo:
# Get the string version of that value
STR = str(AnimeInfo[i])
# In case an information was missing, we should put '' in the file
if STR == '[]':
STR = ''
# Write the value of the information into the file
File.write(STR + ('\t' if i!='animeStaff' else "" ))
File.close()
```
### 1.3.15 Function Extract
With the help of this function we want to extract the desired information from all the .html files that we have.
Here we used some key words so we can easily get the needed information which are in some tags that share the same class.
```
Info = ['Type:', 'Episodes:', 'Aired:', 'Members:','Score:','Ranked:', 'Popularity:']
```
Here we define the default datastructure which is a dictionary to store the inforamtion of each page.
```
Keys = ['animeTitle', 'animeType', 'animeNumEpisode', 'releaseDate', 'endDate', 'animeNumMembers'
, 'animeScore', 'animeUsers', 'animeRank', 'animePopularity', 'animeDescription', 'animeRelated',
'animeCharacters', 'animeVoices', 'animeStaff']
# Empty instance for storing the information for each anime
MyAnimeInfo = {i:"" for i in Keys}
```
Here we will go through each HTML file that we have just downloaded. Then we extract the infomration that we need from the HTML file and then store them in a .tsv file.
* **Note:** as we wanted to avoid each processor override the datastructure of another processor we gave each processor its own private datastructure. That is the usage of exec functions.
* exec function: Given a string it will turn that string into a python code and run the code. In this case we gave this possibility to each processor to work on its own datastructure.
```
def FunctionExtract(ListNumPage, ProcesserNum):
# Going through all the pages
for i in ListNumPage:
# Going through all the anime in each page
for j in range((50 if i!= 383 else 28)):
# Get the copy of the default datastructures
exec('NewAnime'+str(ProcesserNum)+'= MyAnimeInfo.copy()')
# Reading the .html file of a specific anime
Path = '/home/mehrdad/ADM-HW3/HTMLS/page'
File = open(Path + str(i) + '/anime_' + str(j) +'.html', mode = 'r')
# Get the parsed HTML code of the webpage of the anime
Webpage = BeautifulSoup(File.read(), 'html.parser')
# Extracting some of the information that have been stored in the tags that have the
# same value as the class
for div in Webpage.find_all('div', {'class':"spaceit_pad"}):
if Info[0] in str(div):
exec('NewAnime'+ str(ProcesserNum) +"['animeType'] = GetAnimeType(div)")
elif Info[1] in str(div):
exec('NewAnime'+ str(ProcesserNum) +"['animeNumEpisode'] = GetNumOfEpisode(div)")
elif Info[2] in str(div):
exec('NewAnime'+ str(ProcesserNum) +"['releaseDate'] = GetDates(div)[0]")
exec('NewAnime'+ str(ProcesserNum) +"['endDate'] = GetDates(div)[1]")
elif Info[3] in str(div):
exec('NewAnime'+ str(ProcesserNum) +"['animeNumMembers'] = GetMembers(div)")
elif Info[4] in str(div):
exec('NewAnime'+ str(ProcesserNum) +"['animeScore'] = GetScoreAndUsers(div)[0]")
exec('NewAnime'+ str(ProcesserNum) +"['animeUsers'] = GetScoreAndUsers(div)[1]")
elif Info[5] in str(div):
exec('NewAnime'+ str(ProcesserNum) +"['animeRank'] = GetRank(div)")
elif Info[6] in str(div):
exec('NewAnime'+ str(ProcesserNum) +"['animePopularity'] = GetPopularity(div)")
# Extracting the other information
exec('NewAnime'+ str(ProcesserNum) +"['animeTitle'] = GetAnimeName(Webpage)")
exec('NewAnime'+ str(ProcesserNum) +"['animeDescription'] = GetSynopsis(Webpage)")
exec('NewAnime'+ str(ProcesserNum) +"['animeRelated'] = GetRelatedAnime(Webpage)")
exec('NewAnime'+ str(ProcesserNum) +"['animeCharacters'] = GetCharacters(Webpage)")
exec('NewAnime'+ str(ProcesserNum) +"['animeVoices'] = GetVoices(Webpage)")
exec('NewAnime'+ str(ProcesserNum) +"['animeStaff'] = GetStaff(Webpage)")
TSVPath = Path + str(i) + '/anime_' + str(j) +'.tsv'
exec('WriteToTSV(NewAnime'+ str(ProcesserNum)+',TSVPath)')
```
### Creating the .tsv files in parallel.
* **In order to speed up the process, we will distribute the work among the available CPUs.**
We should give a subset of pages to each CPU to make its animes' .tsv file. <br/>
Here we will group the page numbers that should be given to each processor.
```
RangePage = list(range(1, len(EachPageURLs) + 1))
PageNums = [RangePage[i * NumOfPage:(i+1) * NumOfPage] for i in range(mp.cpu_count())]
```
Call the function for each CPU give a susbset of .html files.
```
pool = mp.Pool(mp.cpu_count())
results = [pool.apply_async(FunctionExtract, args = (PageNums[i],i)) for i in range(mp.cpu_count())]
pool.close()
```
# 2. Search Engine
Here we are asked to build a search engine which given a query, will give back the documents that are similar to the given query.
### 2.0 Pre-processing the information
Here we will pre-process all the information of an anime and store it to another .tsv file which will be name SynopsisPrepAnime_(i).csv which i corresponds to the index number of the page in its page.
To do pre-processing we have 5 stages and for each stage we will write a function.
### 2.0.1 Tokenization
Given a string, we will return the words that are in the given string.
```
# Using this functions to extract the terms in each given sentence
def Tokenization(Sentence):
return nltk.word_tokenize(Sentence)
```
### 2.0.2 Lowercasing
Given a list of strings, we will return the same strings but in lower case.
```
# Turn all the words that we have in the given list of words to their lowercase
def Lowercasing(Words):
return [w.lower() for w in Words]
```
### 2.0.3 StopWordsRemoval
Here we will define a list which contains all the stopwords in English language.
```
StopWords = stopwords.words('english')
```
Given a list of strings, we will remove the stopwords from that strings.
```
# We will consider just those terms that are not in stopwords
def StopWordsRemoval(Words):
return [w for w in Words if w not in StopWords]
```
### 2.0.4 PunctuationsRemoval
In this function given a list of strings, we will remove the punctuations from those strings.
```
# To remove the punctuations, we only will consider the alphabetic letters
def PunctuationsRemoval(Words):
return [w for w in Words if w.isalpha()]
```
### 2.0.5 Stemming
In this function, given a list of strings, we try to return back the stem of each string that we have in the list. <br/>
Here we will use 'PorterStemmer' algorithm to do stemming.
```
# The stem of each word will be returned
def Stemming(Words):
return [PorterStemmer().stem(w) for w in Words]
```
* Here we are asked to work with the 'Synopsis' of each anime, so we decided pre-process only the synopsis of each anime and not all the information that we extracted.
* **Note:** For your information, we want to do the pre-process we will distribute the work among the available number of CPUs in the system. Each CPU will be given a subset of pages to do the pre-process for the contained anime information.
### 2.0.6 Main Function
```
def MainFunction(Pages):
# For each page
for page in Pages:
# For each anime in a specific page
for anime in range((50 if page != 383 else 28)):
# Read the '.tsv' file of that specific anime
Path = '/home/mehrdad/ADM-HW3/HTMLS/page'
File = open(Path + str(page) + '/anime_' + str(anime) +'.tsv', mode = 'r')
# For each anime we want to extract the synopsis
Data = File.read().split('\n')[1].split('\t')[10]
File.close()
# Given the synopsis of a specific anime to pre-processing stage
Tokens = Tokenization(Data)
Lowercase = Lowercasing(Tokens)
WithoutStop = StopWordsRemoval(Lowercase)
WithoutPuncs = PunctuationsRemoval(WithoutStop)
Stems = Stemming(WithoutPuncs)
# Store the result of the pre-processing stage in a '.csv' file for each specific anime
PreProcessed = open(Path + str(page) + '/anime_' + str(anime) +'_synopsisPrep.csv', mode = 'w')
PreProcessed.write(",".join(Stems))
PreProcessed.close()
```
## 2.1 Conjunctive query
Here we will pre-process the synopsis of each anime.
Group the pages to be given to the CPUs.
```
RangePage = list(range(1, len(EachPageURLs) + 1))
PageNums = [RangePage[i * NumOfPage:(i+1) * NumOfPage] for i in range(mp.cpu_count())]
```
Pre-processing all the synopsis of animes.
```
pool = mp.Pool(mp.cpu_count())
results = [pool.apply_async(MainFunction, args = (PageNums[i],)) for i in range(mp.cpu_count())]
pool.close()
```
## 2.1.1 Create your index!
Here we will create a file name **'vocabulary.json'** which will map each word that we want to take into account for our analysis to a specific ID.
We will go through all the pre-processed files that we have created for each anime and extract all the words in them and give each word a specific ID.
```
# Dictionary which stores each words in all anime
MyDict = dict()
# For each page
for i in range(1, 384):
# For each anime
for j in range((50 if i != 383 else 28)):
# Open the '.csv' file of each specific anime
Path = '/home/mehrdad/ADM-HW3/HTMLS/page'
File = open(Path + str(i) + '/anime_' + str(j) +'_synopsisPrep.csv', mode = 'r')
# Get the words in the synopsis of each anime
DescriptionWord = File.read().split(',')
# For each word in the synopsis we will have an entry in the dictionary
for term in DescriptionWord:
MyDict[term] = 0
# Assign each word a unique id
for term_id,term in enumerate(MyDict.keys()):
MyDict[term] = term_id
# Writing the resulted information into a .json file so we can easily retrieve them
with open("Vocabulary.json", "w") as write_file:
json.dump(MyDict, write_file)
```
### 2.1.1.1 Creating Inverted Indexes
Here we will go through all the preprocessed files and add the documents id to the values of the terms we find in each document.
We will store the document ids as a combination of page number of anime id (#page, #anime_id).
* We will store our created inverted index into a file named **'InvertedIndex_1'**.
```
# A dictionary which have all the terms in the corpus and their term_id
Vocabularies = json.load(open("Vocabulary.json", "r"))
# We will store our inverted index in this dictionary
# Keys: term
# Value: a list of document_id (which is a pair of page and anime index)
InvertedIndexes = defaultdict(set)
# For each page
for i in range(1, 384):
# For each anime
for j in range((50 if i != 383 else 28)):
# Read the '.csv' file for each specific anime
Path = '/home/mehrdad/ADM-HW3/HTMLS/page'
File = open(Path + str(i) + '/anime_' + str(j) +'_synopsisPrep.csv', mode = 'r')
# Extract the words in the synopsis for each anime
DescriptionWord = File.read().split(',')
# For all the terms that are in this anime, we will add the document_id to its list
for term in DescriptionWord:
InvertedIndexes[Vocabularies[term]].add((i,j))
# Sorting the document_ids
for term in InvertedIndexes:
InvertedIndexes[term] = sorted(InvertedIndexes[term])
# We will store these information in a '.json' file so we can easily retrieve them
with open("InvertedIndex_1.json", "w") as write_file:
json.dump(InvertedIndexes, write_file)
```
## 2.1.2 Execute the query
Here given a query we want to return the documents that are containing all the words in the given query.
In order to answer the query, first we should pre-process the query as well. We need to do this as we have pre-processed all the information that we have extracted from the htmls.
* Here we will write a function which given a string, it will pre-process the string and return the results.
### 2.1.2.1 Function String Pre-process
```
# Given a stirng, the string will go to the pre-process stage
def StringPreProcess(string):
Tokens = Tokenization(string)
LowerCased = Lowercasing(Tokens)
WithoutStop = StopWordsRemoval(LowerCased)
WithoutPunc = PunctuationsRemoval(WithoutStop)
Stemmed = Stemming(WithoutPunc)
return Stemmed
```
### 2.1.2.2 Function token to TermID
This function given a token and the Vocabulary data structure will return back the term_id of that token. If the token is not in the Vocabulary, this function will return None.
```
def WordToTermID(Token, Vocabulary):
return Vocabulary.get(Token)
```
### 2.1.2.3 Function Extracting Documents
Given a TermID and inverted indexes, this function will return the documents which are containing this specific token. If TermID is equal to 'None', this function will return empty list.
```
def ExtractDocs(TermId, InvertedIndex):
return InvertedIndex.get(str(TermId)) if TermId else []
```
### 2.1.2.4 Function Query to Documents
This function will process the given query and return back the documents that are containing all the words in the query.
```
def QueryToDocuments(Query, Vocabulary, InvertedIndex):
PreProcessedQuery = StringPreProcess(Query)
# If the query after the pre-process stage was empty, return an empty list
if not len(PreProcessedQuery):
return []
# This list will store all the documents in which each term was there.
Documents = []
# Convert each term to its termid
TermIDs = [WordToTermID(term, Vocabulary) for term in PreProcessedQuery]
# All the documents for each Term
Documents = [set(map(tuple, ExtractDocs(TermID, InvertedIndex))) for TermID in TermIDs]
# Take the intersection of the documents
Result = sorted(Documents[0].intersection(*Documents))
return Result
```
### 2.1.2.5 Function Data to Dataframe
This function given the name of the columns and the values for each column will create a dataframe with those information which help to visualize the results in tabular format.
```
# Given the column name and the records, will produce a dataframe
def DataToDataFrame(ColumnsName, Records):
# Declare a datafram with specific column name
Table = pd.DataFrame(columns = ColumnsName)
# For each records
for rec in Records:
# We will store the values in each records in a dictionary as for adding a record to the dataframe
# we should pass a dictionary
TempDict = dict()
# For each value of the columns of the records
for col in range(len(ColumnsName)):
# Give the value of that column to the dictionary
TempDict[ColumnsName[col]] = rec[col]
# Add this new record to the dataframe
Table = Table.append(TempDict,ignore_index = True )
display(Table)
```
### 2.1.2.6 Function Main Answer Query
```
# Loading Vocabulary
Vocabulary = json.load(open("Vocabulary.json", "r"))
# Loading Inverted Indexes
InvertedIndex = json.load(open("InvertedIndex_1.json", 'r'))
Query = input('Please enter your query here: ')
# Results
Results = QueryToDocuments(Query, Vocabulary, InvertedIndex)
# To pass the data to show in tabular format
Columns, Data = ['animeTitle', 'animeDescription', 'URL'], []
# Now here we should iterate over all the results and retrieve the information for each of these anime
for Res in Results:
Path = '/home/mehrdad/ADM-HW3/HTMLS/page'
FileURL = open('URLs.txt', mode = 'r')
FileInfo = open(Path + str(Res[0]) + '/anime_' + str(Res[1]) +'.tsv', mode = 'r')
Information = FileInfo.read().split('\n')[1].split('\t')
Title = Information[0]
Description = Information[10]
URL = FileURL.read().split('\n')[(Res[0]-1)*50 + Res[1]]
Data.append([Title, Description, URL])
# Showing the results
DataToDataFrame(Columns, Data)
```
## 2.2. Conjunctive query & Ranking score
For this part we are asking to given a query, show the top k documents that are more closer to this query using scoring schema.
To answer this question, first we should go through some definitions.
### - What is tf?
We define tf(t, d) of term t in documnet d as the **division** of the **number of occurance of term t in document d** by **the total number of occurance of term t in all documents** in the corpus. You can see the formula here:
### - What is idf?
Idf (inverse document frequency) is a measure of how much information the word provides. This value will be obtained by **dividing** the **total number of documents** by the **number of documents containing the term**, and then taking the **logarithm** of that quotient. You can see the formula here:
### - What is tfidf?
Tfidf for each term and document can be obtained by the **multiplication** of **tf(t,d) and idf(t,D)**. The higher this value is, the more important that term is in that specific document.
## 2.2.1 Creating the inverted indexes
Here we should build an inverted index in the format that each term corresponds to the documents in which that term is appearing and also the tfidf of that term in that specific document.
Here we will define some functions to help us to do this process.
### 2.2.1.1 Function tfidf
This function given the list of documents and the number of occurance of each specific term T in each of these documents and also the number of all the documents in the corpus, will return the terms and its tfidf for each of the documents that are containing that term.
```
def GetTfIdf(invertedIndex, NumberOfDocs):
for Term in invertedIndex: # For each term
# How many times that term occured in the corpus
TotalOccurance = sum(doc[1] for doc in invertedIndex[Term])
# How many documents are containig that term
NumberOfTDocs = len(invertedIndex[Term])
# Computing the idf of a term
idf = log(NumberOfDocs / NumberOfTDocs)
for docs in invertedIndex[Term]: # For each document that is contaning the term
# Put the tfidf (tf*idf) instead of the number of occurence of that term in the document
docs[1] = (docs[1] / TotalOccurance) * idf
return invertedIndex
```
### 2.2.1.2 Create a suitable inverted index
Now we should write a code that build another type of inverted index, which each term corresponds to the documents that are contaning that term and also the number of occurence of the term in each of those documents. This inverted index will be saved in 'InvertedIndex_2.json' file.
```
# To get the term_id of each term
Vocabularies = json.load(open("Vocabulary.json", "r"))
# To store the inverted index
# We will store our inverted index in this dictionary
# Keys: term
# Value: a list of (document_id (which is a pair of page and anime index), #occurance of the term in this document)
InvertedIndexes = defaultdict(set)
# For each page
for i in range(1, 384):
# For each anime
for j in range((50 if i != 383 else 28)):
# Read the '.csv' file for a specific anime
Path = '/home/mehrdad/ADM-HW3/HTMLS/page'
File = open(Path + str(i) + '/anime_' + str(j) +'_synopsisPrep.csv', mode = 'r')
# Extract the words in the synopsis of that anime
DescriptionWord = File.read().split(',')
# Check the number of the occurances of each word in the synopsis of a specific anime
NumberOfOccurenceInDoc = Counter(DescriptionWord)
# For each term we will add this anime and its total number of occurance in this anime
for term in NumberOfOccurenceInDoc:
InvertedIndexes[Vocabularies[term]].add(((i,j), NumberOfOccurenceInDoc[term]))
# Sorting the document ids
for term in InvertedIndexes:
InvertedIndexes[term] = sorted(InvertedIndexes[term])
# Store this inverted index in '.json' file to get the information pretty easily
with open("InvertedIndex_2.json", "w") as write_file:
json.dump(InvertedIndexes, write_file)
```
Now we are able to compute the tf, idf and ea the end the tfidf of each term and docment.
### 2.2.1.3 Main Creating the new Inverted Index
Now here we will create a new inverted index such that each term has the information about each document that is containig that specific term and also the tfidf of that term and that specific document. This new inverted index will be saved in a file named **'InvertedIndex_3.json'**.
```
# Loading the second inverted index term -> documents, # Occurence
InvertedIndex = json.load(open("InvertedIndex_2.json", "r"))
# Number of the docuements in the corpus
NumOfDocs = len(AllURLs) # Number of documents are the number of the anime
# Computing the tfidf for each term and document
NewInvertedIndex = GetTfIdf(InvertedIndex, NumOfDocs)
# Saving the new inverted index into a new file named 'InvertedIndex_3.json'
with open("InvertedIndex_3.json", "w") as write_file:
json.dump(NewInvertedIndex, write_file)
```
### 2.2.1.4 Function query to tfidf
This function given the query, the second inverted index which each term corresonds to the docuemnts that are containig the number of occurence of that term in those documents, the vocabulary, and the number of all the docuemnts in the corpus will compute the tfidf of the term in the query.
```
def QueryToTfidf(Query, invertedIndex,Vocabulary, NumberOfDocs):
# Mapping the words in query to their term_id
PreProcessedQuery = StringPreProcess(Query)
Query = [str(Vocabulary.get(Term)) for Term in PreProcessedQuery]
# Check the number of occurence of each term in the query
QueryDict = Counter(Query)
for Term in QueryDict:# for each term in the query
# If that term is in the inverted index
if invertedIndex.get(Term):
# How many times that term occured in the corpus
TotalOccurance = sum(doc[1] for doc in invertedIndex[Term])
# How many documents are containig that term
NumberOfTDocs = len(invertedIndex[Term])
# Computing the idf of a term
idf = log(NumberOfDocs / NumberOfTDocs)
# Put the tfidf (tf*idf) instead of the number of occurence of that term in the query
QueryDict[Term] = (QueryDict[Term]/ TotalOccurance) * idf
else:
QueryDict[Term] = 0
return QueryDict
```
### 2.2.1.5 Function Dot Product
In this function given two vectors, we will compute the dot product of the two and return back the result.
```
def DotProduct(V1, V2): # The two given vectors should have the same length
return sum(V1[i] * V2[i] for i in range(len(V1)))
```
### 2.2.1.6 Function Euclidean norm
This function given a vector, will compute the Euclidean norm of that vector and return the result.
```
# Computes the Eucledean norm the given vector
def Euclidean(Vector):
return (sum(Vector[i]**2 for i in range(len(Vector)))) ** .5
```
### 2.2.1.7 Function Query to Documents
In this function, given the query and the 3rd inverted index, we will extract the documents that are contaning all the terms in the query. The result will be a dictinoary which the keys are the documents and the keys are a list which is containing all the tfirdf of the terms in the query.
```
def QueryToDocuemnts(Query, invertedIndex):
AllTermsDict = []
for term in Query: # For each term in the query
TermDict = {} # The dictionary which contains the documents that are containing that term
# For each document which is contaning the term
if invertedIndex.get(term):
for doc in invertedIndex[term]:
# Add the document and the corresponded tfidf for that term in that document
TermDict[tuple(doc[0])] = doc[1]
# Add the dictionary for a specific term in the query which is containig all
# the document that are containig that term
AllTermsDict.append(TermDict.copy())
# Extract the documents that are containing all the terms in the query
# All the documents in each dictionary
AllDocs = [set(termDict.keys()) for termDict in AllTermsDict]
AllIncludedDocs = AllDocs[0].intersection(*AllDocs) # Docs that are containing all the terms in the query
# Here we are creating a dictionary which keys are the documents that are containig all the terms in the query
# and the keys are the tfidf of all the term in the query in sequence.
DocsToTfidf = defaultdict(list)
for termDict in AllTermsDict:
for doc in AllIncludedDocs:
DocsToTfidf[doc].append(termDict[doc])
return DocsToTfidf
```
### 2.2.1.8 Function Similarity
In this function given the query tfidf values and all the documents that are containig all the terms in the query, we want to compute the similarity of the query with each docuement.
* The cosine similarity between two vectores will be the **dot product of the values** in these two vectors, **divided** by **the multiplication of the euclidean norm** of each of the vectors.
```
def Similarity(QueryTfidf, Documents):
for doc in Documents:
# Compute the dot product of tfidf of the terms in the query and a specific document
DotProductRes = DotProduct(QueryTfidf, Documents[doc])
# Computer the similarity of query and a specific document
Similarity = DotProductRes/(Euclidean(QueryTfidf)*Euclidean(Documents[doc]))
# Append the value of similarity at the end of the least of each document.
Documents[doc].append(Similarity)
return Documents
```
* We are asked to sort the similar documents using heap sort. In order to use heap sort, we should have a class for the object that we are passing to the heap.
### 2.2.1.9 Function Docs Class
```
class Docs:
# Storing the passed information for each object
def __init__(self,DocInfo):
self.docInfo = DocInfo
# Overriding the operator '<'. Here as we need the descending sort, we override in reverse.
def __lt__(self, other):
return self.docInfo[-1] > other.docInfo[-1]
# Overriding the operator '>'
def __gt__(self, other):
return other.__lt__(self)
```
### 2.2.1.10 Function HeapSort
This function given a list of object will sort them by using heap tree and return the result.
```
def heapsort(objects):
# Heap Tree
heap = []
# Add all the given object to the tree
for element in objects:
heappush(heap, element)
# Will store the ordered version of objects
ordered = []
# Until we have still object in tree
while heap:
#Take the root of the tree -> Which is the highest value.
ordered.append(heappop(heap))
return ordered
```
### 2.2.1.10 Main function Ranking
```
# Get the query from the user
Query = input('Please enter your query here: ')
# First K most similar documents
K = int(input('Please enter the value of k here: '))
# Loading the second inverted index term -> documents, # Occurence
SecondInvertedIndex = json.load(open("InvertedIndex_2.json", "r"))
# Loading the third inverted index term -> documents, # tfidf
ThirdInvertedIndex = json.load(open("InvertedIndex_3.json", "r"))
# Loading the vocabulary file which maps each term to a specific ID
Vocabularies = json.load(open("Vocabulary.json", "r"))
# Compute the TFIDF of the query
QueryTFIDF = QueryToTfidf(Query, SecondInvertedIndex,Vocabularies, len(AllURLs))
# Take the documents that are containing all the words
RelatedDocuments = QueryToDocuemnts(QueryTFIDF.keys(), ThirdInvertedIndex)
# Compute the similarity of each document with query
DocumentsSimilarity = Similarity(list(QueryTFIDF.values()), deepcopy(RelatedDocuments))
# Here we will store the details of each similar documents
Data = []
for Res in DocumentsSimilarity:
Path = '/home/mehrdad/ADM-HW3/HTMLS/page'
FileURL = open('URLs.txt', mode = 'r')
FileInfo = open(Path + str(Res[0]) + '/anime_' + str(Res[1]) +'.tsv', mode = 'r')
Information = FileInfo.read().split('\n')[1].split('\t')
Title = Information[0]
Description = Information[10]
URL = FileURL.read().split('\n')[(Res[0]-1)*50 + Res[1]]
Data.append([Title, Description, URL, DocumentsSimilarity[Res][-1]])
# Here we will sort the documents based on the similarity using heap tree
Data = [Doc.docInfo for Doc in heapsort([Docs(i) for i in Data])]
# Setting the similarity to 2 float places
for doc in Data:
doc[-1] = "{:.2f}".format(doc[-1])
# Here we will pick the first K documents that are more similar with respect to the given query
DataToDataFrame(['animeTitle','animeDescriptio', 'Url', 'Similarity'], Data[:K])
```
# 3. Define a new score
In this question we let the user to include more information in his query. Most of the provided information will be working as a filter except the which user gives us for the synopsis. What we let the user include in his query and in which format:
### Filters
1- **The type of anime:** If a user wants to include the type of the anime in the query, he should use this notation -> 1- {The type of anime}, ex. 1- tv
2- **The date of releasing:** If a user want to include a starting point which our search engine consider the anime which their release that is after that starting poin, he should use this notation -> 2- {released year}, ex. 2- 2009
3- **The date of ending:** If the user wants to include an end point in which our search engine not consider the anime that have been ended after this time then he should use this notation: 3- {end year}, ex. 3- 2020
4- **Some words in the synopsis:** If the user wants to include some words that those words has been occured in the resulted anime's synopsis, he should use this notation: 4- {words in synopsis}, ex. 4- saiyan race
* **Note:** We won't consider the documents that are missing some of the information provided in the query.
### Scoring
To score the related documents and show them in order, we will consider these variables:
**The normalized value for value x in a sequence of values X will be defined as (x - min(X))/(max(X) - min(X))**
1- **The cosine similarity:** The docuemnts that have a higher cosine similarity with respect to the words in synopsis given in the query, will have a higher priority.**To mention this value is between 1 and 0**
2- **Anime score and anime user:** We will consider a combination of anime score and its number of user. We will use a multiplication of the number of the users and the score of the anime. Then when we had this value for all the related animes, we will normalize the values according to its formula.
3- **Number of members:** As we know here the higher the member, the more popular the anime. So here we will normalize these values using the mentioned formula for normalization.
**Final score: The final score of a document in our approach will be the sum of all of these values. The the ones that having higher score, will have a higher priority.**
* **Note:** If in any case we had some missing values, we will consider those values as 0.
### *The main function for this part is at the end of this section*.
Now we go throguh the steps and the functions needed to build this search engine.
## 1. Filtering
**Here we first filter the the documents with respect to the given query**
### 3.1.1 Function Query Process
```
# With the help of this function we will be able to extract each parameter in the query
def QueryProcess(Query):
Strings = re.split('[1|2|3|4]-', Query.lower())[1:]
Numbers = re.findall('[1|2|3|4]+-', Query.lower())
GivenConditions = ["".join(i) for i in zip(Numbers, Strings)]
return GivenConditions
```
After getting the query, now we should filter the documents with respect to the given conditions. Here we will filter the by using 'Anime Type', 'Anime Released Data' and 'Anime End Data'.
### 3.1.2 Function Filter Documents
```
def FilterDocs(Conditions):
# This dictionary will contain the filtered documents and their necessary information
FilteredDocs = {}
# To have the URL of all the anime
FileURL = open('URLs.txt', mode = 'r').read().split('\n')
# For each page
for page in range(1, 384):
# For each anime
for anime in range((50 if page != 383 else 28)):
# Read the '.tsv' file of each specific anime
Path = '/home/mehrdad/ADM-HW3/HTMLS/page'
File = open(Path + str(page) + '/anime_' + str(anime) +'.tsv', mode = 'r')
# Take the URL of a specific anime
URL = FileURL[(page-1)*50 + anime]
# The extracted information for that anime
AnimeInfo = FilterInfo(File)
# A flag which specifies if we should consider this docuemnt or it should be filtered
Pick = True
# For each condition that we have in the query
for Con in Conditions:
# Here will check each condition given in the query
# Anime type
# Releasing date
# End date
Con = list(map(str.strip, Con.split('-')))
if Con[0] == '1' and AnimeInfo['animeType'] != Con[1]:
Pick = False
elif (Con[0] == '2' and AnimeInfo['releaseDate'] < Con[1]) or not AnimeInfo['releaseDate'].isdigit():
Pick = False
elif (Con[0] == '3' and (AnimeInfo['endDate'] > Con[1]) or not AnimeInfo['endDate'].isdigit()):
Pick = False
if Pick:
AnimeInfo['URL'] = URL
FilteredDocs[(page,anime)] = deepcopy(AnimeInfo)
return FilteredDocs
```
### 3.1.3 Function Filter Necessary Information
In this function given a document we will extract the necessary information which will be 'Anime Title', 'Anime Score', 'Anime Users' and 'Anime members'.
```
def FilterInfo(Document):
# We will filter some useful information the given document
ReadDocument = Document.read().split('\n')[1].split('\t')
InfoDict = {'animeTitle':ReadDocument[0], 'animeScore': ReadDocument[6], 'animeUser': ReadDocument[7],
'animeMembers': ReadDocument[5], 'releaseDate': ReadDocument[3].split(',')[-1].strip(),
'endDate':ReadDocument[4].split(',')[-1].strip(),'animeType': ReadDocument[1]}
# We will lower case everything except Anime Title
for i in list(InfoDict.keys())[1:]:
InfoDict[i] = InfoDict[i].lower()
return deepcopy(InfoDict)
```
## 3.1.4 Main Function Filter
Here we will get the query from the user in the format stated above.
```
def Filtering(Query):
FilteredDocuments = FilterDocs(Query)
# Then we should compute check the similarity between the query and the given filtered documents
# So we will add another property to each filtered data name synopsisSimilarity.
# This value will be by default 0.
for Doc in FilteredDocuments:
FilteredDocuments[Doc]['synopsisSimilarity'] = 0
# Then we will check the cosine similarity between the query and the synosis of the anime if this information
# was provided in the query
SynopsisQuery = ''
for q in Query:
if '4-' in q:
SynopsisQuery = q.split('- ')[-1]
if SynopsisQuery:
# Loading the second inverted index term -> documents, # Occurence
SecondInvertedIndex = json.load(open("InvertedIndex_2.json", "r"))
# Loading the third inverted index term -> documents, # tfidf
ThirdInvertedIndex = json.load(open("InvertedIndex_3.json", "r"))
# Loading the vocabulary file which maps each term to a specific ID
Vocabularies = json.load(open("Vocabulary.json", "r"))
# Compute the TFIDF of the query
QueryTFIDF = QueryToTfidf(SynopsisQuery, SecondInvertedIndex,Vocabularies, len(AllURLs))
# Take the documents that are containing all the words
RelatedDocuments = QueryToDocuemnts(QueryTFIDF.keys(), ThirdInvertedIndex)
# Compute the similarity of each document with query
DocumentsSimilarity = Similarity(list(QueryTFIDF.values()), deepcopy(RelatedDocuments))
# Here we will pick the similarity between our filtered data and given query
for doc in FilteredDocuments:
SimilarityOfDoc = DocumentsSimilarity.get(doc)
if SimilarityOfDoc:
FilteredDocuments[doc]['synopsisSimilarity'] = SimilarityOfDoc[-1]
return FilteredDocuments
```
After having all the filtered documents and checking their similarity with respect to the given query, we will now add new scores to each documents.
## Scoring
In the scoring part as we mentioned above, we will add new scores to each of the filtered documents.
### 3.2.1 Function Score and User
This function, given all the filtered documents will consider a new score name 'animeSUScore' which is the multiplication of each 'animeScore' and 'animeUser'. At the end we will normalize the values.
```
def RankUser(Docs):
# Pick the default values for max and min
Min, Max = float("inf"), 0
# For each document
for doc in Docs:
# Try to multiply animeScore and animeUser
try:
Docs[doc]['animeSUScore'] = float(Docs[doc]['animeScore']) * float(Docs[doc]['animeUser'])
# In case of an error we find out the values are missed or corrupted
except:
# Consider the result of the multiplication 0
Docs[doc]['animeSUScore'] = 0
# Update the min and max values
Min, Max = min(Min, Docs[doc]['animeSUScore']), max(Max, Docs[doc]['animeSUScore'])
# Normalize the values of animeSUScore
for doc in Docs:
Docs[doc]['animeSUScore'] = ( Docs[doc]['animeSUScore'] - Min)/(Max - Min)
```
### 3.2.2 Function Member Score
This function given all the filtered documents will normalize the number of members of each document and consider that as a new score.
```
def MemberScore(Docs):
# Setting the default values for min and max
Min, Max = float('inf'), 0
# For each document
for doc in Docs:
# Try to conver the value of animeMembers to float
try:
Docs[doc]['animeMembers'] = float(Docs[doc]['animeMembers'])
# If corrupted or missed
except:
# Set it to 0
Docs[doc]['animeMembers'] = 0
# Update the min and max
Min, Max = min(Min, Docs[doc]['animeMembers']), max(Max, Docs[doc]['animeMembers'])
# Normalize the value of memberScore
for doc in Docs:
Docs[doc]['memberScore'] = (Docs[doc]['animeMembers'] - Min)/(Max - Min)
```
### 3.2.3 Function Final Score
This function given all the documents will compute the final score of each document which will be the sum of all the scores we just defined and also the cosine similarity.
* **None:** As the cosine similarity between the query and the synopsis of the anime gives us more detail about the anime, we will give a coefficient of '3' to this value so that this value dominate the others.
```
def FinalScore(Docs):
# For each document we will compute the final score
for doc in Docs:
Docs[doc]['finalScore'] = Docs[doc]['memberScore'] + Docs[doc]['animeSUScore'] + 3 * Docs[doc]['synopsisSimilarity']
```
## 3.2.4 Main Score
This function will go over all the filtered documents and compute the socre of each of the documents and show the documents in order of their final score.
```
# We will give all the filtered documents to be scored
def Scoring(FilteredDocuments):
RankUser(FilteredDocuments)
MemberScore(FilteredDocuments)
FinalScore(FilteredDocuments)
return FilteredDocuments
```
## 3.3 Main Function Query to Documents
Here we take a query from the user and give back him the resulted documents with respect to the given query.
**Important: Don't forget to use the format of the query when you want to issue a query"**
1- {Anime Type} 2- {Anime released date} 3- {Anime end date} 4- {Words in synopsis}<br/><br/>
**FYI:** You can issue a subset of the parameters in the query.
```
# Processing the query and filter the related documents
Query = QueryProcess(input("Please enter your query here: "))
# Filtering documents based on the given parameters in the query
FilteredDocuments = Filtering(Query)
# Scoring the filtered documents
ScoredDocuments = Scoring(FilteredDocuments)
# Here we will store the details of each related documents
Data = []
for Res in ScoredDocuments:
Path = '/home/mehrdad/ADM-HW3/HTMLS/page'
FileInfo = open(Path + str(Res[0]) + '/anime_' + str(Res[1]) +'.tsv', mode = 'r')
Description = FileInfo.read().split('\n')[1].split('\t')[10]
Data.append([ScoredDocuments[Res]['animeTitle'], Description, ScoredDocuments[Res]['URL'],
ScoredDocuments[Res]['finalScore']])
Data = [Doc.docInfo for Doc in heapsort([Docs(i) for i in Data])]
# Setting the similarity to 2 float places
for doc in Data:
doc[-1] = "{:.2f}".format(doc[-1])
# Here we will pick the first K documents that are more similar with respect to the given query
DataToDataFrame(['animeTitle','animeDescription', 'Url', 'Final score'], Data[:10])
```
## 3.4 Comparing
In this section we will compare the results that we got from this search engine the previous search engine that we have been built in the section 2.2.
The search engine in part 3.3 is more powerful than the search engine in 2.2 due to these:
- Search engine in 3.3 gives the user the oppurtunity to use a kind of filtering based on the type, released data and the end date of the anime, while we didn't have this feature in search engine 2.2.
- Search engine in 3.3 for the resulted anime that have the same cosine similarity will with the help of the other information of the anime can sort the documents with respect to their popularity and rank. The ones that are better will be higher in the result.
- Search engine in 3.3 even if can not find any document that contains all the word given for the synopsis will give us the result based on the other parameters of filtering.
- If for a query in synopsis we have less than K related docuements, the search engine in 3.3 can give the result based on the other parameters of the filtering.
**In the end we discovered that our search engine in 3.3 works much better than the search engine in 2.2.**
# 5. Algorithmic question
## 5.1 Algorithm
Basically in this case we are trying to find the maximum of the elements of an array while these elements are not adjacent. Here we will explain how does our algorithm works.
We can solve this quetion with a greedy algorithm which solves this question with time complexity of O(n) as we can compute this value by iterating over the values just once. Here you can find the algorithm:
At each step, we will consider two sums. First the maximum sum up to this iteration with the previous element included and another sum which is the maximum sum up to this iteration without the previous element. We call these two sums as 1-SumWithPrevious, 2- SumWithoutPreviuos
1- We go through the elements.
2- As we assume that the previous element has been picked so we add the current element to the SumWithoutPrevious sum.
3- We check if this value (SumWithoutPrevious) is greater than the value of SumWithPrevious or not. If this was the case then we will swap these two values as for the next item we have picked its adjacent item.
4- If at some point the value of SumWithoutPrevious + the current element was not greater than SumWithPrevious, it means that with or without the current element we had the maximum sum so far. As we didn't include the element in the sums so we won't have a problem for the next item to be considered. Here we can assign the SumWithoutPrevios to SumWithPrevious.
5- At the end we will return the maximum of these two values, which will be store in SumWithPrevious.
**You can check a detailed example in 5.3 section.**
## 5.2 Implementation
```
def MaximumSumWithoutAdjacent(List):
# define two sums and necessary datastructures
SumWithoutPrevious, SumWithPrevious = 0, 0
# Showing the elements in the list
print('The elements in the list: ', List)
# Iterating over the elements
for i in List:
# Add the current value to the sum without previous
SumWithoutPrevious += i
# Check the condition
if SumWithoutPrevious > SumWithPrevious:
# As we gain more score by picking the current element so we swap the values.
SumWithoutPrevious, SumWithPrevious = SumWithPrevious, SumWithoutPrevious
# If by considering the current element, we don't gain more score
else:
# Up to this point we have the maximum score by not picking the previous element
SumWithoutPrevious = SumWithPrevious
# Showing the last result.
print('\nResult:')
print('\nMaximum sum without considering adjacent elements: \'', SumWithPrevious, '\'', sep = '')
```
### Give me an example here:
```
MyList = list(map(int, input("Please give me the elements of your list: ").split()))
MaximumSumWithoutAdjacent(MyList)
```
## 5.3 Steps of the algorithm
```
def MaximumSumWithoutAdjacentSteps(List):
# define two sums and necessary datastructures
SumWithoutPrevious, SumWithPrevious, NotPickLast = 0, 0, False
# To keep track the picked elements in each sum
WithPrevious, WithoutPrevious = [], []
# Showing the elements in the list
print('The elements in the list: ', List)
# Iterating over the elements
for Index, i in enumerate(List):
# To distinguish between the steps
print('-' * 50)
print('* Step '+str(Index+1)+' *\n')
# Explaining of the procedure
print('We are considering number \'', i, '\':', sep = '')
print('\nCurrent value of SumWithPrevious:', SumWithPrevious)
print('Current value of SumWithoutPrevious:', SumWithoutPrevious, end = '\n\n')
# Add the current value to the sum without previous
SumWithoutPrevious += i
print('Adding value \'', i, '\' to SumWithoutPrevious -> SumWithoutPrevious = ', SumWithoutPrevious, sep = '', end = '\n\n')
# Check the condition
if SumWithoutPrevious > SumWithPrevious:
# As we gain more score by picking the current element so we swap the values.
SumWithoutPrevious, SumWithPrevious = SumWithPrevious, SumWithoutPrevious
# If we didn't pick the previous element
if NotPickLast:
print('We didn\'t pick the previous element!!!')
# As we didn't pick the previous element, we add current value to with previous elements
WithPrevious.append(i)
# If we have considered the previous element
else:
# If this is not the first iteration
if Index:
print('Swap two lists!!!')
# Now we add current element to sumwithout previous set and swap two lists
WithoutPrevious.append(i)
WithPrevious, WithoutPrevious = WithoutPrevious[:], WithPrevious[:]
# Showing the values at the current iteration
print('--->> Pick the current element!!!')
print('\nSumWithoutPrevious is greater than SumWithPrevious -> Swap two maximum!')
print('SumWithPrevious = ', SumWithPrevious, ' SumWithoutPrevious = ', SumWithoutPrevious)
# We removed the previous element -> we didn't pick the previous element
NotPickLast = False
# If by considering the current element, we don't gain more score
else:
# Up to this point we have the maximum score by not picking the previous element
SumWithoutPrevious = SumWithPrevious
WithoutPrevious = WithPrevious[:]
# We are not picking the current element, so for next iteration we didn't pick the previous one.
NotPickLast = True
# Showing the details of what we did exactly
print('\n--->>Don\'t pick the element!!!')
print('\nSumWithoutPrevious is not greater than SumWithPrevious -> Both take maximum!')
print('SumWithPrevious = ', SumWithPrevious, ' SumWithoutPrevious = ', SumWithoutPrevious)
# Showing the picked element up to this point.
print('\nMaximum sum with current element: ', WithPrevious)
print('\nMaximum sum without current element: ', WithoutPrevious)
# Showing the last result.
print('\n***************')
print('Result:\n')
print('All elements:', List)
print('\nMaximum sum without considering adjacent elements: \'', SumWithPrevious, '\'', sep = '')
print('By picking these values: ', WithPrevious)
```
### Run the detailed function here.
```
MaximumSumWithoutAdjacentSteps(MyList)
```
| github_jupyter |
# Softmax exercise
*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*
This exercise is analogous to the SVM exercise. You will:
- implement a fully-vectorized **loss function** for the Softmax classifier
- implement the fully-vectorized expression for its **analytic gradient**
- **check your implementation** with numerical gradient
- use a validation set to **tune the learning rate and regularization** strength
- **optimize** the loss function with **SGD**
- **visualize** the final learned weights
```
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading extenrnal modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000, num_dev=500):
"""
Load the CIFAR-10 dataset from disk and perform preprocessing to prepare
it for the linear classifier. These are the same steps as we used for the
SVM, but condensed to a single function.
"""
# Load the raw CIFAR-10 data
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# subsample the data
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val = y_train[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
mask = np.random.choice(num_training, num_dev, replace=False)
X_dev = X_train[mask]
y_dev = y_train[mask]
# Preprocessing: reshape the image data into rows
X_train = np.reshape(X_train, (X_train.shape[0], -1))
X_val = np.reshape(X_val, (X_val.shape[0], -1))
X_test = np.reshape(X_test, (X_test.shape[0], -1))
X_dev = np.reshape(X_dev, (X_dev.shape[0], -1))
# Normalize the data: subtract the mean image
mean_image = np.mean(X_train, axis = 0)
X_train -= mean_image
X_val -= mean_image
X_test -= mean_image
X_dev -= mean_image
# add bias dimension and transform into columns
X_train = np.hstack([X_train, np.ones((X_train.shape[0], 1))])
X_val = np.hstack([X_val, np.ones((X_val.shape[0], 1))])
X_test = np.hstack([X_test, np.ones((X_test.shape[0], 1))])
X_dev = np.hstack([X_dev, np.ones((X_dev.shape[0], 1))])
return X_train, y_train, X_val, y_val, X_test, y_test, X_dev, y_dev
# Invoke the above function to get our data.
X_train, y_train, X_val, y_val, X_test, y_test, X_dev, y_dev = get_CIFAR10_data()
print 'Train data shape: ', X_train.shape
print 'Train labels shape: ', y_train.shape
print 'Validation data shape: ', X_val.shape
print 'Validation labels shape: ', y_val.shape
print 'Test data shape: ', X_test.shape
print 'Test labels shape: ', y_test.shape
print 'dev data shape: ', X_dev.shape
print 'dev labels shape: ', y_dev.shape
```
## Softmax Classifier
Your code for this section will all be written inside **cs231n/classifiers/softmax.py**.
```
# First implement the naive softmax loss function with nested loops.
# Open the file cs231n/classifiers/softmax.py and implement the
# softmax_loss_naive function.
from cs231n.classifiers.softmax import softmax_loss_naive
import time
# Generate a random softmax weight matrix and use it to compute the loss.
W = np.random.randn(3073, 10) * 0.0001
loss, grad = softmax_loss_naive(W, X_dev, y_dev, 0.0)
# As a rough sanity check, our loss should be something close to -log(0.1).
print 'loss: %f' % loss
print 'sanity check: %f' % (-np.log(0.1))
```
## Inline Question 1:
Why do we expect our loss to be close to -log(0.1)? Explain briefly.**
**Your answer:** *Fill this in*
```
# Complete the implementation of softmax_loss_naive and implement a (naive)
# version of the gradient that uses nested loops.
loss, grad = softmax_loss_naive(W, X_dev, y_dev, 0.0)
# As we did for the SVM, use numeric gradient checking as a debugging tool.
# The numeric gradient should be close to the analytic gradient.
from cs231n.gradient_check import grad_check_sparse
f = lambda w: softmax_loss_naive(w, X_dev, y_dev, 0.0)[0]
grad_numerical = grad_check_sparse(f, W, grad, 10)
# similar to SVM case, do another gradient check with regularization
loss, grad = softmax_loss_naive(W, X_dev, y_dev, 1e2)
f = lambda w: softmax_loss_naive(w, X_dev, y_dev, 1e2)[0]
grad_numerical = grad_check_sparse(f, W, grad, 10)
# Now that we have a naive implementation of the softmax loss function and its gradient,
# implement a vectorized version in softmax_loss_vectorized.
# The two versions should compute the same results, but the vectorized version should be
# much faster.
tic = time.time()
loss_naive, grad_naive = softmax_loss_naive(W, X_dev, y_dev, 0.00001)
toc = time.time()
print 'naive loss: %e computed in %fs' % (loss_naive, toc - tic)
from cs231n.classifiers.softmax import softmax_loss_vectorized
tic = time.time()
loss_vectorized, grad_vectorized = softmax_loss_vectorized(W, X_dev, y_dev, 0.00001)
toc = time.time()
print 'vectorized loss: %e computed in %fs' % (loss_vectorized, toc - tic)
# As we did for the SVM, we use the Frobenius norm to compare the two versions
# of the gradient.
grad_difference = np.linalg.norm(grad_naive - grad_vectorized, ord='fro')
print 'Loss difference: %f' % np.abs(loss_naive - loss_vectorized)
print 'Gradient difference: %f' % grad_difference
# Use the validation set to tune hyperparameters (regularization strength and
# learning rate). You should experiment with different ranges for the learning
# rates and regularization strengths; if you are careful you should be able to
# get a classification accuracy of over 0.35 on the validation set.
from cs231n.classifiers import Softmax
results = {}
best_val = -1
best_softmax = None
learning_rates = [1e-7, 5e-7]
regularization_strengths = [5e4, 1e8]
################################################################################
# TODO: #
# Use the validation set to set the learning rate and regularization strength. #
# This should be identical to the validation that you did for the SVM; save #
# the best trained softmax classifer in best_softmax. #
################################################################################
pass
################################################################################
# END OF YOUR CODE #
################################################################################
# Print out results.
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print 'lr %e reg %e train accuracy: %f val accuracy: %f' % (
lr, reg, train_accuracy, val_accuracy)
print 'best validation accuracy achieved during cross-validation: %f' % best_val
# evaluate on test set
# Evaluate the best softmax on test set
y_test_pred = best_softmax.predict(X_test)
test_accuracy = np.mean(y_test == y_test_pred)
print 'softmax on raw pixels final test set accuracy: %f' % (test_accuracy, )
# Visualize the learned weights for each class
w = best_softmax.W[:-1,:] # strip out the bias
w = w.reshape(32, 32, 3, 10)
w_min, w_max = np.min(w), np.max(w)
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
for i in xrange(10):
plt.subplot(2, 5, i + 1)
# Rescale the weights to be between 0 and 255
wimg = 255.0 * (w[:, :, :, i].squeeze() - w_min) / (w_max - w_min)
plt.imshow(wimg.astype('uint8'))
plt.axis('off')
plt.title(classes[i])
```
| github_jupyter |
# Constructing the musical scale
So far we have discovered two important facts about how we hear and interpret musical notes. We will call them axioms because they are fundamental to our task of constructing the music scale.
**Axiom 1** The ear compares different frequencies *multiplicatively* rather than *additively*
**Axiom 2** Two notes of different frequency sound “good” together when the ratio of their frequencies can be expressed as a quotient of two small integers.
Okay––let’s construct a musical scale. Now what do I mean by that? Recall that a note is a certain frequency of oscillation. There are an infinite number of possible frequencies available, so we need to pick out a certain finite subset and agree that these will be the notes to “use” (tune our instruments to) when we play music. But which ones shall we pick and what properties do we want the scale to have?
There are lots of ways to make a scale, in fact different solutions have been adopted by cultures througout history. The system we use now has dominated Western culture for 500 years, and that suggests that it might just have something going for it.
In this system we’ve grouped notes into octaves each with 12 notes, and the frequencies in each octave are twice those in the previous octave. In the table of frequencies generated by the code below, each row is an octave.
```
import pandas as pd
noteList = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
def generateOctave(note, startingFrequency):
frequencyList = [startingFrequency]
for x in range(1,9):
frequencyList.append(startingFrequency * 2**x)
frequencyDf = pd.DataFrame({note:frequencyList})
return frequencyDf
df = pd.DataFrame() # create an empty dataframe
for n, note in enumerate(noteList, start=1):
startingFrequency = 2**(n/12) * 15.434 # calculate the new note's frequency
frequencyDf = generateOctave(note, startingFrequency)
df = pd.concat([df, frequencyDf], axis=1) # join the new column to the dataframe
df.style.set_precision(4) # display the dataframe with 4 significant figures
```
What patterns do you see in the frequency table?
Out of all the possible alternatives for designing a scale, why did we choose to base it on 12? As a hint, it has something to do with factors and simple ratios.
We can reword the axioms above as:
1. *Homogeneity* - No matter where we are in the scale, adjacent notes should have the same frequency ratio.
2. *Nice combinations* - The scale should have lots of pairs of notes with frequencies in the ratio of small integers.
Looking at the second axiom, the simplest ratio of integers is 1:2. If we play a note and then a note with double the frequency, they sound like different versions of the same note. So we give them the same letter name, for example $A_4$ is 440 Hz and $A_5$ is 880 Hz. We say these two notes are an [octave](https://en.wikipedia.org/wiki/Octave) apart.
```
from numpy import linspace, pi, sin
from IPython.display import Audio, display
import time
f1 = 440
f2 = 880
sampleRate = 32000
duration = 0.5
t = linspace(0, duration, int(sampleRate * duration))
display(Audio(sin(f1 * 2 * pi * t), rate = sampleRate, autoplay = True))
time.sleep(1)
display(Audio(sin(f2 * 2 * pi * t), rate = sampleRate, autoplay = True))
```
The question is, how many notes (frequencies) should we include in an octave? We know from axiom 1 that the frequencies of successive notes should be equally spaced multiplicatively. We also know from axiom 2 that we should get a note that is twice the frequency of the first.
This means that we must choose some ratio of frequencies, $r$, to an integer exponent, $n$, that results in 2. We can write that as $r^n=2$ where $n$ will be the number of notes in an octave.
The equation $r^n=2$ contains two unknowns though. Rather than trying to find a value for $r$, it will be easier to find a value for $n$ because we know it is an integer.
## The search for $n$
So let’s look for $n$, the number of notes in an octave. This is not so hard to do as we know that it has to be an integer and it can’t be too small or too large.
If it were small, like around 5, we wouldn’t have enough notes in an octave to give us interesting music, and if it were too large, like 20, we might well have more notes than we could cope with, both conceptually and mechanically.
We will judge $n$ to be "good" if we get lots of small integer ratios.
For example, if we take $n=10$ then the 10 notes in an octave will be: $r^0=1$, $r^1$, $r^2$... $r^{10}=2$.
Actually there are 11 notes in that list, but we usually take the last one, $r^n=2$, to be the start of the next octave.
Since we know that $r^{10}=2$, then $r=2^{1/10} \approx 1.0718$ means that the first ratio of notes is about 1:1.0718.
Each successive note will be equally spaced multiplicatively, so:
$r^0 = (2^{1/10})^0 = 1$
$r^1 = (2^{1/10})^1 \approx 1.0718$
...
$r^10 = (2^{1/10})^{10} = 2$
Which means in general $r^i = (2^{1/n})^i = 2^{i/n}$
Now that we know $r^i = 2^{i/n}$, let's try some different values for $n$:
```
valuesToCheck = range(4, 17) # we'll check values from 4 to 16
def generateFrequencyList(n):
frequencyList = [1.0] # start a new list with 1.0
for i in range(1,n+1): # iterate integers from 1 to n
f = 2**(i/n) # calculate the frequency value
frequencyList.append(f)
return frequencyList
df = pd.DataFrame() # create an empty dataframe
for n in valuesToCheck:
frequencyList = generateFrequencyList(n)
frequencyDf = pd.DataFrame({'n = '+str(n): frequencyList}) # make a dataframe from the list
df = pd.concat([df, frequencyDf], axis=1) # join the new dataframe to our existing one
df.fillna(value='', inplace=True) # replace all of the NaN values with blanks
pd.options.display.float_format = '{:,.3f}'.format # display values to 3 decimals
df # display the dataframe
```
That table shows us the decimal representations of the frequencies in an octave with $n$ equal to the number of notes.
So what makes on $n$ better than another? Axiom 2 tells us that we want lots of small integer ratios in our pairs of notes. That means that whatever colun we select shoul have a good supply of fractions like $\frac{3}{2}$, $\frac{4}{3}$, $\frac{5}{3}$, $\frac{5}{4}$, $\frac{7}{4}$, etc.
First the bad news, the numbers $2^{i/n}$ will always be irrational and will *never* contain integer ratios (small or otherwise). This is a fascinating set of ideas in itself, and is pursued in problem 6.
But now for the good news, the ear can’t actually distinguish tiny variations in frequency so it’s good enough to be very close to lots of small integer ratios. And from the JND table of the last section, “very close” in the case of frequency discrimination means around half a percent. So let’s re-reformulate axiom 2:
2. *Nice combinations* - The scale should have lots of pairs of notes with frequencies within half a percent of small-integer ratios.
Go on to [15.3b-Looking-for-a-good-ratio.ipynb](./15.3b-Looking-for-a-good-ratio.ipynb)
| github_jupyter |
# Poisson Regression, Gradient Descent
In this notebook, we will show how to use gradient descent to solve a [Poisson regression model](https://en.wikipedia.org/wiki/Poisson_regression). A Poisson regression model takes on the following form.
$\operatorname{E}(Y\mid\mathbf{x})=e^{\boldsymbol{\theta}' \mathbf{x}}$
where
* $x$ is a vector of input values
* $\theta$ is a vector weights (the coefficients)
* $y$ is the expected value of the parameter for a [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution), typically, denoted as $\lambda$
Note that [Scikit-Learn](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.linear_model) does not provide a solver a Poisson regression model, but [statsmodels](http://www.statsmodels.org/dev/generated/statsmodels.discrete.discrete_model.Poisson.html) does, though examples for the latter is [thin](https://datascience.stackexchange.com/questions/23143/poisson-regression-options-in-python).
## Simulate data
Now, let's simulate the data. Note that the coefficients are $[1, 0.5, 0.2]$ and that there is error $\epsilon \sim \mathcal{N}(0, 1)$ added to the simulated data.
$y=e^{1 + 0.5x_1 + 0.2x_2 + \epsilon}$
In this notebook, the score is denoted as $z$ and $z = 1 + 0.5x_1 + 0.2x_2 + \epsilon$. Additionally, $y$ is the mean for a Poisson distribution. The variables $X_1$ and $X_2$ are independently sampled from their own normal distribution $\mathcal{N}(0, 1)$.
After we simulate the data, we will plot the distribution of the scores and means. Note that the expected value of the output $y$ is 5.2.
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from numpy.random import normal
from scipy.stats import poisson
np.random.seed(37)
sns.set(color_codes=True)
n = 10000
X = np.hstack([
np.array([1 for _ in range(n)]).reshape(n, 1),
normal(0.0, 1.0, n).reshape(n, 1),
normal(0.0, 1.0, n).reshape(n, 1)
])
z = np.dot(X, np.array([1.0, 0.5, 0.2])) + normal(0.0, 1.0, n)
y = np.exp(z)
```
## Visualize data
```
fig, ax = plt.subplots(1, 2, figsize=(20, 5))
sns.kdeplot(z, ax=ax[0])
ax[0].set_title(r'Distribution of Scores')
ax[0].set_xlabel('score')
ax[0].set_ylabel('probability')
sns.kdeplot(y, ax=ax[1])
ax[1].set_title(r'Distribution of Means')
ax[1].set_xlabel('mean')
ax[1].set_ylabel('probability')
```
## Solve for the Poisson regression model weights
Now we learn the weights of the Poisson regression model using gradient descent. Notice that the loss function of a Poisson regression model is identical to an Ordinary Least Square (OLS) regression model?
$L(\theta) = \frac{1}{n} (\hat{y} - y)^2$
We do not have to worry about writing out the gradient of the loss function since we are using [Autograd](https://github.com/HIPS/autograd).
```
import autograd.numpy as np
from autograd import grad
from autograd.numpy import exp, log, sqrt
# define the loss function
def loss(w, X, y):
y_pred = np.exp(np.dot(X, w))
loss = ((y_pred - y) ** 2.0)
return loss.mean(axis=None)
#the magic line that gives you the gradient of the loss function
loss_grad = grad(loss)
def learn_weights(X, y, alpha=0.05, max_iter=30000, debug=False):
w = np.array([0.0 for _ in range(X.shape[1])])
if debug is True:
print('initial weights = {}'.format(w))
loss_trace = []
weight_trace = []
for i in range(max_iter):
loss = loss_grad(w, X, y)
w = w - (loss * alpha)
if i % 2000 == 0 and debug is True:
print('{}: loss = {}, weights = {}'.format(i, loss, w))
loss_trace.append(loss)
weight_trace.append(w)
if debug is True:
print('intercept + weights: {}'.format(w))
loss_trace = np.array(loss_trace)
weight_trace = np.array(weight_trace)
return w, loss_trace, weight_trace
def plot_traces(w, loss_trace, weight_trace, alpha):
fig, ax = plt.subplots(1, 2, figsize=(20, 5))
ax[0].set_title(r'Log-loss of the weights over iterations, $\alpha=${}'.format(alpha))
ax[0].set_xlabel('iteration')
ax[0].set_ylabel('log-loss')
ax[0].plot(loss_trace[:, 0], label=r'$\beta$')
ax[0].plot(loss_trace[:, 1], label=r'$x_0$')
ax[0].plot(loss_trace[:, 2], label=r'$x_1$')
ax[0].legend()
ax[1].set_title(r'Weight learning over iterations, $\alpha=${}'.format(alpha))
ax[1].set_xlabel('iteration')
ax[1].set_ylabel('weight')
ax[1].plot(weight_trace[:, 0], label=r'$\beta={:.2f}$'.format(w[0]))
ax[1].plot(weight_trace[:, 1], label=r'$x_0={:.2f}$'.format(w[1]))
ax[1].plot(weight_trace[:, 2], label=r'$x_1={:.2f}$'.format(w[2]))
ax[1].legend()
```
We try learning the coefficients with different learning weights $\alpha$. Note the behavior of the traces of the loss and weights for different $\alpha$? The loss function was the same one used for OLS regression, but the loss function for Poisson regression is defined differently. Nevertheless, we still get acceptable results.
### Use gradient descent with $\alpha=0.001$
```
alpha = 0.001
w, loss_trace, weight_trace = learn_weights(X, y, alpha=alpha, max_iter=1000)
plot_traces(w, loss_trace, weight_trace, alpha=alpha)
print(w)
```
### Use gradient descent with $\alpha=0.005$
```
alpha = 0.005
w, loss_trace, weight_trace = learn_weights(X, y, alpha=alpha, max_iter=200)
plot_traces(w, loss_trace, weight_trace, alpha=alpha)
print(w)
```
### Use gradient descent with $\alpha=0.01$
```
alpha = 0.01
w, loss_trace, weight_trace = learn_weights(X, y, alpha=alpha, max_iter=200)
plot_traces(w, loss_trace, weight_trace, alpha=alpha)
print(w)
```
| github_jupyter |
# Unwetter Simulator
```
import os
os.chdir('..')
f'Working directory: {os.getcwd()}'
from unwetter import db, map
from datetime import datetime
from unwetter import config
config.SEVERITY_FILTER = ['Severe', 'Extreme']
config.STATES_FILTER = ['NW']
config.URGENCY_FILTER = ['Immediate']
severities = {
'Minor': 'Wetterwarnung',
'Moderate': 'Markante Wetterwarnung',
'Severe': '🔴 Amtliche Unwetterwarnung',
'Extreme': '🔴 Amtliche Extreme Unwetterwarnung',
}
search_start = datetime(2019, 6, 19, 11, 0)
search_end = datetime(2019, 6, 19, 22, 0)
search_filter = {
'$and': [
{
'sent': {
'$gt': search_start,
},
},
{
'sent': {
'$lt': search_end,
},
},
]
}
events = list(db.collection.find(search_filter).sort([('sent', 1)]))
len(events)
len([e for e in events if e['published']])
for e in events:
e['published'] = False
def mock_by_ids(ids):
return [event for event in events if event['id'] in ids]
def mock_publish(ids):
for event in events:
if event['id'] in ids:
event['published'] = True
from unwetter.dwd import special_type
def mock_has_changes(event, old_events):
if not any(t['published'] for t in old_events):
extended_references = set()
extended_references.update(event.get('extended_references', event['references']))
for old_event in old_events:
if 'extended_references' in old_event:
extended_references.update(old_event['extended_references'])
elif 'references' in old_event:
extended_references.update(old_event['references'])
event['extended_references'] = sorted(extended_references, reverse=True)
old_events = mock_by_ids(extended_references)
event['has_changes'] = [
{
'id': old_event['id'],
'changed': mock_changes(event, old_event),
'published': old_event['published'],
}
for old_event in old_events
]
event['special_type'] = special_type(event, old_events)
return event
from datetime import datetime, timedelta
from unwetter.generate.blocks import expires, district_list, state_for_cell_id, region_list, dates
from unwetter.generate.helpers import upper_first, local_time
STATES_FILTER = config.STATES_FILTER
def mock_changes_old(event, old_event):
"""
Generate a list of changes between two events
:param event:
:param old_event:
:return: str
"""
text = ''
simple_fields = {
'severity': 'Warnstufe',
'event': 'Wetterphänomen',
'certainty': 'Wahrscheinlichkeit',
}
for field in simple_fields:
if old_event.get(field) != event.get(field):
if field == 'severity' and event[field] in ['Minor', 'Moderate']:
text += f'{simple_fields[field]}: Herabstufung auf {severities[event[field]]}\n\n'
elif field == 'severity':
text += f'{simple_fields[field]}: {severities[event[field]]} ' \
f'(zuvor "{severities[old_event[field]]}")\n\n'
else:
text += f'{simple_fields[field]}: {event[field]} ' \
f'(zuvor "{old_event.get(field, "Nicht angegeben")}")\n\n'
# Editorial request to check only, if expires time changed, since every update has new onset-time
if abs(event['onset'] - event['sent']) > timedelta(minutes=2) and dates(old_event) != dates(event):
text += f'Gültigkeit: {dates(event)} (zuvor "{dates(old_event)}")\n\n'
elif expires(old_event) != expires(event):
text += f'Ende der Gültigkeit: {expires(event)} (zuvor "{expires(old_event)}")\n\n'
if district_list(old_event) != district_list(event):
districts_now = {
district['name'] for district in event['districts']
if state_for_cell_id(district['warn_cell_id']) in STATES_FILTER
}
districts_before = {
district['name'] for district in old_event['districts']
if state_for_cell_id(district['warn_cell_id']) in STATES_FILTER
}
added = districts_now - districts_before
removed = districts_before - districts_now
if added:
text += f'Neue Kreise/Städte: {", ".join(sorted(added))}\n'
if removed:
text += f'Nicht mehr betroffene Kreise/Städte: {", ".join(sorted(removed))}\n'
if region_list(old_event) != region_list(event):
text += f'Regionale Zuordnung: {upper_first(region_list(event))} ' \
f'(zuvor: "{upper_first(region_list(old_event))}")\n\n'
else:
text += f'Regionale Zuordnung unverändert: {upper_first(region_list(event))}\n\n'
'''
# Editorial choice --> No relevant information due to relatively small area --> Thus, no update
elif commune_list(old_event) != commune_list(event):
text += 'Regionale Zuordnung: Änderung der betroffenen Gemeinden\n\n'
'''
return text
from datetime import datetime, timedelta
import re
STATES_FILTER = config.STATES_FILTER
def mock_changes(event, old_event):
"""
Generate a list of changes between two events
:param event:
:param old_event:
:return: bool
"""
if any(event.get(field) != old_event.get(field) for field in ['severity', 'certainty']):
return True
# Notify about big hail sizes
if 'Hagel' not in event['parameters']:
if event['event'] != old_event['event'].replace(' und HAGEL', ''):
return True
else:
hail_re = r'^.*?(\d+).*?cm'
hail_size_now = int(re.match(hail_re, event['parameters']['Hagel']).group(1))
hail_size_before = int(re.match(hail_re, old_event['parameters'].get('Hagel', '0 cm')).group(1))
if hail_size_now >= 3 and hail_size_before < 3:
return True
else:
if event['event'].replace(' und HAGEL', '') != old_event['event'].replace(' und HAGEL', ''):
return True
if abs(event['onset'] - event['sent']) > timedelta(minutes=2) and event['sent'] - event['onset'] < timedelta(minutes=2) and old_event['onset'] != event['onset']:
return True
elif old_event['expires'] != event['expires']:
return True
if len(set(r[0] for r in event['regions']) - set(r[0] for r in old_event['regions'])) > 0:
return True
districts_now = {
district['name'] for district in event['districts']
if state_for_cell_id(district['warn_cell_id']) in STATES_FILTER
}
districts_before = {
district['name'] for district in old_event['districts']
if state_for_cell_id(district['warn_cell_id']) in STATES_FILTER
}
added = districts_now - districts_before
if len(districts_before) <= 3 and added:
return True
return False
from unwetter.config import filter_event
def mock_update(new_events):
filtered = []
for event in new_events:
if filter_event(event):
if event['msg_type'] in ['Alert', 'Cancel']:
filtered.append(event)
elif any(t['changed'] and t['published'] for t in event['has_changes']):
filtered.append(event)
elif event['special_type'] == 'UpdateAlert':
filtered.append(event)
elif not any(t['changed'] and t['published'] for t in event['has_changes']):
continue
else:
print(f'Event was not filtered 1: {event["id"]}')
mock_publish([event['id'] for event in filtered])
return filtered
from unwetter.generate.blocks import changes
current_sent = events[0]['sent']
bins = []
current_bin = []
for event in events:
if event['sent'] != current_sent:
current_sent = event['sent']
bins.append(current_bin)
current_bin = []
current_bin.append(event)
bins.append(current_bin)
processed = []
for bin in bins:
for event in bin:
if 'references' in event:
old_events = mock_by_ids(event.get('extended_references', event['references']))
mock_has_changes(event, old_events)
processed.append(mock_update(bin))
sum(len(bin) for bin in processed)
[print(event['event'], event['sent'] + timedelta(hours=2), event.get('special_type'), event['id']) for bin in processed for event in bin]
```
| github_jupyter |
# MLI BYOR: Custom Explainers
This notebook is a demo of MLI **bring your own explainer recipe** (BYOR) Python API.
**Ad-hoc OOTB and/or custom explainer run** scenario:
* **Upload** interpretation recipe.
* Determine recipe upload job **status**.
* **Run** ad-hoc recipe run job.
* Determine ad-hoc recipe job **status**.
* **Get** explainer type for given job.
* **List** explanation types for given explainer run.
* **List** explanation representations (formats) URLs for given explanation type.
* **Download** explanation representation from ^ URL.
* **Download** interpretation recipe job result **data**.
**Interpretation explainers run** scenario:
* **List** available/compatible explainers.
* **Choose** subset or all ^ compatible explainers.
* **Run** interpretation job.
* Determine **status** of interpretation job.
* Determine **status** per explainer job (running within the scope of interpretation).
* **List** explainer types which were ran within interpretation.
* **List** explainer runs for given explainer type within the interpretation.
* **List** explanation types for given explainer run.
* **List** explanation representations (formats) URLs for given explanation type.
* **Download** explanation representation from ^ URL.
### Virtual Environment and Dependencies
Prepare and activate virtual environment for this notebook by running:
```
. .env/bin/activate
pip install ipykernel
ipython kernel install --user --name=dai
```
```
import os
import pprint
import time
from random import randint
from h2oaicore.mli.oss.commons import MimeType, MliJobStatus
from h2oaicore.messages import (
CommonDaiExplainerParameters,
CommonExplainerParameters,
DatasetReference,
Explainer,
ExplainerDescriptor,
ExplainerJobStatus,
ExplainerRunJob,
ExplainersRunJob,
InterpretationJob,
ModelReference,
)
import h2o
import h2oai_client
from h2oai_client import Client
```
**Connect** to DAI server:
```
# connect to Driverless AI server - make sure to use the same
# user name and password as when signing in through the GUI
hostname = '127.0.0.1'
address = 'http://' + hostname + ':12345'
username = 'h2oai'
password = 'h2oai'
# h2oai = Client("http://localhost:12345", "h2oai", "h2oai")
h2oai = Client(address = address, username = username, password = password)
```
# Upload
Upload BYOR interpretation [recipe](http://192.168.59.141/mli-byor/mli_byor_foo.py) to Driverless AI server.
```
# URL of the recipe to upload
# Custom Morris sensitivity analysis
URL_BYOR_EXPLAINER = "https://h2o-public-test-data.s3.amazonaws.com/recipes/explainers/morris_sensitivity_explainer.py"
BYOR_EXPLAINER_NAME = "Morris Sensitivity Analysis"
```
**Upload recipe** to DAI server:
```
recipe_job_key = h2oai.create_custom_recipe_from_url(URL_BYOR_EXPLAINER)
recipe_job_key
recipe_job = h2oai._wait_for_recipe_load(recipe_job_key)
pprint.pprint(recipe_job.dump())
if recipe_job.entity.explainers:
uploaded_explainer_id:str = recipe_job.entity.explainers[0].id
else:
# explainer already deployed (look it up)
explainers = h2oai.list_explainers(
experiment_types=None,
explanation_scopes=None,
dai_model_key=None,
keywords=None,
explainer_filter=[]
)
uploaded_explainer_id = [explainer.id for explainer in explainers if BYOR_EXPLAINER_NAME == explainer.name][0]
print(f"Uploaded recipe ID: {uploaded_explainer_id}'")
```
Driverless AI **model** and **dataset**:
```
# *) hardcoded DAI keys
# DATASET_KEY = "f12f69b4-475b-11ea-bf67-9cb6d06b189b"
# MODEL_KEY = "f268e364-475b-11ea-bf67-9cb6d06b189b"
# *) lookup compatible DAI keys
compatible_models = h2oai.list_explainable_models(
explainer_id=uploaded_explainer_id, offset=0, size=30
)
if compatible_models.models:
MODEL_KEY = compatible_models.models[0].key
DATASET_KEY = compatible_models.models[0].parameters.dataset.key
else:
raise RuntimeError("No compatible models found: please train an IID regression/binomial experiment")
target_col = h2oai.get_model_summary(key=MODEL_KEY).parameters.target_col
print(f"Model : {MODEL_KEY}\nDataset: {DATASET_KEY}\nTarget : {target_col}")
```
# List Explainers
List custom and OOTB recipes.
```
# list available server recipes
explainers = h2oai.list_explainers(
experiment_types=None,
explanation_scopes=None,
dai_model_key=None,
keywords=None,
explainer_filter=[]
)
for e in explainers:
pprint.pprint(e.dump())
# list server recipes for given experiment type
explainers = h2oai.list_explainers(
experiment_types=["binomial"],
explanation_scopes=None,
dai_model_key=None,
keywords=None,
explainer_filter=[]
)
for e in explainers:
pprint.pprint(e.dump())
# list server recipes compatible with given DAI model
explainers = h2oai.list_explainers(
dai_model_key=MODEL_KEY,
experiment_types=None,
explanation_scopes=None,
keywords=None,
explainer_filter=[]
)
for e in explainers:
pprint.pprint(e.dump())
```
# Ad-hoc Run of Built-in Explainer Recipe
Run OOTB explainer recipe shipped w/ DAI server:
```
sa_explainer_id = [explainer.id for explainer in explainers if "SA explainer" == explainer.name][0]
sa_explainer_id
# prepare explaination parameters
explanation_params=Client.build_common_dai_explainer_params(
target_col=target_col,
model_key=MODEL_KEY,
dataset_key=DATASET_KEY,
)
explanation_params.dump()
# run explainer
explainer_id = sa_explainer_id
print(f"Running OOTB explainer: {explainer_id}")
run_job = h2oai.run_explainers(
explainers=[Explainer(
explainer_id=explainer_id,
explainer_params="",
)],
params=explanation_params,
)
run_job.dump()
# wait for explainer to finish
explainer_job_statuses = h2oai.wait_for_explainers(run_job.mli_key)
for job_status in explainer_job_statuses:
pprint.pprint(job_status.dump())
mli_key = job_status.mli_key
explainer_job_key = job_status.explainer_job_key
explainer_job = job_status.explainer_job
```
## Get Recipe Result
```
# get recipe result FORMATS/TYPES (representations of recipe output)
explainer_job.entity.can_explain
explainer_job.entity.explanation_scopes
for explanation in explainer_job.entity.explanations: pprint.pprint(explanation.dump())
# choose the most suitable format (if more than one) and get the result
BASE_URL = f"{address}/files/"
for explanation in explainer_job.entity.explanations:
for e_format in explanation.formats:
server_path: str = h2oai.get_explainer_result_url_path(
mli_key=mli_key,
explainer_job_key=explainer_job_key,
explanation_type=explanation.explanation_type,
explanation_format=e_format
)
print(f"Explanation {explanation.explanation_type}:\n {e_format}:\n {BASE_URL}{server_path}")
download_dir = "/tmp"
h2oai.download(server_path, download_dir)
!ls -l {download_dir}/explanation.zip
```
URL from above can be used to **download** choosen recipe result representation. Explainer log can be downloaded from:
```
server_path = h2oai.get_explainer_run_log_url_path(
mli_key=mli_key,
explainer_job_key=explainer_job_key,
)
print(f"{BASE_URL}{server_path}")
```
# Ad-hoc Run of Custom Explainer Recipe
Running previously uploaded custom explainer.
```
# run custom explainer - use previously uploaded recipe ID
if uploaded_explainer_id:
explainer_id = uploaded_explainer_id
else:
# explainer has been uploaded before
explainers = h2oai.list_explainers(
time_series=False,
dai_model_key=MODEL_KEY,
experiment_types=None,
explanation_scopes=None,
keywords=None,
)
for e in explainers:
if e.name == BYOR_EXPLAINER_NAME:
explainer_id = e.id
print(f"Running CUSTOM explainer: {explainer_id}")
run_job = h2oai.run_explainers(
explainers=[
Explainer(explainer_id=explainer_id, explainer_params=None)
],
params=Client.build_common_dai_explainer_params(
target_col=target_col,
model_key=MODEL_KEY,
dataset_key=DATASET_KEY,
),
)
run_job.dump()
# wait for explainer to finish
explainer_job_statuses = h2oai.wait_for_explainers(run_job.mli_key)
for job_status in explainer_job_statuses:
pprint.pprint(job_status.dump())
server_path = h2oai.get_explainer_result_url_path(
mli_key=job_status.mli_key,
explainer_job_key=job_status.explainer_job_key,
explanation_type='global-feature-importance',
explanation_format='application/json'
)
print(f"{BASE_URL}{server_path}")
```
URL from above can be used to **download** choosen **custom** recipe result representation.
# Explain (Model) with All Compatible or Selected Explainers
```
# get IDs of previously listed recipes
explainer_ids = [explainer.id for explainer in explainers]
explainer_ids
# run explainers: list of IDs OR empty list
# - empty explainer IDs list means "run all model COMPATIBLE explainers with default parameters")
print(f"All explainers:\n{explainer_ids}")
run_job: ExplainersRunJob = h2oai.run_explainers(
explainers=[],
params=Client.build_common_dai_explainer_params(
target_col=target_col,
model_key=MODEL_KEY,
dataset_key=DATASET_KEY,
),
)
run_job.dump()
# check interpretation job status (legacy RPC API)
i_job: InterpretationJob = h2oai.get_interpretation_job(run_job.mli_key)
# note per-explainer (subtask) ID and display name
i_job.dump()
# check particular sub-job status (existing RPC API reused)
h2oai.get_explainer_job_status(run_job.mli_key, run_job.explainer_job_keys[0]).dump()
# check sub-jobs statuses (existing RPC API reused)
job_statuses = h2oai.get_explainer_job_statuses(run_job.mli_key, run_job.explainer_job_keys)
for js in job_statuses:
pprint.pprint(js.dump())
# wait for ALL explainers to finish
explainer_statuses=h2oai.wait_for_explainers(run_job.mli_key)
explainer_statuses
# download explanation type in desired format
DOWNLOAD_DIR = f"/tmp/interpretation_run_{randint(0,1_000_000)}"
explainer_job_key = explainer_statuses[0].explainer_job_key
explanations = h2oai.list_explainer_results(explainer_job_key=explainer_job_key).explanations
# explanations
for explanation in explanations:
# explantion's formats
for explanation_format in explanation.formats:
# format's URL
result_path: str = h2oai.get_explainer_result_url_path(
mli_key=run_job.mli_key,
explainer_job_key=explainer_job_key,
explanation_type=explanation.explanation_type,
explanation_format=explanation_format,
)
# where to download
EXPLANATION_DIR = f"{DOWNLOAD_DIR}/explanation_{randint(0,1_000_000)}"
os.makedirs(EXPLANATION_DIR, exist_ok=True)
# download
h2oai.download(result_path, EXPLANATION_DIR)
print(
f"Explanation {explanation.explanation_type}:\n"
f" {explanation_format}:\n"
f" {BASE_URL}{result_path}"
)
print(f"\nDownloaded explanations in {DOWNLOAD_DIR}:")
!ls -l {DOWNLOAD_DIR}
```
| github_jupyter |
```
from sklearn import datasets
from sklearn.cross_validation import cross_val_score, train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression,LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import VotingClassifier
import pandas as pd
import warnings
import numpy as np
from sklearn.model_selection import RepeatedKFold
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
warnings.filterwarnings('ignore')
df = pd.read_csv("Replaced.csv", encoding='ISO-8859-1')
df.didPurchase = (df.didPurchase)*1
df.doRecommend = (df.doRecommend)*1
df['doRecommend'] = df['doRecommend'].fillna(1)
df['didPurchase'] = df['didPurchase'].fillna(1)
```
## Voting Classifier Ensemble
```
X=df[['didPurchase','rating']]
y=df['doRecommend']
clf1 = LogisticRegression(random_state=1)
clf2 = RandomForestClassifier(random_state=1)
clf3 = GaussianNB()
clf4 = KNeighborsClassifier(n_neighbors=10)
eclf = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2), ('gnb', clf3),('knn',clf4)], voting='hard')
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=None)
eclf.fit(X_train, y_train)
eclf.score( X_test, y_test)
```
Voting classifier gives an accuracy of 95%
```
for clf, label in zip([clf1, clf2, clf3,clf4, eclf], ['Logistic Regression', 'Random Forest', 'naive Bayes', 'KNN','Ensemble']):
scores = cross_val_score(clf, X, y, cv=20, scoring='accuracy')
print("Accuracy: %0.3f (+/- %0.3f) [%s]" % (scores.mean(), scores.std(), label))
```
***
# Staked Ensemble
```
training, valid, ytraining, yvalid = train_test_split(X_train, y_train, test_size=0.3, random_state=0)
clf2.fit(training,ytraining)
clf4.fit(training,ytraining)
preds1=clf2.predict(valid)
preds2=clf4.predict(valid)
test_preds1=clf2.predict(X_test)
test_preds2=clf4.predict(X_test)
stacked_predictions=np.column_stack((preds1,preds2))
stacked_test_predictions=np.column_stack((test_preds1,test_preds2))
meta_model=LinearRegression()
meta_model.fit(stacked_predictions,yvalid)
final_predictions=meta_model.predict(stacked_test_predictions)
count=[];
y_list=y_test.tolist()
for i in range(len(y_list)):
if (y_list[i]==np.round(final_predictions[i])):
count.append("Correct")
else:
count.append("Incorrect")
import seaborn as sns
sns.countplot(x=count)
accuracy_score(y_test,np.round(final_predictions))
```
***
## Stacked Ensemble with Cross validation
```
def fit_stack(clf, training, valid, ytraining,X_test,stacked_predictions,stacked_test_predictions):
clf.fit(training,ytraining)
preds=clf.predict(valid)
test_preds=clf.predict(X_test)
stacked_predictions=np.append(stacked_predictions,preds)
stacked_test_predictions=np.append(stacked_test_predictions,test_preds)
return {'pred':stacked_predictions,'test':stacked_test_predictions}
def stacked():
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=None)
training, valid, ytraining, yvalid = train_test_split(X_train, y_train, test_size=0.3, random_state=None)
#kf = RepeatedKFold(n_splits=5, n_repeats=5, random_state=None)
#for train_index, test_index in kf.split(X):
# training, valid = X.iloc[train_index], X.iloc[test_index]
# ytraining, yvalid = y.iloc[train_index], y.iloc[test_index]
clf2.fit(training,ytraining)
clf4.fit(training,ytraining)
preds1=clf2.predict(valid)
preds2=clf4.predict(valid)
test_preds1=clf2.predict(X_test)
test_preds2=clf4.predict(X_test)
stacked_predictions=np.column_stack((preds1,preds2))
stacked_test_predictions=np.column_stack((test_preds1,test_preds2))
#print(stacked_predictions.shape)
#print(stacked_test_predictions.shape)
meta_model=KNeighborsClassifier(n_neighbors=10)
meta_model.fit(stacked_predictions,yvalid)
final_predictions=meta_model.predict(stacked_test_predictions)
return accuracy_score(y_test,final_predictions)
accuracies=[]
for i in range(10):
accuracies.append(stacked())
print("%0.3f" % accuracies[i])
print(accuracies)
mean_acc=sum(accuracies) / float(len(accuracies))
print("Mean %0.3f" % mean_acc)
```
### Repeated KFold with X and y
```
accuracies=[]
def stacked2():
from sklearn.metrics import accuracy_score
#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=None)
#training, valid, ytraining, yvalid = train_test_split(X_train, y_train, test_size=0.3, random_state=None)
kf = RepeatedKFold(n_splits=5, n_repeats=2, random_state=None)
for train_index, test_index in kf.split(X):
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
training, valid, ytraining, yvalid = train_test_split(X_train, y_train, test_size=0.3, random_state=None)
stacked_predictions=[]
stacked_test_predictions=[]
result=fit_stack(clf2, training, valid, ytraining,X_test,stacked_predictions,stacked_test_predictions)
stacked_predictions=result['pred']
stacked_test_predictions=result['test']
result=fit_stack(clf4, training, valid, ytraining,X_test,stacked_predictions,stacked_test_predictions)
stacked_predictions=result['pred']
stacked_test_predictions=result['test']
result=fit_stack(clf3, training, valid, ytraining,X_test,stacked_predictions,stacked_test_predictions)
stacked_predictions=result['pred']
stacked_test_predictions=result['test']
meta_model=KNeighborsClassifier(n_neighbors=10)
meta_model.fit(stacked_predictions.reshape(-1,3),yvalid)
final_predictions=meta_model.predict(stacked_test_predictions.reshape(-1,3))
acc=accuracy_score(y_test,final_predictions)
accuracies.append(acc)
print(accuracies)
mean_acc=sum(accuracies) / float(len(accuracies))
print("Mean %0.3f" % mean_acc)
stacked2()
```
### Repeated KFold with X_train and y_train
```
accuracies=[]
def stacked1():
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=None)
kf = RepeatedKFold(n_splits=5, n_repeats=1, random_state=None)
for train_index, test_index in kf.split(X_train):
training, valid = X_train.iloc[train_index], X_train.iloc[test_index]
ytraining, yvalid = y_train.iloc[train_index], y_train.iloc[test_index]
stacked_predictions=[]
stacked_test_predictions=[]
result=fit_stack(clf2, training, valid, ytraining,X_test,stacked_predictions,stacked_test_predictions)
stacked_predictions=result['pred']
stacked_test_predictions=result['test']
result=fit_stack(clf4, training, valid, ytraining,X_test,stacked_predictions,stacked_test_predictions)
stacked_predictions=result['pred']
stacked_test_predictions=result['test']
result=fit_stack(clf3, training, valid, ytraining,X_test,stacked_predictions,stacked_test_predictions)
stacked_predictions=result['pred']
stacked_test_predictions=result['test']
meta_model=KNeighborsClassifier(n_neighbors=10)
meta_model.fit(stacked_predictions.reshape(-1,3),yvalid)
final_predictions=meta_model.predict(stacked_test_predictions.reshape(-1,3))
acc=accuracy_score(y_test,final_predictions)
accuracies.append(acc)
print(accuracies)
mean_acc=sum(accuracies) / float(len(accuracies))
print("Mean %0.3f" % mean_acc)
stacked1()
```
### How did to combine the models? Cross-validate the model. How well did it do?
Cross validation did not increase the acccuray. It decreased the accuracy by approx by 1.5%.
But this gives us a more clear picture of the actual accuracy of the model which around 94%
| 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.
```
# Convolutional Neural Networks
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/beta/tutorials/images/intro_to_cnns">
<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/images/intro_to_cnns.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/images/intro_to_cnns.ipynb">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />
View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/site/en/r2/tutorials/images/intro_to_cnns.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
This tutorial demonstrates training a simple [Convolutional Neural Network](https://developers.google.com/machine-learning/glossary/#convolutional_neural_network) (CNN) to classify MNIST digits. This simple network will achieve over 99% accuracy on the MNIST test set. Because this tutorial uses the [Keras Sequential API](https://www.tensorflow.org/guide/keras), creating and training our model will take just a few lines of code.
Note: CNNs train faster with a GPU. If you are running this notebook with Colab, you can enable the free GPU via * Edit -> Notebook settings -> Hardware accelerator -> GPU*.
### Import TensorFlow
```
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta0
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
```
### Download and prepare the MNIST dataset
```
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0
```
### Create the convolutional base
The 6 lines of code below define the convolutional base using a common pattern: a stack of [Conv2D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D) and [MaxPooling2D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D) layers.
As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to color channels, MNIST has one (because the images are grayscale), whereas a color image has three (R,G,B). In this example, we will configure our CNN to process inputs of shape (28, 28, 1), which is the format of MNIST images. We do this by passing the argument `input_shape` to our first layer.
```
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
```
Let display the architecture of our model so far.
```
model.summary()
```
Above, you can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as we go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, we can afford (computationally) to add more output channels in each Conv2D layer.
### Add Dense layers on top
To complete our model, we will feed the last output tensor from the convolutional base (of shape (3, 3, 64)) into one or more Dense layers to perform classification. Dense layers take vectors as input (which are 1D), while the current output is a 3D tensor. First, we will flatten (or unroll) the 3D output to 1D, then add one or more Dense layers on top. MNIST has 10 output classes, so we use a final Dense layer with 10 outputs and a softmax activation.
```
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
```
Here's the complete architecture of our model.
```
model.summary()
```
As you can see, our (3, 3, 64) outputs were flattened into vectors of shape (576) before going through two Dense layers.
### Compile and train the model
```
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
```
### Evaluate the model
```
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(test_acc)
```
As you can see, our simple CNN has achieved a test accuracy of over 99%. Not bad for a few lines of code! For another style of writing a CNN (using the Keras Subclassing API and a GradientTape) head [here](https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/quickstart/advanced.ipynb).
| github_jupyter |
# Sensitivity Analysis
```
import os
import itertools
import random
import pandas as pd
import numpy as np
import scipy
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid")
import sys
sys.path.insert(0, '../utils')
import model_utils
import geoutils
import logging
import warnings
logging.getLogger().setLevel(logging.ERROR)
warnings.filterwarnings("ignore")
SEED = 42
%load_ext autoreload
%autoreload 2
```
## File Locations
```
lr_index, rf_index, svc_index = 7, 3, 3
output_dir = "../outputs/"
neg_samples_strs = ['10k', '30k', '50k']
neg_samples_dirs = [
output_dir + '10k_results/',
output_dir + '30k_results/',
output_dir + '50k_results/'
]
model_types = [
'logistic_regression',
'random_forest',
'linear_svc'
]
```
## Load Results
```
results_dict = model_utils.load_neg_sample_results(model_types, neg_samples_strs, neg_samples_dirs)
results_dict['logistic_regression']['10k_per_area'][0]['pixel_preds'][lr_index].head(3)
```
## Generate Sensitivity Analysis Matrix
```
lr_area_dict = {
'10k LR' : results_dict['logistic_regression']['10k_per_area'],
'30k LR' : results_dict['logistic_regression']['30k_per_area'],
'50k LR' : results_dict['logistic_regression']['50k_per_area'],
}
model_utils.generate_iou_matrix_per_area(
lr_area_dict, lr_index, model_utils.AREA_CODES, percent=0.20
)
rf_area_dict = {
'10k RF' : results_dict['random_forest']['10k_per_area'],
'30k RF' : results_dict['random_forest']['30k_per_area'],
'50k RF' : results_dict['random_forest']['50k_per_area'],
}
model_utils.generate_iou_matrix_per_area(
rf_area_dict, rf_index, model_utils.AREA_CODES, percent=0.20
)
svc_area_dict = {
'10k SVC' : results_dict['linear_svc']['10k_per_area'],
'30k SVC' : results_dict['linear_svc']['30k_per_area'],
'50k SVC' : results_dict['linear_svc']['50k_per_area'],
}
model_utils.generate_iou_matrix_per_area(
svc_area_dict, svc_index, model_utils.AREA_CODES, percent=0.20
)
```
## Sensitivity Analysis on Unseen Test Set
```
from tqdm import tqdm
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import (
MinMaxScaler,
StandardScaler
)
SEED = 42
```
### File Locations
```
version = '20200509'
data_dir = "../data/"
input_file = data_dir + '{}_dataset.csv'.format(version)
output_dir = "../outputs/sensitivity/"
tmp_dir = data_dir + 'tmp/'
images_dir = data_dir + 'images/'
indices_dir = data_dir + 'indices/'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if not os.path.exists(tmp_dir):
os.makedirs(tmp_dir)
#!gsutil -q -m cp gs://immap-images/20200525/medellin_*.tif {images_dir}
#!gsutil -q -m cp gs://immap-indices/20200525/indices_medellin_*.tif {indices_dir}
#!gsutil -q -m cp gs://immap-images/20200518/cali_*.tif {images_dir}
#!gsutil -q -m cp gs://immap-indices/20200518/indices_cali_*.tif {indices_dir}
#!gsutil -q -m cp gs://immap-images/20200508/malambo_*.tif {images_dir}
#!gsutil -q -m cp gs://immap-indices/20200508/indices_malambo_*.tif {indices_dir}
```
### Load Data
```
raw_data = pd.read_csv(input_file).reset_index(drop=True)
print('Data dimensions: {}'.format(raw_data.shape))
raw_data.head(3)
```
### Check Hyperparameters of Best Model
```
print('Logistic Regression Parameters: {}'.format(
results_dict['logistic_regression']['30k']['labels'][lr_index]
))
print('Random Forest Parameters: {}'.format(
results_dict['random_forest']['30k']['labels'][rf_index]
))
```
### Instantiate Models
```
lr = LogisticRegression(penalty='l1', C=1.0)
rf = RandomForestClassifier(
n_estimators=800,
max_depth=12,
min_samples_split=15,
min_samples_leaf=2,
random_state=42
)
neg_samples_list = [10000, 30000, 50000]
models, model_strs = [lr, rf], ['LR', 'RF']
areas = ['medellin', 'cali', 'malambo']
area_dict = geoutils.get_filepaths(areas, images_dir, indices_dir)
```
### Run Model for 10k, 30k, and 50k Negative Samples
```
for num_neg_samples, neg_samples_str in zip(neg_samples_list, neg_samples_strs):
for model, model_str in zip(models, model_strs):
model, features = model_utils.train_model(model, raw_data, num_neg_samples, SEED)
for area in areas:
output = output_dir + '{}_{}_{}_{}.tif'.format(version, area, model_str, neg_samples_str)
geoutils.get_preds_windowing(
area=area,
area_dict=area_dict,
model=model,
tmp_dir=tmp_dir,
best_features=features,
output=output,
grid_blocks=9,
threshold=0
)
for file in os.listdir(output_dir):
if '.ipynb' not in file:
out_file = output_dir + file
!gsutil -q cp {out_file} gs://immap-results/probmaps/
```
## Test on Unseen Data
```
import geopandas as gpd
areas = ['medellin', 'malambo', 'cali']
data_dir = "../data/"
grid_dirs = [data_dir + 'grids/grid-' + area + '.gpkg' for area in areas]
grid_gpkgs = {area: gpd.read_file(file) for area, file in zip(areas, grid_dirs)}
grid_gpkgs['medellin'].head(3)
lr_area_dict = {
'10k LR' : {area: {'grid_preds' : [grid_gpkgs[area][['id', 'LR_10k_mean']]]} for area in areas},
'30k LR' : {area: {'grid_preds' : [grid_gpkgs[area][['id', 'LR_30k_mean']]]} for area in areas},
'50k LR' : {area: {'grid_preds' : [grid_gpkgs[area][['id', 'LR_50k_mean']]]} for area in areas},
}
model_utils.generate_iou_matrix_per_area(
lr_area_dict, 0, areas, percent=0.20, nrows=1, ncols=3, figsize=(8,2.5)
)
rf_area_dict = {
'10k RF' : {area: {'grid_preds' : [grid_gpkgs[area][['id', 'RF_10K_mean']]]} for area in areas},
'30k RF' : {area: {'grid_preds' : [grid_gpkgs[area][['id', 'RF_30K_mean']]]} for area in areas},
'50k RF' : {area: {'grid_preds' : [grid_gpkgs[area][['id', 'RF_50K_mean']]]} for area in areas},
}
model_utils.generate_iou_matrix_per_area(
rf_area_dict, 0, areas, percent=0.20, nrows=1, ncols=3, figsize=(8,2.5)
)
```
| github_jupyter |
# Weight Sampling Tutorial
If you want to fine-tune one of the trained original SSD models on your own dataset, chances are that your dataset doesn't have the same number of classes as the trained model you're trying to fine-tune.
This notebook explains a few options for how to deal with this situation. In particular, one solution is to sub-sample (or up-sample) the weight tensors of all the classification layers so that their shapes correspond to the number of classes in your dataset.
This notebook explains how this is done.
## 0. Our example
I'll use a concrete example to make the process clear, but of course the process explained here is the same for any dataset.
Consider the following example. You have a dataset on road traffic objects. Let this dataset contain annotations for the following object classes of interest:
`['car', 'truck', 'pedestrian', 'bicyclist', 'traffic_light', 'motorcycle', 'bus', 'stop_sign']`
That is, your dataset contains annotations for 8 object classes.
You would now like to train an SSD300 on this dataset. However, instead of going through all the trouble of training a new model from scratch, you would instead like to use the fully trained original SSD300 model that was trained on MS COCO and fine-tune it on your dataset.
The problem is: The SSD300 that was trained on MS COCO predicts 80 different classes, but your dataset has only 8 classes. The weight tensors of the classification layers of the MS COCO model don't have the right shape for your model that is supposed to learn only 8 classes. Bummer.
So what options do we have?
### Option 1: Just ignore the fact that we need only 8 classes
The maybe not so obvious but totally obvious option is: We could just ignore the fact that the trained MS COCO model predicts 80 different classes, but we only want to fine-tune it on 8 classes. We could simply map the 8 classes in our annotated dataset to any 8 indices out of the 80 that the MS COCO model predicts. The class IDs in our dataset could be indices 1-8, they could be the indices `[0, 3, 8, 1, 2, 10, 4, 6, 12]`, or any other 8 out of the 80. Whatever we would choose them to be. The point is that we would be training only 8 out of every 80 neurons that predict the class for a given box and the other 72 would simply not be trained. Nothing would happen to them, because the gradient for them would always be zero, because these indices don't appear in our dataset.
This would work, and it wouldn't even be a terrible option. Since only 8 out of the 80 classes would get trained, the model might get gradually worse at predicting the other 72 clases, but we don't care about them anyway, at least not right now. And if we ever realize that we now want to predict more than 8 different classes, our model would be expandable in that sense. Any new class we want to add could just get any one of the remaining free indices as its ID. We wouldn't need to change anything about the model, it would just be a matter of having the dataset annotated accordingly.
Still, in this example we don't want to take this route. We don't want to carry around the computational overhead of having overly complex classifier layers, 90 percent of which we don't use anyway, but still their whole output needs to be computed in every forward pass.
So what else could we do instead?
### Option 2: Just ignore those weights that are causing problems
We could build a new SSD300 with 8 classes and load into it the weights of the MS COCO SSD300 for all layers except the classification layers. Would that work? Yes, that would work. The only conflict is with the weights of the classification layers, and we can avoid this conflict by simply ignoring them. While this solution would be easy, it has a significant downside: If we're not loading trained weights for the classification layers of our new SSD300 model, then they will be initialized randomly. We'd still benefit from the trained weights for all the other layers, but the classifier layers would need to be trained from scratch.
Not the end of the world, but we like pre-trained stuff, because it saves us a lot of training time. So what else could we do?
### Option 3: Sub-sample the weights that are causing problems
Instead of throwing the problematic weights away like in option 2, we could also sub-sample them. If the weight tensors of the classification layers of the MS COCO model don't have the right shape for our new model, we'll just **make** them have the right shape. This way we can still benefit from the pre-trained weights in those classification layers. Seems much better than option 2.
The great thing in this example is: MS COCO happens to contain all of the eight classes that we care about. So when we sub-sample the weight tensors of the classification layers, we won't just do so randomly. Instead, we'll pick exactly those elements from the tensor that are responsible for the classification of the 8 classes that we care about.
However, even if the classes in your dataset were entirely different from the classes in any of the fully trained models, it would still make a lot of sense to use the weights of the fully trained model. Any trained weights are always a better starting point for the training than random initialization, even if your model will be trained on entirely different object classes.
And of course, in case you happen to have the opposite problem, where your dataset has **more** classes than the trained model you would like to fine-tune, then you can simply do the same thing in the opposite direction: Instead of sub-sampling the classification layer weights, you would then **up-sample** them. Works just the same way as what we'll be doing below.
Let's get to it.
```
import h5py
import numpy as np
import shutil
from misc_utils.tensor_sampling_utils import sample_tensors
```
## 1. Load the trained weights file and make a copy
First, we'll load the HDF5 file that contains the trained weights that we need (the source file). In our case this is "`VGG_coco_SSD_300x300_iter_400000.h5`" (download link available in the README of this repo), which are the weights of the original SSD300 model that was trained on MS COCO.
Then, we'll make a copy of that weights file. That copy will be our output file (the destination file).
```
# TODO: Set the path for the source weights file you want to load.
dataFolder = '../Models/'
weights_source_path = dataFolder + 'VGG_coco_SSD_300x300_iter_400000.h5'
# TODO: Set the path and name for the destination weights file
# that you want to create.
weights_destination_path = dataFolder + 'VGG_coco_SSD_300x300_iter_400000_subsampled_3_classes3.h5'
# Make a copy of the weights file.
shutil.copy(weights_source_path, weights_destination_path)
# Load both the source weights file and the copy we made.
# We will load the original weights file in read-only mode so that we can't mess up anything.
weights_source_file = h5py.File(weights_source_path, 'r')
weights_destination_file = h5py.File(weights_destination_path)
```
## 2. Figure out which weight tensors we need to sub-sample
Next, we need to figure out exactly which weight tensors we need to sub-sample. As mentioned above, the weights for all layers except the classification layers are fine, we don't need to change anything about those.
So which are the classification layers in SSD300? Their names are:
```
classifier_names = ['conv4_3_norm_mbox_conf',
'fc7_mbox_conf',
'conv6_2_mbox_conf',
'conv7_2_mbox_conf',
'conv8_2_mbox_conf',
'conv9_2_mbox_conf']
```
## 3. Figure out which slices to pick
The following section is optional. I'll look at one classification layer and explain what we want to do, just for your understanding. If you don't care about that, just skip ahead to the next section.
We know which weight tensors we want to sub-sample, but we still need to decide which (or at least how many) elements of those tensors we want to keep. Let's take a look at the first of the classifier layers, "`conv4_3_norm_mbox_conf`". Its two weight tensors, the kernel and the bias, have the following shapes:
```
conv4_3_norm_mbox_conf_kernel = weights_source_file[classifier_names[0]][classifier_names[0]]['kernel:0']
conv4_3_norm_mbox_conf_bias = weights_source_file[classifier_names[0]][classifier_names[0]]['bias:0']
print("Shape of the '{}' weights:".format(classifier_names[0]))
print()
print("kernel:\t", conv4_3_norm_mbox_conf_kernel.shape)
print("bias:\t", conv4_3_norm_mbox_conf_bias.shape)
```
So the last axis has 324 elements. Why is that?
- MS COCO has 80 classes, but the model also has one 'backgroud' class, so that makes 81 classes effectively.
- The 'conv4_3_norm_mbox_loc' layer predicts 4 boxes for each spatial position, so the 'conv4_3_norm_mbox_conf' layer has to predict one of the 81 classes for each of those 4 boxes.
That's why the last axis has 4 * 81 = 324 elements.
So how many elements do we want in the last axis for this layer?
Let's do the same calculation as above:
- Our dataset has 8 classes, but our model will also have a 'background' class, so that makes 9 classes effectively.
- We need to predict one of those 9 classes for each of the four boxes at each spatial position.
That makes 4 * 9 = 36 elements.
Now we know that we want to keep 36 elements in the last axis and leave all other axes unchanged. But which 36 elements out of the original 324 elements do we want?
Should we just pick them randomly? If the object classes in our dataset had absolutely nothing to do with the classes in MS COCO, then choosing those 36 elements randomly would be fine (and the next section covers this case, too). But in our particular example case, choosing these elements randomly would be a waste. Since MS COCO happens to contain exactly the 8 classes that we need, instead of sub-sampling randomly, we'll just take exactly those elements that were trained to predict our 8 classes.
Here are the indices of the 9 classes in MS COCO that we are interested in:
`[0, 1, 2, 3, 4, 6, 8, 10, 12]`
The indices above represent the following classes in the MS COCO datasets:
`['background', 'person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign']`
How did I find out those indices? I just looked them up in the annotations of the MS COCO dataset.
While these are the classes we want, we don't want them in this order. In our dataset, the classes happen to be in the following order as stated at the top of this notebook:
`['background', 'car', 'truck', 'pedestrian', 'bicyclist', 'traffic_light', 'motorcycle', 'bus', 'stop_sign']`
For example, '`traffic_light`' is class ID 5 in our dataset but class ID 10 in the SSD300 MS COCO model. So the order in which I actually want to pick the 9 indices above is this:
`[0, 3, 8, 1, 2, 10, 4, 6, 12]`
So out of every 81 in the 324 elements, I want to pick the 9 elements above. This gives us the following 36 indices:
```
n_classes_source = 81
classes_of_interest = [0, 3, 8, 1, 2, 10, 4, 6, 12]
classes_of_interest = [0, 10, 10, 10]
subsampling_indices = []
for i in range(int(324/n_classes_source)):
indices = np.array(classes_of_interest) + i * n_classes_source
subsampling_indices.append(indices)
subsampling_indices = list(np.concatenate(subsampling_indices))
print(subsampling_indices)
```
These are the indices of the 36 elements that we want to pick from both the bias vector and from the last axis of the kernel tensor.
This was the detailed example for the '`conv4_3_norm_mbox_conf`' layer. And of course we haven't actually sub-sampled the weights for this layer yet, we have only figured out which elements we want to keep. The piece of code in the next section will perform the sub-sampling for all the classifier layers.
## 4. Sub-sample the classifier weights
The code in this section iterates over all the classifier layers of the source weights file and performs the following steps for each classifier layer:
1. Get the kernel and bias tensors from the source weights file.
2. Compute the sub-sampling indices for the last axis. The first three axes of the kernel remain unchanged.
3. Overwrite the corresponding kernel and bias tensors in the destination weights file with our newly created sub-sampled kernel and bias tensors.
The second step does what was explained in the previous section.
In case you want to **up-sample** the last axis rather than sub-sample it, simply set the `classes_of_interest` variable below to the length you want it to have. The added elements will be initialized either randomly or optionally with zeros. Check out the documentation of `sample_tensors()` for details.
```
# TODO: Set the number of classes in the source weights file. Note that this number must include
# the background class, so for MS COCO's 80 classes, this must be 80 + 1 = 81.
n_classes_source = 81
# TODO: Set the indices of the classes that you want to pick for the sub-sampled weight tensors.
# In case you would like to just randomly sample a certain number of classes, you can just set
# `classes_of_interest` to an integer instead of the list below. Either way, don't forget to
# include the background class. That is, if you set an integer, and you want `n` positive classes,
# then you must set `classes_of_interest = n + 1`.
classes_of_interest = [0, 10, 13, 14]
#classes_of_interest = [0, 3, 8, 1, 2, 10, 4, 6, 12]
# classes_of_interest = 9 # Uncomment this in case you want to just randomly sub-sample the last axis instead of providing a list of indices.
for name in classifier_names:
# Get the trained weights for this layer from the source HDF5 weights file.
kernel = weights_source_file[name][name]['kernel:0'].value
bias = weights_source_file[name][name]['bias:0'].value
# Get the shape of the kernel. We're interested in sub-sampling
# the last dimension, 'o'.
height, width, in_channels, out_channels = kernel.shape
# Compute the indices of the elements we want to sub-sample.
# Keep in mind that each classification predictor layer predicts multiple
# bounding boxes for every spatial location, so we want to sub-sample
# the relevant classes for each of these boxes.
if isinstance(classes_of_interest, (list, tuple)):
subsampling_indices = []
for i in range(int(out_channels/n_classes_source)):
indices = np.array(classes_of_interest) + i * n_classes_source
subsampling_indices.append(indices)
subsampling_indices = list(np.concatenate(subsampling_indices))
elif isinstance(classes_of_interest, int):
subsampling_indices = int(classes_of_interest * (out_channels/n_classes_source))
else:
raise ValueError("`classes_of_interest` must be either an integer or a list/tuple.")
# Sub-sample the kernel and bias.
# The `sample_tensors()` function used below provides extensive
# documentation, so don't hesitate to read it if you want to know
# what exactly is going on here.
new_kernel, new_bias = sample_tensors(weights_list=[kernel, bias],
sampling_instructions=[height, width, in_channels, subsampling_indices],
axes=[[3]], # The one bias dimension corresponds to the last kernel dimension.
init=['gaussian', 'zeros'],
mean=0.0,
stddev=0.005)
# Delete the old weights from the destination file.
del weights_destination_file[name][name]['kernel:0']
del weights_destination_file[name][name]['bias:0']
# Create new datasets for the sub-sampled weights.
weights_destination_file[name][name].create_dataset(name='kernel:0', data=new_kernel)
weights_destination_file[name][name].create_dataset(name='bias:0', data=new_bias)
# Make sure all data is written to our output file before this sub-routine exits.
weights_destination_file.flush()
```
That's it, we're done.
Let's just quickly inspect the shapes of the weights of the '`conv4_3_norm_mbox_conf`' layer in the destination weights file:
```
conv4_3_norm_mbox_conf_kernel = weights_destination_file[classifier_names[0]][classifier_names[0]]['kernel:0']
conv4_3_norm_mbox_conf_bias = weights_destination_file[classifier_names[0]][classifier_names[0]]['bias:0']
print("Shape of the '{}' weights:".format(classifier_names[0]))
print()
print("kernel:\t", conv4_3_norm_mbox_conf_kernel.shape)
print("bias:\t", conv4_3_norm_mbox_conf_bias.shape)
```
Nice! Exactly what we wanted, 36 elements in the last axis. Now the weights are compatible with our new SSD300 model that predicts 8 positive classes.
This is the end of the relevant part of this tutorial, but we can do one more thing and verify that the sub-sampled weights actually work. Let's do that in the next section.
## 5. Verify that our sub-sampled weights actually work
In our example case above we sub-sampled the fully trained weights of the SSD300 model trained on MS COCO from 80 classes to just the 8 classes that we needed.
We can now create a new SSD300 with 8 classes, load our sub-sampled weights into it, and see how the model performs on a few test images that contain objects for some of those 8 classes. Let's do it.
```
from keras.optimizers import Adam
from keras import backend as K
from keras.models import load_model
from models.keras_ssd300 import ssd_300
from keras_loss_function.keras_ssd_loss import SSDLoss
from keras_layers.keras_layer_AnchorBoxes import AnchorBoxes
from keras_layers.keras_layer_DecodeDetections import DecodeDetections
from keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast
from keras_layers.keras_layer_L2Normalization import L2Normalization
from data_generator.object_detection_2d_data_generator import DataGenerator
from data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels
from data_generator.object_detection_2d_patch_sampling_ops import RandomMaxCropFixedAR
from data_generator.object_detection_2d_geometric_ops import Resize
```
### 5.1. Set the parameters for the model.
As always, set the parameters for the model. We're going to set the configuration for the SSD300 MS COCO model.
```
img_height = 300 # Height of the input images
img_width = 300 # Width of the input images
img_channels = 3 # Number of color channels of the input images
subtract_mean = [123, 117, 104] # The per-channel mean of the images in the dataset
swap_channels = [2, 1, 0] # The color channel order in the original SSD is BGR, so we should set this to `True`, but weirdly the results are better without swapping.
# TODO: Set the number of classes.
n_classes = 3 # Number of positive classes, e.g. 20 for Pascal VOC, 80 for MS COCO
scales = [0.07, 0.15, 0.33, 0.51, 0.69, 0.87, 1.05] # The anchor box scaling factors used in the original SSD300 for the MS COCO datasets.
# scales = [0.1, 0.2, 0.37, 0.54, 0.71, 0.88, 1.05] # The anchor box scaling factors used in the original SSD300 for the Pascal VOC datasets.
aspect_ratios = [[1.0, 2.0, 0.5],
[1.0, 2.0, 0.5, 3.0, 1.0/3.0],
[1.0, 2.0, 0.5, 3.0, 1.0/3.0],
[1.0, 2.0, 0.5, 3.0, 1.0/3.0],
[1.0, 2.0, 0.5],
[1.0, 2.0, 0.5]] # The anchor box aspect ratios used in the original SSD300; the order matters
two_boxes_for_ar1 = True
steps = [8, 16, 32, 64, 100, 300] # The space between two adjacent anchor box center points for each predictor layer.
offsets = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5] # The offsets of the first anchor box center points from the top and left borders of the image as a fraction of the step size for each predictor layer.
clip_boxes = False # Whether or not you want to limit the anchor boxes to lie entirely within the image boundaries
variances = [0.1, 0.1, 0.2, 0.2] # The variances by which the encoded target coordinates are scaled as in the original implementation
normalize_coords = True
```
### 5.2. Build the model
Build the model and load our newly created, sub-sampled weights into it.
```
# 1: Build the Keras model
K.clear_session() # Clear previous models from memory.
model = ssd_300(image_size=(img_height, img_width, img_channels),
n_classes=n_classes,
mode='inference',
l2_regularization=0.0005,
scales=scales,
aspect_ratios_per_layer=aspect_ratios,
two_boxes_for_ar1=two_boxes_for_ar1,
steps=steps,
offsets=offsets,
clip_boxes=clip_boxes,
variances=variances,
normalize_coords=normalize_coords,
subtract_mean=subtract_mean,
divide_by_stddev=None,
swap_channels=swap_channels,
confidence_thresh=0.5,
iou_threshold=0.45,
top_k=200,
nms_max_output_size=400,
return_predictor_sizes=False)
print("Model built.")
# 2: Load the sub-sampled weights into the model.
# Load the weights that we've just created via sub-sampling.
weights_path = weights_destination_path
model.load_weights(weights_path, by_name=True)
print("Weights file loaded:", weights_path)
# 3: Instantiate an Adam optimizer and the SSD loss function and compile the model.
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
ssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)
model.compile(optimizer=adam, loss=ssd_loss.compute_loss)
```
### 5.3. Load some images to test our model on
We sub-sampled some of the road traffic categories from the trained SSD300 MS COCO weights, so let's try out our model on a few road traffic images. The Udacity road traffic dataset linked to in the `ssd7_training.ipynb` notebook lends itself to this task. Let's instantiate a `DataGenerator` and load the Udacity dataset. Everything here is preset already, but if you'd like to learn more about the data generator and its capabilities, take a look at the detailed tutorial in [this](https://github.com/pierluigiferrari/data_generator_object_detection_2d) repository.
```
dataset = DataGenerator()
# TODO: Set the paths to your dataset here.
images_path = '../TrainData/Simulator/'
labels_path = '../TrainData/Simulator/label_sim_training.csv'
dataset.parse_csv(images_dir=images_path,
labels_filename=labels_path,
input_format=['image_name', 'xmin', 'xmax', 'ymin', 'ymax', 'class_id'], # This is the order of the first six columns in the CSV file that contains the labels for your dataset. If your labels are in XML format, maybe the XML parser will be helpful, check the documentation.
include_classes='all',
random_sample=False)
print("Number of images in the dataset:", dataset.get_dataset_size())
```
Make sure the batch generator generates images of size `(300, 300)`. We'll first randomly crop the largest possible patch with aspect ratio 1.0 and then resize to `(300, 300)`.
```
convert_to_3_channels = ConvertTo3Channels()
random_max_crop = RandomMaxCropFixedAR(patch_aspect_ratio=img_width/img_height)
resize = Resize(height=img_height, width=img_width)
generator = dataset.generate(batch_size=1,
shuffle=True,
transformations=[convert_to_3_channels,
random_max_crop,
resize],
returns={'processed_images',
'processed_labels',
'filenames'},
keep_images_without_gt=False)
```
### 5.4. Make predictions and visualize them
```
# Make a prediction
y_pred = model.predict(batch_images)
print(y_pred)
# Generate samples
batch_images, batch_labels, batch_filenames = next(generator)
i = 0 # Which batch item to look at
print("Image:", batch_filenames[i])
print()
print("Ground truth boxes:\n")
print(batch_labels[i])
# Make a prediction
y_pred = model.predict(batch_images)
# Decode the raw prediction.
i = 0
confidence_threshold = 0.10
y_pred_thresh = [y_pred[k][y_pred[k,:,1] > confidence_threshold] for k in range(y_pred.shape[0])]
np.set_printoptions(precision=2, suppress=True, linewidth=90)
print("Predicted boxes:\n")
print(' class conf xmin ymin xmax ymax')
print(y_pred_thresh[0])
# Visualize the predictions.
from matplotlib import pyplot as plt
%matplotlib inline
plt.figure(figsize=(20,12))
plt.imshow(batch_images[i])
current_axis = plt.gca()
classes = ['background', 'car', 'truck', 'pedestrian', 'bicyclist',
'traffic_light', 'motorcycle', 'bus', 'stop_sign'] # Just so we can print class names onto the image instead of IDs
# Draw the predicted boxes in blue
for box in y_pred_thresh[i]:
class_id = box[0]
confidence = box[1]
xmin = box[2]
ymin = box[3]
xmax = box[4]
ymax = box[5]
label = '{}: {:.2f}'.format(classes[int(class_id)], confidence)
current_axis.add_patch(plt.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, color='blue', fill=False, linewidth=2))
current_axis.text(xmin, ymin, label, size='x-large', color='white', bbox={'facecolor':'blue', 'alpha':1.0})
# Draw the ground truth boxes in green (omit the label for more clarity)
for box in batch_labels[i]:
class_id = box[0]
xmin = box[1]
ymin = box[2]
xmax = box[3]
ymax = box[4]
label = '{}'.format(classes[int(class_id)])
current_axis.add_patch(plt.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, color='green', fill=False, linewidth=2))
#current_axis.text(box[1], box[3], label, size='x-large', color='white', bbox={'facecolor':'green', 'alpha':1.0})
```
Seems as if our sub-sampled weights were doing a good job, sweet. Now we can fine-tune this model on our dataset with 8 classes.
| github_jupyter |
## KF Basics - Part I
### Introduction
#### What is the need to describe belief in terms of PDF's?
This is because robot environments are stochastic. A robot environment may have cows with Tesla by side. That is a robot and it's environment cannot be deterministically modelled(e.g as a function of something like time t). In the real world sensors are also error prone, and hence there'll be a set of values with a mean and variance that it can take. Hence, we always have to model around some mean and variances associated.
#### What is Expectation of a Random Variables?
Expectation is nothing but an average of the probabilites
$$\mathbb E[X] = \sum_{i=1}^n p_ix_i$$
In the continous form,
$$\mathbb E[X] = \int_{-\infty}^\infty x\, f(x) \,dx$$
```
import numpy as np
import random
x=[3,1,2]
p=[0.1,0.3,0.4]
E_x=np.sum(np.multiply(x,p))
print(E_x)
```
#### What is the advantage of representing the belief as a unimodal as opposed to multimodal?
Obviously, it makes sense because we can't multiple probabilities to a car moving for two locations. This would be too confusing and the information will not be useful.
### Variance, Covariance and Correlation
#### Variance
Variance is the spread of the data. The mean does'nt tell much **about** the data. Therefore the variance tells us about the **story** about the data meaning the spread of the data.
$$\mathit{VAR}(X) = \frac{1}{n}\sum_{i=1}^n (x_i - \mu)^2$$
```
x=np.random.randn(10)
np.var(x)
```
#### Covariance
This is for a multivariate distribution. For example, a robot in 2-D space can take values in both x and y. To describe them, a normal distribution with mean in both x and y is needed.
For a multivariate distribution, mean $\mu$ can be represented as a matrix,
$$
\mu = \begin{bmatrix}\mu_1\\\mu_2\\ \vdots \\\mu_n\end{bmatrix}
$$
Similarly, variance can also be represented.
But an important concept is that in the same way as every variable or dimension has a variation in its values, it is also possible that there will be values on how they **together vary**. This is also a measure of how two datasets are related to each other or **correlation**.
For example, as height increases weight also generally increases. These variables are correlated. They are positively correlated because as one variable gets larger so does the other.
We use a **covariance matrix** to denote covariances of a multivariate normal distribution:
$$
\Sigma = \begin{bmatrix}
\sigma_1^2 & \sigma_{12} & \cdots & \sigma_{1n} \\
\sigma_{21} &\sigma_2^2 & \cdots & \sigma_{2n} \\
\vdots & \vdots & \ddots & \vdots \\
\sigma_{n1} & \sigma_{n2} & \cdots & \sigma_n^2
\end{bmatrix}
$$
**Diagonal** - Variance of each variable associated.
**Off-Diagonal** - covariance between ith and jth variables.
$$\begin{aligned}VAR(X) = \sigma_x^2 &= \frac{1}{n}\sum_{i=1}^n(X - \mu)^2\\
COV(X, Y) = \sigma_{xy} &= \frac{1}{n}\sum_{i=1}^n[(X-\mu_x)(Y-\mu_y)\big]\end{aligned}$$
```
x=np.random.random((3,3))
np.cov(x)
```
Covariance taking the data as **sample** with $\frac{1}{N-1}$
```
x_cor=np.random.rand(1,10)
y_cor=np.random.rand(1,10)
np.cov(x_cor,y_cor)
```
Covariance taking the data as **population** with $\frac{1}{N}$
```
np.cov(x_cor,y_cor,bias=1)
```
### Gaussians
#### Central Limit Theorem
According to this theorem, the average of n samples of random and independent variables tends to follow a normal distribution as we increase the sample size.(Generally, for n>=30)
```
import matplotlib.pyplot as plt
import random
a=np.zeros((100,))
for i in range(100):
x=[random.uniform(1,10) for _ in range(1000)]
a[i]=np.sum(x,axis=0)/1000
plt.hist(a)
```
#### Gaussian Distribution
A Gaussian is a *continuous probability distribution* that is completely described with two parameters, the mean ($\mu$) and the variance ($\sigma^2$). It is defined as:
$$
f(x, \mu, \sigma) = \frac{1}{\sigma\sqrt{2\pi}} \exp\big [{-\frac{(x-\mu)^2}{2\sigma^2} }\big ]
$$
Range is $$[-\inf,\inf] $$
This is just a function of mean($\mu$) and standard deviation ($\sigma$) and what gives the normal distribution the charecteristic **bell curve**.
```
import matplotlib.mlab as mlab
import math
import scipy.stats
mu = 0
variance = 5
sigma = math.sqrt(variance)
x = np.linspace(mu - 5*sigma, mu + 5*sigma, 100)
plt.plot(x,scipy.stats.norm.pdf(x, mu, sigma))
plt.show()
```
#### Why do we need Gaussian distributions?
Since it becomes really difficult in the real world to deal with multimodal distribution as we cannot put the belief in two seperate location of the robots. This becomes really confusing and in practice impossible to comprehend.
Gaussian probability distribution allows us to drive the robots using only one mode with peak at the mean with some variance.
### Gaussian Properties
**Multiplication**
For the measurement update in a Bayes Filter, the algorithm tells us to multiply the Prior P(X_t) and measurement P(Z_t|X_t) to calculate the posterior:
$$P(X \mid Z) = \frac{P(Z \mid X)P(X)}{P(Z)}$$
Here for the numerator, $P(Z \mid X),P(X)$ both are gaussian.
$N(\mu_1, \sigma_1^2)$ and $N(\mu_2, \sigma_2^2)$ are their mean and variances.
New mean is
$$\mu_\mathtt{new} = \frac{\mu_1 \sigma_2^2 + \mu_2 \sigma_1^2}{\sigma_1^2+\sigma_2^2}$$
New variance is
$$\sigma_\mathtt{new} = \frac{\sigma_1^2\sigma_2^2}{\sigma_1^2+\sigma_2^2}$$
```
import matplotlib.mlab as mlab
import math
mu1 = 0
variance1 = 2
sigma = math.sqrt(variance1)
x1 = np.linspace(mu1 - 3*sigma, mu1 + 3*sigma, 100)
plt.plot(x1,scipy.stats.norm.pdf(x1, mu1, sigma),label='prior')
mu2 = 10
variance2 = 2
sigma = math.sqrt(variance2)
x2 = np.linspace(mu2 - 3*sigma, mu2 + 3*sigma, 100)
plt.plot(x2,scipy.stats.norm.pdf(x2, mu2, sigma),"g-",label='measurement')
mu_new=(mu1*variance2+mu2*variance1)/(variance1+variance2)
print("New mean is at: ",mu_new)
var_new=(variance1*variance2)/(variance1+variance2)
print("New variance is: ",var_new)
sigma = math.sqrt(var_new)
x3 = np.linspace(mu_new - 3*sigma, mu_new + 3*sigma, 100)
plt.plot(x3,scipy.stats.norm.pdf(x3, mu_new, var_new),label="posterior")
plt.legend(loc='upper left')
plt.xlim(-10,20)
plt.show()
```
**Addition**
The motion step involves a case of adding up probability (Since it has to abide the Law of Total Probability). This means their beliefs are to be added and hence two gaussians. They are simply arithmetic additions of the two.
$$\begin{gathered}\mu_x = \mu_p + \mu_z \\
\sigma_x^2 = \sigma_z^2+\sigma_p^2\, \square\end{gathered}$$
```
import matplotlib.mlab as mlab
import math
mu1 = 5
variance1 = 1
sigma = math.sqrt(variance1)
x1 = np.linspace(mu1 - 3*sigma, mu1 + 3*sigma, 100)
plt.plot(x1,scipy.stats.norm.pdf(x1, mu1, sigma),label='prior')
mu2 = 10
variance2 = 1
sigma = math.sqrt(variance2)
x2 = np.linspace(mu2 - 3*sigma, mu2 + 3*sigma, 100)
plt.plot(x2,scipy.stats.norm.pdf(x2, mu2, sigma),"g-",label='measurement')
mu_new=mu1+mu2
print("New mean is at: ",mu_new)
var_new=(variance1+variance2)
print("New variance is: ",var_new)
sigma = math.sqrt(var_new)
x3 = np.linspace(mu_new - 3*sigma, mu_new + 3*sigma, 100)
plt.plot(x3,scipy.stats.norm.pdf(x3, mu_new, var_new),label="posterior")
plt.legend(loc='upper left')
plt.xlim(-10,20)
plt.show()
#Example from:
#https://scipython.com/blog/visualizing-the-bivariate-gaussian-distribution/
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
# Our 2-dimensional distribution will be over variables X and Y
N = 60
X = np.linspace(-3, 3, N)
Y = np.linspace(-3, 4, N)
X, Y = np.meshgrid(X, Y)
# Mean vector and covariance matrix
mu = np.array([0., 1.])
Sigma = np.array([[ 1. , -0.5], [-0.5, 1.5]])
# Pack X and Y into a single 3-dimensional array
pos = np.empty(X.shape + (2,))
pos[:, :, 0] = X
pos[:, :, 1] = Y
def multivariate_gaussian(pos, mu, Sigma):
"""Return the multivariate Gaussian distribution on array pos.
pos is an array constructed by packing the meshed arrays of variables
x_1, x_2, x_3, ..., x_k into its _last_ dimension.
"""
n = mu.shape[0]
Sigma_det = np.linalg.det(Sigma)
Sigma_inv = np.linalg.inv(Sigma)
N = np.sqrt((2*np.pi)**n * Sigma_det)
# This einsum call calculates (x-mu)T.Sigma-1.(x-mu) in a vectorized
# way across all the input variables.
fac = np.einsum('...k,kl,...l->...', pos-mu, Sigma_inv, pos-mu)
return np.exp(-fac / 2) / N
# The distribution on the variables X, Y packed into pos.
Z = multivariate_gaussian(pos, mu, Sigma)
# Create a surface plot and projected filled contour plot under it.
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z, rstride=3, cstride=3, linewidth=1, antialiased=True,
cmap=cm.viridis)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-0.15, cmap=cm.viridis)
# Adjust the limits, ticks and view angle
ax.set_zlim(-0.15,0.2)
ax.set_zticks(np.linspace(0,0.2,5))
ax.view_init(27, -21)
plt.show()
```
This is a 3D projection of the gaussians involved with the lower surface showing the 2D projection of the 3D projection above. The innermost ellipse represents the highest peak, that is the maximum probability for a given (X,Y) value.
** numpy einsum examples **
```
a = np.arange(25).reshape(5,5)
b = np.arange(5)
c = np.arange(6).reshape(2,3)
print(a)
print(b)
print(c)
#this is the diagonal sum, i repeated means the diagonal
np.einsum('ij', a)
#this takes the output ii which is the diagonal and outputs to a
np.einsum('ii->i',a)
#this takes in the array A represented by their axes 'ij' and B by its only axes'j'
#and multiples them element wise
np.einsum('ij,j',a, b)
A = np.arange(3).reshape(3,1)
B = np.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
C=np.multiply(A,B)
np.sum(C,axis=1)
D = np.array([0,1,2])
E = np.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
np.einsum('i,ij->i',D,E)
from scipy.stats import multivariate_normal
x, y = np.mgrid[-5:5:.1, -5:5:.1]
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x; pos[:, :, 1] = y
rv = multivariate_normal([0.5, -0.2], [[2.0, 0.9], [0.9, 0.5]])
plt.contourf(x, y, rv.pdf(pos))
```
### References:
1. Roger Labbe's [repo](https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python) on Kalman Filters. (Majority of the examples in the notes are from this)
2. Probabilistic Robotics by Sebastian Thrun, Wolfram Burgard and Dieter Fox, MIT Press.
3. Scipy [Documentation](https://scipython.com/blog/visualizing-the-bivariate-gaussian-distribution/)
| github_jupyter |
## Expectation Reflection for Classification
```
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
import expectation_reflection as ER
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(1)
l = 1000
n = 20
g = 3.
```
### Categorical variables
```
def synthesize_data(l,n,g,data_type='discrete'):
if data_type == 'binary':
X = np.sign(np.random.rand(l,n)-0.5)
w = np.random.normal(0.,g/np.sqrt(n),size=n)
if data_type == 'discrete':
X = 2*np.random.rand(l,n)-1
w = np.random.normal(0.,g/np.sqrt(n),size=n)
if data_type == 'categorical':
from sklearn.preprocessing import OneHotEncoder
m = 5 # categorical number for each variables
# initial s (categorical variables)
s = np.random.randint(0,m,size=(l,n)) # integer values
onehot_encoder = OneHotEncoder(sparse=False,categories='auto')
X = onehot_encoder.fit_transform(s)
w = np.random.normal(0.,g/np.sqrt(n),size=n*m)
h = X.dot(w)
p = 1/(1+np.exp(-2*h)) # kinetic
#p = 1/(1+np.exp(-h)) # logistic regression
y = np.sign(p - np.random.rand(l))
return w,X,y
w0,X,y = synthesize_data(l,n,g,data_type='categorical')
from sklearn.preprocessing import MinMaxScaler
X = MinMaxScaler().fit_transform(X)
h0,w = ER.fit(X,y,niter_max=100,regu=0.005)
plt.figure(figsize=(4,3))
plt.plot([-2,2],[-2,2],'r--')
plt.scatter(w0,w)
plt.xlabel('actual interactions')
plt.ylabel('inferred interactios')
plt.show()
y_pred = ER.predict(X,h0,w)
accuracy = accuracy_score(y,y_pred)
mse = ((w0-w)**2).mean()
print(mse,accuracy)
kf = 5
def ER_inference(X,y,kf=5,regu=0.005):
#x_train,x_test,y_train,y_test = train_test_split(X1,y,test_size=0.3,random_state = 100)
kfold = KFold(n_splits=kf,shuffle=False,random_state=1)
accuracy = np.zeros(kf)
for i,(train_index,test_index) in enumerate(kfold.split(y)):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
# predict with ER
h0,w = ER.fit(X_train,y_train,niter_max=100,regu=0.005)
y_pred = ER.predict(X_test,h0,w)
accuracy[i] = accuracy_score(y_test,y_pred)
#print(accuracy[i])
return accuracy.mean(),accuracy.std()
regu_list = [0.0,0.001,0.002,0.003,0.004,0.005,0.01,0.02,0.1,0.2,0.5,0.6,0.8,1.]
for regu in regu_list:
accuracy_mean,accuracy_std = ER_inference(X,y,kf,regu)
print('ER:',accuracy_mean,accuracy_std,regu)
```
#### Logistic Regression
```
model = LogisticRegression(solver='liblinear')
model.fit(X, y)
w_lg = 0.5*model.coef_
plt.figure(figsize=(4,3))
plt.plot([-2,2],[-2,2],'r--')
plt.scatter(w0,w_lg)
plt.xlabel('actual interactions')
plt.ylabel('inferred interactios')
plt.show()
y_pred = model.predict(X)
accuracy = accuracy_score(y,y_pred)
mse = ((w0-w_lg)**2).mean()
print(mse,accuracy)
def inference(X,y,kf=5,method='naive_bayes'):
kfold = KFold(n_splits=kf,shuffle=False,random_state=1)
accuracy = np.zeros(kf)
if method == 'logistic_regression':
model = LogisticRegression(solver='liblinear')
if method == 'naive_bayes':
model = GaussianNB()
if method == 'random_forest':
model = RandomForestClassifier(criterion = "gini", random_state = 1,
max_depth=3, min_samples_leaf=5,n_estimators=100)
if method == 'decision_tree':
model = DecisionTreeClassifier()
if method == 'knn':
model = KNeighborsClassifier()
if method == 'svm':
model = SVC(gamma='scale')
for i,(train_index,test_index) in enumerate(kfold.split(y)):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
# fit and predict
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy[i] = accuracy_score(y_test,y_pred)
#print(accuracy[i])
return accuracy.mean(),accuracy.std()
other_methods=['logistic_regression']
for i,method in enumerate(other_methods):
accuracy_mean,accuracy_std = inference(X,y,kf,method)
print('% 20s :'%method,accuracy_mean,accuracy_std)
```
| github_jupyter |
# Classifier Training
Make image size and crop size the same.
```
! rsync -a /kaggle/input/mmdetection-v280/mmdetection /
! pip install /kaggle/input/mmdetection-v280/src/mmpycocotools-12.0.3/mmpycocotools-12.0.3/
! pip install /kaggle/input/hpapytorchzoo/pytorch_zoo-master/
! pip install /kaggle/input/hpacellsegmentation/HPA-Cell-Segmentation/
! pip install /kaggle/input/iterative-stratification/iterative-stratification-master/
! cp -r /kaggle/input/kgl-humanprotein-data/kgl_humanprotein_data /
! cp -r /kaggle/input/humanpro/kgl_humanprotein /
import sys
sys.path.append('/kgl_humanprotein/')
import os
import time
from pathlib import Path
import shutil
import zipfile
import functools
import multiprocessing
import numpy as np
import pandas as pd
import cv2
from sklearn.model_selection import KFold,StratifiedKFold
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
import torch
from torch.backends import cudnn
from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler
from torch.nn import DataParallel
import matplotlib.pyplot as plt
from tqdm import tqdm
from kgl_humanprotein.utils.common_util import *
from kgl_humanprotein.config.config import *
from kgl_humanprotein.data_process import *
from kgl_humanprotein.datasets.tool import image_to_tensor
from kgl_humanprotein.networks.imageclsnet import init_network
from kgl_humanprotein.layers.loss import *
from kgl_humanprotein.layers.scheduler import *
from kgl_humanprotein.utils.augment_util import train_multi_augment2
from kgl_humanprotein.utils.log_util import Logger
from kgl_humanprotein.run.train import *
%cd /kaggle
```
## Write out 6 image-level samples from each subset for testing on laptop
```
# import shutil
# def generate_testing_samples(isubset, n_images=6, sz_img=384, dir_out=None):
# dir_subset = Path(f'/kaggle/input/humanpro-train-cells-subset{isubset}')
# dir_subset = dir_subset / f'humanpro_train_cells_subset{isubset}/train'
# df = pd.read_feather(dir_subset / 'train.feather')
# imgids = df['Id'].apply(lambda o: o.split('_')[0])
# sample_imgids = np.random.choice(imgids.unique(), n_images)
# df_sample = df[imgids.isin(sample_imgids)].reset_index(drop=True)
# if dir_out is not None:
# dir_subset_out = dir_out/'train'
# dir_subset_out.mkdir(exist_ok=True, parents=True)
# df_sample.to_feather(dir_subset_out/'train.feather')
# dir_img = dir_subset/f'images_{sz_img}'
# dir_img_out = dir_subset_out/f'images_{sz_img}'
# dir_img_out.mkdir(exist_ok=True, parents=True)
# for _, row in df_sample.iterrows():
# srcs = list(dir_img.glob(f"{row['Id']}*.png"))
# for src in srcs:
# shutil.copy(src, dir_img_out/src.name)
# return df_sample
# n_subsets = 5
# for isubset in range(n_subsets):
# print(f'\rProcessing subset {isubset}...', end='', flush=True)
# dir_out = Path(f'/kaggle/working/humanpro_train_cells_subset{isubset}')
# generate_testing_samples(isubset, dir_out=dir_out)
# ! zip -qr humanpro_train_cells_subset0.zip humanpro_train_cells_subset0/
# ! zip -qr humanpro_train_cells_subset1.zip humanpro_train_cells_subset1/
# ! zip -qr humanpro_train_cells_subset2.zip humanpro_train_cells_subset2/
# ! zip -qr humanpro_train_cells_subset3.zip humanpro_train_cells_subset3/
# ! zip -qr humanpro_train_cells_subset4.zip humanpro_train_cells_subset4/
```
## Combine subsets' meta data
```
dir_data = Path('/kaggle/input')
dir_mdata = Path('/kaggle/mdata')
n_subsets = 5
# sz_img = 384
%%time
df_cells = combine_subsets_metadata(dir_data, n_subsets)
dir_mdata_raw = dir_mdata/'raw'
dir_mdata_raw.mkdir(exist_ok=True, parents=True)
df_cells.to_feather(dir_mdata_raw/'train.feather')
del df_cells
```
## Filter samples
```
# Keep single labels
df_cells = pd.read_feather(dir_mdata_raw/'train.feather')
df_cells = (df_cells[df_cells['Target'].apply(lambda o: len(o.split('|'))==1)]
.reset_index(drop=True))
# Limit number of samples per label
def cap_number_per_label(df_cells, cap=10_000, idx_start=0):
df_cells_cap = pd.DataFrame()
for label in df_cells.Target.unique():
df = df_cells[df_cells.Target==label]
if len(df) > cap:
df = df.iloc[idx_start:idx_start + cap]
df_cells_cap = df_cells_cap.append(df, ignore_index=True)
return df_cells_cap
df_cells = cap_number_per_label(df_cells, cap=10_000, idx_start=0)
df_cells.Target.value_counts()
df_cells.to_feather(dir_mdata_raw/'train.feather')
```
## One-hot encode labels
```
%%time
generate_meta(dir_mdata, 'train.feather')
```
## Split generation
```
%%time
train_meta = pd.read_feather(dir_mdata/'meta'/'train_meta.feather')
create_random_split(dir_mdata, train_meta, n_splits=5, alias='random')
del train_meta
```
## Training
```
model_multicell = (
'../../kgl_humanprotein_data/result/models/'
'external_crop512_focal_slov_hardlog_class_densenet121_dropout_i768_aug2_5folds/'
'fold0/final.pth')
gpu_id = '0' # '0,1,2,3'
arch = 'class_densenet121_dropout'
num_classes = len(LABEL_NAME_LIST)
scheduler = 'Adam55'
epochs = 10 #55
resume = Path('/kaggle/input/humanpro-classifier/results/models/'
'external_crop384_focal_slov_hardlog_class_densenet121_dropout_i384_aug2_5folds/fold0/final.pth')
sz_img = 384
crop_size = 384
batch_size = 32
split_name = 'random_folds5'
fold = 0
workers = 3
pin_memory = True
dir_results = Path('results')
dir_results.mkdir(exist_ok=True, parents=True)
out_dir = Path(f'external_crop{crop_size}_focal_slov_hardlog_class_densenet121_dropout_i{sz_img}_aug2_5folds')
main_training(dir_data, dir_mdata, dir_results, out_dir,
split_name=split_name, fold=fold,
arch=arch, model_multicell=model_multicell, scheduler=scheduler,
epochs=epochs, resume=resume,
img_size=sz_img, crop_size=crop_size, batch_size=batch_size,
gpu_id=gpu_id, workers=workers, pin_memory=pin_memory)
! cp -r results/ /kaggle/working/.
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit # import the curve fitting function
import pandas as pd
%matplotlib inline
```
## Argon
```
Argon = pd.read_table('Ar.txt',delimiter=', ',engine='python', header=None)
Amu = Argon[0] #These are the values of amu that the mass spec searches for
Argon = np.array([entry[:-1] for entry in Argon[1]],dtype='float')*1e6
```
### Raw Argon Data
```
plt.figure(figsize=(9,4))
plt.scatter(Amu, Argon);
ax = plt.gca()
#ax.set_yscale('log')
plt.xlim(12,45);
plt.ylim(0,4)
plt.xlabel('Particle Mass [Amu]',size=18);
plt.ylabel('Pressure [Torr]$\cdot 10^{-6}$',size=18);
plt.xticks(size = 11);
plt.yticks(size = 11);
plt.savefig('RawArgon.png')
```
### Substract Argon Background
```
Arbkd = pd.read_table('Background_Ar.txt',delimiter=', ',engine='python', header=None)
Arbkd = np.array([entry[:-1] for entry in Arbkd[1]],dtype='float')*1e6
plt.figure(figsize=(9,4))
plt.scatter(Amu, Argon - Arbkd);
ax = plt.gca()
#ax.set_yscale('log')
plt.xlim(12,45);
plt.ylim(0,4)
plt.xlabel('Particle Mass [Amu]',size=18);
plt.ylabel('Pressure [Torr]$\cdot 10^{-6}$',size=18);
plt.xticks(size = 11);
plt.yticks(size = 11);
plt.savefig('TrueArgon.png')
```
Upon close inspection, background substraction has removed a single peak near 19 amu.
## Kyrpton
```
Krypton = pd.read_table('Kr.txt',delimiter=', ',engine='python', header=None)
Krypton = np.array([entry[:-1] for entry in Krypton[1]],dtype='float')*1e6
Krbkd = pd.read_table('Background_Kr.txt',delimiter=', ',engine='python', header=None)
Krbkd = np.array([entry[:-1] for entry in Krbkd[1]],dtype='float')*1e6
plt.figure(figsize=(9,4))
plt.scatter(Amu, Krypton - Krbkd);
ax = plt.gca()
plt.xlim(12,45);
plt.ylim(0,6)
plt.xlabel('Particle Mass [Amu]',size=18);
plt.ylabel('Pressure [Torr]$\cdot 10^{-6}$',size=18);
plt.xticks(size = 11);
plt.yticks(size = 11);
plt.savefig('Krypton.png')
```
Here, and for all subsequent measurements on this day, there is a slight peak at 40 amu, which is to be some residual from the Argon test.
## Neon
```
Neon = pd.read_table('Ne.txt',delimiter=', ',engine='python', header=None)
Neon = np.array([entry[:-1] for entry in Neon[1]],dtype='float')*1e6
Nebkd = pd.read_table('Background_Ne.txt',delimiter=', ',engine='python', header=None)
Nebkd = np.array([entry[:-1] for entry in Nebkd[1]],dtype='float')*1e6
plt.figure(figsize=(9,4))
plt.scatter(Amu, Neon - Nebkd);
ax = plt.gca()
plt.xlim(12,35);
plt.ylim(0,3.2)
plt.xlabel('Particle Mass [Amu]',size=18);
plt.ylabel('Pressure [Torr]$\cdot 10^{-6}$',size=18);
plt.xticks(size = 11);
plt.yticks(size = 11);
plt.savefig('Neon.png')
```
## Air
```
Air = pd.read_table('Air.txt',delimiter=', ',engine='python', header=None)
Air = np.array([entry[:-1] for entry in Air[1]],dtype='float')*1e6
plt.figure(figsize=(9,4))
plt.scatter(Amu, Air - Nebkd);
ax = plt.gca()
plt.xlim(12,35);
plt.ylim(0,3.2)
plt.xlabel('Particle Mass [Amu]',size=18);
plt.ylabel('Pressure [Torr]$\cdot 10^{-6}$',size=18);
plt.xticks(size = 11);
plt.yticks(size = 11);
plt.savefig('Air.png')
```
# Day 2
## Quick Exhale vs Hold Breath
```
Quick = pd.read_table('QuickExhale.txt',delimiter=', ',engine='python', header=None)
Quick = np.array([entry[:-1] for entry in Quick[1]],dtype='float')*1e6
Quickbkd = pd.read_table('Background_Breath.txt',delimiter=', ',engine='python', header=None)
Quickbkd = np.array([entry[:-1] for entry in Quickbkd[1]],dtype='float')*1e6
Hold = pd.read_table('HoldBreath30s.txt',delimiter=', ',engine='python', header=None)
Hold = np.array([entry[:-1] for entry in Hold[1]],dtype='float')*1e6
plt.figure(figsize=(9,4))
plt.scatter(Amu, Quick - Quickbkd,color='blue',label='Quick Exhale');
plt.scatter(Amu, Hold - Quickbkd,color='red',label = 'Hold Breath');
ax = plt.gca()
plt.xlim(12,35);
plt.ylim(0,8.5)
plt.xlabel('Particle Mass [Amu]',size=18);
plt.ylabel('Pressure [Torr]$\cdot 10^{-6}$',size=18);
plt.xticks(size = 11);
plt.yticks(size = 11);
plt.legend(loc='upper left')
plt.savefig('Breath.png')
```
## Compressed Air Comparison
```
Can1 = pd.read_table('CompressedAir_Tetrafluoroethane.txt',delimiter=', ',engine='python', header=None)
Can1 = np.array([entry[:-1] for entry in Can1[1]],dtype='float')*1e6
Can2 = pd.read_table('CompressedAir_Difluoroethane.txt',delimiter=', ',engine='python', header=None)
Can2 = np.array([entry[:-1] for entry in Can2[1]],dtype='float')*1e6
plt.figure(figsize=(9,4))
plt.scatter(Amu, Can1 - Quickbkd,color='blue',label='Tetrafluoroethane');
plt.scatter(Amu, Can2 - Quickbkd,color='red',label = 'Difluoroethane');
ax = plt.gca()
plt.xlim(10,65);
plt.ylim(0,8.5)
plt.xlabel('Particle Mass [Amu]',size=18);
plt.ylabel('Pressure [Torr]$\cdot 10^{-6}$',size=18);
plt.xticks(size = 11);
plt.yticks(size = 11);
plt.legend(loc='upper right')
plt.savefig('CompressedAir.png')
Volcano = pd.read_table('Volcano.txt',delimiter=', ',engine='python', header=None)
Volcano = np.array([entry[:-1] for entry in Volcano[1]],dtype='float')*1e6
VolcanoBackground = pd.read_table('VolcanoBackground.txt',delimiter=', ',engine='python', header=None)
VolcanoBackground = np.array([entry[:-1] for entry in VolcanoBackground[1]],dtype='float')*1e6
plt.figure(figsize=(9,4))
plt.scatter(Amu, Volcano - VolcanoBackground);
ax = plt.gca()
plt.xlim(10,35);
plt.ylim(0,8.5)
plt.xlabel('Particle Mass [Amu]',size=18);
plt.ylabel('Pressure [Torr]$\cdot 10^{-6}$',size=18);
plt.xticks(size = 11);
plt.yticks(size = 11);
plt.savefig('Volcano.png')
```
| github_jupyter |
```
import json
import pathlib
import numpy as np
import sklearn
import yaml
from sklearn.preprocessing import normalize
from numba import jit
from utils import get_weight_path_in_current_system
def load_features() -> dict:
datasets = ("cifar10", "cifar100", "ag_news")
epochs = (500, 500, 100)
features = {}
for dataset, epoch in zip(datasets, epochs):
base_dir = pathlib.Path("../results/{}/analysis/save_unnormalised_feature/".format(dataset))
for config_path in base_dir.glob("**/config.yaml"):
with open(config_path) as f:
config = yaml.load(f, Loader=yaml.FullLoader)
seed = config["experiment"]["seed"]
if config["experiment"]["use_projection_head"]:
extractor = "Head"
else:
extractor = "Without Head"
self_sup_path = pathlib.Path(
get_weight_path_in_current_system(config["experiment"]["target_weight_file"])).parent
with open(self_sup_path / ".hydra" / "config.yaml") as f:
config = yaml.load(f, Loader=yaml.FullLoader)
num_mini_batches = config["experiment"]["batches"]
path = config_path.parent.parent
d = dataset.replace("100", "").replace("10", "")
y_train = np.load(path / "epoch_{}-{}.pt.label.train.npy".format(epoch, d))
X_train_0 = np.load(path / "epoch_{}-{}.pt.feature.0.train.npy".format(epoch, d))
X_train_1 = np.load(path / "epoch_{}-{}.pt.feature.1.train.npy".format(epoch, d))
d_name = dataset
if "augmentation_type" in config["dataset"]:
d_name = "{}-{}".format(dataset, config["dataset"]["augmentation_type"])
if d_name not in features:
features[d_name] = {}
if extractor not in features[d_name]:
features[d_name][extractor] = {}
if seed not in features[d_name][extractor]:
features[d_name][extractor][seed] = {}
features[d_name][extractor][seed][num_mini_batches] = (
X_train_0,
X_train_1,
y_train
)
return features
features = load_features()
@jit(nopython=True, parallel=True)
def compute_bound(c, y_train, X_train_0, X_train_1):
target_ids = y_train == c
X_train_0_c = X_train_0[target_ids]
X_train_1_c = X_train_1[target_ids]
cos_sim = X_train_0_c.dot(X_train_1_c.T)
n = np.sum(target_ids)
bounds_by_sample = np.abs(cos_sim - np.diag(cos_sim)).sum(axis=0) / (n - 1)
return bounds_by_sample
upper_bound_collision = {}
for dataset, f_d in features.items():
upper_bound_collision[dataset] = {}
for head_info, f_d_h in f_d.items():
upper_bound_collision[dataset][head_info] = {}
for seed, f_d_h_s in f_d_h.items():
negs = list(sorted(f_d_h_s))
for i, neg in enumerate(negs):
if neg not in upper_bound_collision[dataset][head_info]:
upper_bound_collision[dataset][head_info][neg] = []
X_train_0, X_train_1, y_train = f_d_h[seed][neg]
C = len(np.unique(y_train))
X_train_0 = sklearn.preprocessing.normalize(X_train_0, axis=1)
X_train_1 = sklearn.preprocessing.normalize(X_train_1, axis=1)
upper_bounds = []
for c in range(C):
upper_bounds.append(
compute_bound(c, y_train, X_train_0, X_train_1)
)
upper_bound = np.array(upper_bounds).flatten().mean()
print(dataset, head_info, seed, neg, upper_bound)
upper_bound_collision[dataset][head_info][neg].append(float(upper_bound))
with open("upper_bound_collision.json", "w") as f:
json.dump(upper_bound_collision, f)
```
| github_jupyter |
```
from wikification import wikification, wikification_filter
TEST_PATH = "test.txt"
with open(TEST_PATH, "r") as f:
text = "\n".join(f.readlines())
len(text)
res = wikification(text[:10000],
wikification_type="FULL",
long_text_method_name="sum_classic_page_rank")
len(res["words"])
res["concepts"] # attention chunk 0 ?
wikification_filter(res, "SIMPLE", in_place=False)
wikification_filter(res, "CLASSIC", in_place=False)
res
```
Test SAHAN
```
PATH = "/home/benromdhane-w/Bureau/ls2n/projects/X5GON/hackaton/x5gon_hackathon_materials/x5gon_materials_catelogue.tsv"
PATHOUT = "/home/benromdhane-w/Bureau/ls2n/projects/X5GON/hackaton/x5gon_hackathon_materials/comparewiki.tsv"
import psycopg2
PGCred = dict(PGHOST='127.0.0.1',
PGDATABASE='x5gon',
PGUSER='developernantestest',
PGPASSWORD='devntes#51!&#test',
PGPORT='5555')
def db_connect(PGHOST:str,PGDATABASE:str,PGUSER:str,PGPASSWORD:str,PGPORT:str):
# Set up a connection to the postgres server.
conn_string = "host="+ PGHOST +" port="+ PGPORT +" dbname="+ PGDATABASE +" user=" + PGUSER +" password="+ PGPASSWORD
conn=psycopg2.connect(conn_string)
conn.set_session(autocommit=True)
cursor = conn.cursor()
return {'connexion': conn, 'cursor': cursor}
connexion = db_connect(PGCred['PGHOST'],
PGCred['PGDATABASE'],
PGCred['PGUSER'],
PGCred['PGPASSWORD'],
PGCred['PGPORT'])
def get_data_generator(rid, *, verbose=True):
query = "SELECT value FROM material_contents WHERE material_id=" + rid + " AND language='en' AND extension='plain';"
# query exec
if verbose: print("Sending query...")
try:
cursor = connexion["cursor"]
cursor.execute(query)
except:
print("Error when executing the query: verify it !")
if verbose: print("Query processed!")
return cursor
import csv
import spacy
import time
nlp = spacy.load("en")
from wikification import LONG_TEXT_METHODS, wikification
# del LONG_TEXT_METHODS["sum_page_rank"]
nb = 0
with open(PATH, "r") as csvfile:
with open(PATHOUT, "w") as csvout:
csv_reader = csv.reader(csvfile, delimiter="\t", quotechar='"', quoting=csv.QUOTE_ALL)
fields = next(csv_reader)
print(fields)
csv_writer = csv.writer(csvout, delimiter="\t", quotechar='"')
csv_writer.writerow(fields + ["concepts sum_classic_page_rank cos",
"concepts sum_classic_page_rank pk",
"concepts sum_classic_page_rank cos top10",
"concepts sum_classic_page_rank pk top10",
"concepts recompute_on_anchor_text cos",
"concepts recompute_on_anchor_text pk",
"concepts recompute_on_anchor_text cos top10",
"concepts recompute_on_anchor_text pk top10",
"concepts sum_classic_page time",
"concepts recompute_on_anchor_text time"])
for row in csv_reader:
nb += 1
print(nb)
rid = row[1]
try:
text = next(get_data_generator(rid, verbose=False))[0]["value"]
except StopIteration:
print(row, " has no en version in db!")
wikifications = []
runtime = []
for m in LONG_TEXT_METHODS:
print(f"Wikification {m}...")
start = time.time()
res = [(c['url'], c['title'], c['pageRank'], c['cosine']) for c in wikification(text, long_text_method_name=m)]
end = time.time()
ccos = sorted(res, key=lambda x: x[3], reverse=True)
cpr = sorted(res, key=lambda x: x[2], reverse=True)
top10cos = [c[1] for c in ccos[:10]]
top10pr = [c[1] for c in cpr[:10]]
wikifications.extend([ccos, cpr, top10cos, top10pr])
runtime.append(end - start)
print(f"{m} elapsed time: %f ms" % (1000*(end - start)))
csv_writer.writerow(row + wikifications + runtime)
if nb > 100: break
times
wikifications = {k: sorted(v, key=lambda x: x[2], reverse=True)[:20] for k, v in wikifications.items()}
wikifications["sum_classic_page_rank"]
wikifications["recompute_on_anchor_text"]
```
| github_jupyter |
```
"""
created by Arj at 16:28 BST
#Section
Investigating the challenge notebook and running it's code.
#Subsection
Running a simulated qubit with errors
"""
import matplotlib.pyplot as plt
import numpy as np
from qctrlvisualizer import get_qctrl_style, plot_controls
from qctrl import Qctrl
plt.style.use(get_qctrl_style())
qctrl = Qctrl()
def simulate_more_realistic_qubit(
duration=1, values=np.array([np.pi]), shots=1024, repetitions=1
):
# 1. Limits for drive amplitudes
assert np.amax(values) <= 1.0
assert np.amin(values) >= -1.0
max_drive_amplitude = 2 * np.pi * 20 # MHz
# 2. Dephasing error
dephasing_error = -2 * 2 * np.pi # MHz
# 3. Amplitude error
amplitude_i_error = 0.98
amplitude_q_error = 1.03
# 4. Control line bandwidth limit
cut_off_frequency = 2 * np.pi * 10 # MHz
resample_segment_count = 1000
# 5. SPAM error confusion matrix
confusion_matrix = np.array([[0.99, 0.01], [0.02, 0.98]])
# Lowering operator
b = np.array([[0, 1], [0, 0]])
# Number operator
n = np.diag([0, 1])
# Initial state
initial_state = np.array([[1], [0]])
with qctrl.create_graph() as graph:
# Apply 1. max Rabi rate.
values = values * max_drive_amplitude
# Apply 3. amplitude errors.
values_i = np.real(values) * amplitude_i_error
values_q = np.imag(values) * amplitude_q_error
values = values_i + 1j * values_q
# Apply 4. bandwidth limits
drive_unfiltered = qctrl.operations.pwc_signal(duration=duration, values=values)
drive_filtered = qctrl.operations.convolve_pwc(
pwc=drive_unfiltered,
kernel_integral=qctrl.operations.sinc_integral_function(cut_off_frequency),
)
drive = qctrl.operations.discretize_stf(
drive_filtered, duration=duration, segments_count=resample_segment_count
)
# Construct microwave drive
drive_term = qctrl.operations.pwc_operator_hermitian_part(
qctrl.operations.pwc_operator(signal=drive, operator=b)
)
# Construct 2. dephasing term.
dephasing_term = qctrl.operations.constant_pwc_operator(
operator=dephasing_error * n,
duration=duration,
)
# Construct Hamiltonian.
hamiltonian = qctrl.operations.pwc_sum(
[
drive_term,
dephasing_term,
]
)
# Solve Schrodinger's equation and get total unitary at the end
unitary = qctrl.operations.time_evolution_operators_pwc(
hamiltonian=hamiltonian,
sample_times=np.array([duration]),
)[-1]
unitary.name = "unitary"
# Repeat final unitary
repeated_unitary = np.eye(2)
for _ in range(repetitions):
repeated_unitary = repeated_unitary @ unitary
repeated_unitary.name = "repeated_unitary"
# Calculate final state.
state = repeated_unitary @ initial_state
# Calculate final populations.
populations = qctrl.operations.abs(state[:, 0]) ** 2
# Normalize populations
norm = qctrl.operations.sum(populations)
populations = populations / norm
populations.name = "populations"
# Evaluate graph.
result = qctrl.functions.calculate_graph(
graph=graph,
output_node_names=["unitary", "repeated_unitary", "populations"],
)
# Extract outputs.
unitary = result.output["unitary"]["value"]
repeated_unitary = result.output["repeated_unitary"]["value"]
populations = result.output["populations"]["value"]
# Sample projective measurements.
true_measurements = np.random.choice(2, size=shots, p=populations)
measurements = np.array(
[np.random.choice(2, p=confusion_matrix[m]) for m in true_measurements]
)
results = {"unitary": unitary, "measurements": measurements}
return results
max_rabi_rate = 20 * 2 * np.pi # MHz
not_duration = np.pi / (max_rabi_rate) # us
h_duration = np.pi / (2 * max_rabi_rate) # us
shots = 1024
values = np.array([1.0])
not_results = simulate_more_realistic_qubit(
duration=not_duration, values=values, shots=shots
)
h_results = simulate_more_realistic_qubit(
duration=h_duration, values=values, shots=shots
)
error_norm = (
lambda operate_a, operator_b: 1
- np.abs(np.trace((operate_a.conj().T @ operator_b)) / 2) ** 2
)
def estimate_probability_of_one(measurements):
size = len(measurements)
probability = np.mean(measurements)
standard_error = np.std(measurements) / np.sqrt(size)
return (probability, standard_error)
realised_not_gate = not_results["unitary"]
ideal_not_gate = np.array([[0, -1j], [-1j, 0]])
not_error = error_norm(realised_not_gate, ideal_not_gate)
realised_h_gate = h_results["unitary"]
ideal_h_gate = (1 / np.sqrt(2)) * np.array([[1, -1j], [-1j, 1]])
h_error = error_norm(realised_h_gate, ideal_h_gate)
not_measurements = not_results["measurements"]
h_measurements = h_results["measurements"]
not_probability, not_standard_error = estimate_probability_of_one(not_measurements)
h_probability, h_standard_error = estimate_probability_of_one(h_measurements)
print("Realised NOT Gate:")
print(realised_not_gate)
print("Ideal NOT Gate:")
print(ideal_not_gate)
print("NOT Gate Error:" + str(not_error))
print("NOT estimated probability of getting 1:" + str(not_probability))
print("NOT estimate standard error:" + str(not_standard_error) + "\n")
print("Realised H Gate:")
print(realised_h_gate)
print("Ideal H Gate:")
print(ideal_h_gate)
print("H Gate Error:" + str(h_error))
print("H estimated probability of getting 1:" + str(h_probability))
print("H estimate standard error:" + str(h_standard_error))
# Now using the CLHO
# Define standard matrices.
sigma_x = np.array([[0, 1], [1, 0]], dtype=np.complex)
sigma_y = np.array([[0, -1j], [1j, 0]], dtype=np.complex)
sigma_z = np.array([[1, 0], [0, -1]], dtype=np.complex)
# Define control parameters.
duration = 1e-6 # s
# Define standard deviation of the errors in the experimental results.
sigma = 0.01
# Create a random unknown operator.
rng = np.random.default_rng(seed=10)
phi = rng.uniform(-np.pi, np.pi)
u = rng.uniform(-1, 1)
Q_unknown = (
u * sigma_z + np.sqrt(1 - u ** 2) * (np.cos(phi) * sigma_x + np.sin(phi) * sigma_y)
) / 4
def run_experiments(omegas):
"""
Simulates a series of experiments where controls `omegas` attempt to apply
an X gate to a system. The result of each experiment is the infidelity plus
a Gaussian error.
In your actual implementation, this function would run the experiment with
the parameters passed. Note that the simulation handles multiple test points,
while your experimental implementation might need to queue the test point
requests to obtain one at a time from the apparatus.
"""
# Create the graph with the dynamics of the system.
with qctrl.create_graph() as graph:
signal = qctrl.operations.pwc_signal(values=omegas, duration=duration)
hamiltonian = qctrl.operations.pwc_operator(
signal=signal,
operator=0.5 * (sigma_x + Q_unknown),
)
qctrl.operations.infidelity_pwc(
hamiltonian=hamiltonian,
target_operator=qctrl.operations.target(operator=sigma_x),
name="infidelities",
)
# Run the simulation.
result = qctrl.functions.calculate_graph(
graph=graph,
output_node_names=["infidelities"],
)
# Add error to the measurement.
error_values = rng.normal(loc=0, scale=sigma, size=len(omegas))
infidelities = result.output["infidelities"]["value"] + error_values
# Return only infidelities between 0 and 1.
return np.clip(infidelities, 0, 1)
# Define the number of test points obtained per run.
test_point_count = 20
# Define number of segments in the control.
segment_count = 10
# Define parameters as a set of controls with piecewise constant segments.
parameter_set = (
np.pi
/ duration
* (np.linspace(-1, 1, test_point_count)[:, None])
* np.ones((test_point_count, segment_count))
)
# Obtain a set of initial experimental results.
experiment_results = run_experiments(parameter_set)
# Define initialization object for the automated closed-loop optimization.
length_scale_bound = qctrl.types.closed_loop_optimization_step.BoxConstraint(
lower_bound=1e-5,
upper_bound=1e5,
)
bound = qctrl.types.closed_loop_optimization_step.BoxConstraint(
lower_bound=-5 * np.pi / duration,
upper_bound=5 * np.pi / duration,
)
initializer = qctrl.types.closed_loop_optimization_step.GaussianProcessInitializer(
length_scale_bounds=[length_scale_bound] * segment_count,
bounds=[bound] * segment_count,
rng_seed=0,
)
# Define state object for the closed-loop optimization.
optimizer = qctrl.types.closed_loop_optimization_step.Optimizer(
gaussian_process_initializer=initializer,
)
```
| github_jupyter |
```
import os
import pandas as pd
def load_data(path):
full_path = os.path.join(os.path.realpath('..'), path)
df = pd.read_csv(full_path, header=0, index_col=0)
print("Dataset has {} rows, {} columns.".format(*df.shape))
return df
df_train = load_data('data/raw/train.csv')
df_test = load_data('data/raw/test.csv')
```
## Data cleaning
```
# fill NaN with string "unknown"
df_train.fillna('unknown',inplace=True)
df_test.fillna('unknown',inplace=True)
```
## Create features
```
def create_features(df):
"Create features as seen in EDA"
print("Dataframe as {} rows and {} columns.".format(*df.shape))
# Uppercase count
df['processed'] = df['comment_text'].str.split()
print("Counting uppercases...")
df['uppercase_count'] = df['processed'].apply(lambda x: sum(1 for t in x if t.isupper() and len(t)>2))
print("Dataframe as {} rows and {} columns.".format(*df.shape))
# Bad words
print("Counting bad words...")
path = 'data/external/badwords.txt'
bad_words = []
f = open(os.path.join(os.path.realpath('..'), path), mode='rt', encoding='utf-8')
for line in f:
words = line.split(', ')
for word in words:
word = word.replace('\n', '')
bad_words.append(word)
f.close()
df['bad_words'] = df['processed'].apply(lambda x: sum(1 for t in x if t in bad_words))
print("Dataframe as {} rows and {} columns.".format(*df.shape))
# Count of typos
from enchant.checker import SpellChecker
def typo_count(corpus):
"Count the number of errors found by pyenchant"
count = []
for row in corpus:
chkr = SpellChecker("en_US")
chkr.set_text(row)
i = 0
for err in chkr:
i += 1
count.append(i)
return count
print("Counting typos...")
df['typos'] = typo_count(df.comment_text)
print("Dataframe as {} rows and {} columns.".format(*df.shape))
# Doc length
print("Counting length of each comment...")
df['length'] = [len(t) for t in df['processed']]
print("Dataframe as {} rows and {} columns.".format(*df.shape))
# Drop processed (helper column)
df = df.drop(['processed'], axis=1)
print("Dataframe as {} rows and {} columns.".format(*df.shape))
return df
df_train = create_features(df_train)
df_test = create_features(df_test)
```
## Spell check - TBC
```
import enchant
from enchant.checker import SpellChecker
from enchant.checker import SpellChecker
def spellcheck(corpus):
"Spellcheck using pyenchant"
for row in corpus:
chkr = SpellChecker("en_US")
chkr.set_text(row)
for err in chkr:
sug = err.suggest()[0]
err.replace(sug)
print(err.word, sug)
row = chkr.get_text()
return corpus
spellcheck(df_train.comment_text[:5])
```
## Output
```
# save list to file
def save_list(lines, filename):
# convert lines to a single blob of text data = '\n'.join(lines)
data = '\n'.join(lines)
# open file
file = open(filename, 'w')
# write text
file.write(data)
# close file
file.close()
def save_df(df, path):
full_path = os.path.join(os.path.realpath('..'), path)
df.to_csv(full_path, header=True, index=True)
print('Dataframe ({}, {}) saved as csv.'.format(*df.shape))
save_df(df_train, 'data/processed/train.csv')
save_df(df_test, 'data/processed/test.csv')
```
| github_jupyter |
## Sentiment Analysis with MXNet and Gluon
This tutorial will show how to train and test a Sentiment Analysis (Text Classification) model on SageMaker using MXNet and the Gluon API.
```
import os
import boto3
import sagemaker
from sagemaker.mxnet import MXNet
from sagemaker import get_execution_role
sagemaker_session = sagemaker.Session()
role = get_execution_role()
```
## Download training and test data
In this notebook, we will train the **Sentiment Analysis** model on [SST-2 dataset (Stanford Sentiment Treebank 2)](https://nlp.stanford.edu/sentiment/index.html). The dataset consists of movie reviews with one sentence per review. Classification involves detecting positive/negative reviews.
We will download the preprocessed version of this dataset from the links below. Each line in the dataset has space separated tokens, the first token being the label: 1 for positive and 0 for negative.
```
%%bash
mkdir data
curl https://raw.githubusercontent.com/saurabh3949/Text-Classification-Datasets/master/stsa.binary.phrases.train > data/train
curl https://raw.githubusercontent.com/saurabh3949/Text-Classification-Datasets/master/stsa.binary.test > data/test
```
## Uploading the data
We use the `sagemaker.Session.upload_data` function to upload our datasets to an S3 location. The return value `inputs` identifies the location -- we will use this later when we start the training job.
```
inputs = sagemaker_session.upload_data(path='data', key_prefix='data/DEMO-sentiment')
```
## Implement the training function
We need to provide a training script that can run on the SageMaker platform. The training scripts are essentially the same as one you would write for local training, except that you need to provide a `train` function. When SageMaker calls your function, it will pass in arguments that describe the training environment. Check the script below to see how this works.
The script here is a simplified implementation of ["Bag of Tricks for Efficient Text Classification"](https://arxiv.org/abs/1607.01759), as implemented by Facebook's [FastText](https://github.com/facebookresearch/fastText/) for text classification. The model maps each word to a vector and averages vectors of all the words in a sentence to form a hidden representation of the sentence, which is inputted to a softmax classification layer. Please refer to the paper for more details.
```
!cat 'sentiment.py'
```
## Run the training script on SageMaker
The ```MXNet``` class allows us to run our training function on SageMaker infrastructure. We need to configure it with our training script, an IAM role, the number of training instances, and the training instance type. In this case we will run our training job on a single c4.2xlarge instance.
```
m = MXNet('sentiment.py',
role=role,
train_instance_count=1,
train_instance_type='ml.c4.xlarge',
framework_version='1.4.0',
py_version='py2',
distributions={'parameter_server': {'enabled': True}},
hyperparameters={'batch-size': 8,
'epochs': 2,
'learning-rate': 0.01,
'embedding-size': 50,
'log-interval': 1000})
```
After we've constructed our `MXNet` object, we can fit it using the data we uploaded to S3. SageMaker makes sure our data is available in the local filesystem, so our training script can simply read the data from disk.
```
m.fit(inputs)
```
As can be seen from the logs, we get > 80% accuracy on the test set using the above hyperparameters.
After training, we use the MXNet object to build and deploy an MXNetPredictor object. This creates a SageMaker endpoint that we can use to perform inference.
This allows us to perform inference on json encoded string array.
```
predictor = m.deploy(initial_instance_count=1, instance_type='ml.c4.xlarge')
```
The predictor runs inference on our input data and returns the predicted sentiment (1 for positive and 0 for negative).
```
data = ["this movie was extremely good .",
"the plot was very boring .",
"this film is so slick , superficial and trend-hoppy .",
"i just could not watch it till the end .",
"the movie was so enthralling !"]
response = predictor.predict(data)
print(response)
```
## Cleanup
After you have finished with this example, remember to delete the prediction endpoint to release the instance(s) associated with it.
```
predictor.delete_endpoint()
```
| github_jupyter |
"Geo Data Science with Python"
### Notebook Lesson 3
# Object Type: Dictionaries
This lesson discusses the Python object type **Dictionaries**. Carefully study the content of this Notebook and use the chance to reflect the material through the interactive examples.
### Sources
This lesson is an adaption of the lesson [Understanding Dictionaries in Python 3](https://www.digitalocean.com/community/tutorials/understanding-dictionaries-in-python-3) of the [Digital Ocean Community](https://www.digitalocean.com/community).
---
## Part A: Introduction
Table 1 provides a comprehensive overview of Python object classifications. The table gives information about their mutability and their category. The sequential character of strings and lists was emphasized in the last notebooks. Now we want to look at another type of objects in Python that provides the most flexibility: *Dictionaries*. Tuples, Sets and Files will be discussed in the upcoming notebooks.
Table 1. *Object Cassifications* (Lutz, 2013)
| Object Type | Category | Mutable? |
| :---------: | :-------: | :-------: |
| Numbers (all) | Numeric | No |
| Strings | Sequence | No |
| Lists | Sequence | Yes |
| Dictionaries | Mapping | Yes |
| Files | Extention | N/A |
| Tuples | Sequence | No |
| Sets | Set | Yes |
| `frozenset` | Set | No |
The dictionary is Python’s built-in *mapping* type. Dictionaries map *keys* to *values* and these key-value pairs provide a useful way to store data in Python. Since dictionaries are mutable, they allow **mutable data mapping**.
<div class="alert alert-info">
**Note**
Dictionaries are an unordered collection of arbritrary objects (no sequences) of variable length. They are similar to lists, but provide more general data access, since accessing the content is not limited to index numbers and it can be achieved by other types of indices.
</div>
Dictionaries are typically used to hold data that are related, such as the information contained in an ID or a user profile. They are constructed with curly braces on either side `{` `}`.
A simple example for a dictionary looks like this:
```
sammy = {'username': 'sammy-shark', 'online': True, 'followers': 987}
type(sammy)
```
In addition to the curly braces, there are also colons (`:`) throughout the dictionary.
The words to the left of the colons are the keys. *Keys* can be made up of any immutable data type. The keys in the dictionary above are:
* `'username'`
* `'online'`
* `'followers'`
Keys have to be of immutable object type, like numbers or strings. Each of the keys in the above example are string values.
The words to the right of the colons are the values. Values can be comprised of any data type. The values in the dictionary above are:
* `'sammy-shark'`
* `True`
* `987`
Each of these values is either a string, Boolean, or integer.
Let’s print out the dictionary `sammy`:
```
print(sammy)
```
Looking at the output, the order of the key-value pairs may have shifted. In Python version 3.5 and earlier, the dictionary data type is unordered. However, in Python version 3.6 and later, the dictionary data type remains ordered. Regardless of whether the dictionary is ordered or not, the key-value pairs will remain intact, enabling us to access data based on their relational meaning.
# Part B: Accessing Dictionary Elements
We can call the values of a dictionary by referencing the related keys.
### Accessing Data Items with Keys
Because dictionaries offer key-value pairs for storing data, they can be important elements in your Python program.
If we want to isolate Sammy’s username, we can do so by calling `sammy['username']`. Let’s print that out:
```
print(sammy['username'])
```
Dictionaries behave like a database in that instead of calling an integer to get a particular index value as you would with a list, you assign a value to a key and can call that key to get its related value.
By invoking the key `'username'` we receive the value of that key, which is `'sammy-shark'`.
The remaining values in the `sammy` dictionary can similarly be called using the same format:
```
sammy['followers']
sammy['online']
```
By making use of dictionaries’ key-value pairs, we can reference keys to retrieve values.
### Using Methods to Access Elements
In addition to using keys to access values, we can also work with some type-specific methods is a placeholder for the name of a dictionary):
* `.keys()` isolates keys
* `.values()` isolates values
* `.items()` returns items in a list format of `(key, value)` tuple pairs
To return the keys, we would use the `.keys()` method. In our example, that would use the variable name and be `sammy.keys()`. Let’s pass that to a `print()` method and look at the output:
```
print(sammy.keys())
type(sammy.keys())
```
We receive output that places the keys within an iterable view object of the `dict_keys` class. The keys are then printed within a list format.
This method can be used to query across dictionaries. For example, we could take a look at the common keys shared between two dictionary data structures:
```
sammy = {'username': 'sammy-shark', 'online': True, 'followers': 987}
jesse = {'username': 'JOctopus', 'online': False, 'points': 723}
```
The dictionary `sammy` and the dictionary `jesse` are each a user profile dictionary.
Their profiles have different keys, however, because Sammy has a social profile with associated followers, and Jesse has a gaming profile with associated points. The two keys they have in common are `username` and `online` status, which we can find when we run this small program:
```
for common_key in sammy.keys() & jesse.keys():
print(sammy[common_key], jesse[common_key])
```
We could certainly improve on the program to make the output more user-readable, but this illustrates that the method `.keys()` can be used to check across various dictionaries to see what they share in common or not. This is especially useful for large dictionaries.
Similarly, we can use the `.values()` method to query the values in the `sammy` dictionary, which would be constructed as `sammy.values()`. Let’s print those out:
```
sammy = {'username': 'sammy-shark', 'online': True, 'followers': 987}
print(sammy.values())
```
Both the methods `keys()` and `values()` return unsorted lists of the keys and values present in the `sammy` dictionary with the view objects of `dict_keys` and `dict_values` respectively.
If we are interested in all of the items in a dictionary, we can access them with the `items()` method:
```
print(sammy.items())
```
The returned format of this is a list made up of `(key, value)` tuple pairs with the `dict_items` view object. We will discuss tuples in the next notebook lesson.
We can iterate over the returned list format with a `for` loop. For example, we can print out both at the same time keys and values of a given dictionary, and then make it more human-readable by adding a string:
```
for key, value in sammy.items():
print(key, 'is the key for the value', value)
```
The `for` loop above iterated over the items within the sammy dictionary and printed out the keys and values line by line, with information to make it easier to understand by humans.
We can use built-in methods to access items, values, and keys from dictionary data structures.
# Part C: Modifying Dictionaries
Dictionaries are a mutable data structure, so you are able to modify them. In this section, we’ll go over adding and deleting dictionary elements.
### Adding and Changing Dictionary Elements
Without using a method or function, you can add key-value pairs to dictionaries by using the following syntax:
`dict[key] = value`.
We’ll look at how this works in practice by adding a key-value pair to a dictionary called `usernames`:
```
usernames = {'Sammy': 'sammy-shark', 'Jamie': 'mantisshrimp54'}
usernames['Drew'] = 'squidly'
print(usernames)
```
We see now that the dictionary has been updated with the `'Drew': 'squidly'` key-value pair. Because dictionaries may be unordered, this pair may occur anywhere in the dictionary output. If we use the `usernames` dictionary later in our program file, it will include the additional key-value pair.
Additionally, this syntax can be used for modifying the value assigned to a key. In this case, we’ll reference an existing key and pass a different value to it.
Let’s consider a dictionary `drew` that is one of the users on a given network. We’ll say that this user got a bump in followers today, so we need to update the integer value passed to the `'followers'` key. We’ll use the `print()` function to check that the dictionary was modified.
```
drew = {'username': 'squidly', 'online': True, 'followers': 305}
drew['followers'] = 342
print(drew)
```
In the output, we see that the number of followers jumped from the integer value of 305 to 342.
We can also add and modify dictionaries by using the `.update()` method. This varies from the `append()` method available in lists.
In the `jesse` dictionary below, let’s add the key `'followers'` and give it an integer value with `jesse.update()`. Following that, let’s `print()` the updated dictionary.
```
jesse = {'username': 'JOctopus', 'online': False, 'points': 723}
jesse.update({'followers': 481})
print(jesse)
```
From the output, we can see that we successfully added the `'followers': 481` key-value pair to the dictionary `jesse`.
We can also use the `.update()` method to modify an existing key-value pair by replacing a given value for a specific key.
Let’s change the online status of Sammy from `True` to `False` in the sammy dictionary:
```
sammy = {'username': 'sammy-shark', 'online': True, 'followers': 987}
sammy.update({'online': False})
print(sammy)
```
The line `sammy.update({'online': False})` references the existing key `'online'` and modifies its Boolean value from `True` to `False`. When we call to `print()` the dictionary, we see the update take place in the output.
To add items to dictionaries or modify values, we can use wither the `dict[key] = value` syntax or the method `.update()`.
### Deleting Dictionary Elements
Just as you can add key-value pairs and change values within the dictionary data type, you can also delete items within a dictionary.
To remove a key-value pair from a dictionary, we’ll use the following syntax:
`del dict[key]`
Let’s take the `jesse` dictionary that represents one of the users. We’ll say that Jesse is no longer using the online platform for playing games, so we’ll remove the item associated with the `'points'` key. Then, we’ll print the dictionary out to confirm that the item was deleted:
```
jesse = {'username': 'JOctopus', 'online': False, 'points': 723, 'followers': 481}
del jesse['points']
print(jesse)
```
The line `del jesse['points']` removes the key-value pair `'points': 723` from the jesse dictionary.
If we would like to clear a dictionary of all of its values, we can do so with the `.clear()` method. This will keep a given dictionary in case we need to use it later in the program, but it will no longer contain any items.
Let’s remove all the items within the `jesse` dictionary:
```
jesse = {'username': 'JOctopus', 'online': False, 'points': 723, 'followers': 481}
jesse.clear()
print(jesse)
```
The output shows that we now have an empty dictionary devoid of key-value pairs.
If we no longer need a specific dictionary, we can use `del` to get rid of it entirely:
```
del jesse
```
When we run a call to `print()` after deleting the jesse dictionary, we’ll receive the `NameError`:
```
print(jesse)
```
Because dictionaries are mutable data types, they can be added to, modified, and have items removed and cleared.
### Nested Dictionaries and Lists
A for-loop on a dictionary in the syntax of *list comprehensions* iterates over its keys by default. This returns the keys saved in a list object (in contrast to the `keys()` method). The keys will appear in an arbitrary order.
```
[ key for key in jesse ]
```
In addition to that, lists and dictionaries can be combined, i.e. nested in order to design various useful data structures. For example, instead of saving the user information of `sammy`, `jesse` and `drew` in three different dictionaries, ...
```
sammy = {'username': 'sammy-shark', 'online': True, 'points': 120, 'followers': 987}
jesse = {'username': 'JOctopus' , 'online': False, 'points': 723, 'followers': 481}
drew = {'username': 'squidly' , 'online': False, 'points': 652, 'followers': 532}
```
... we coul simply feed the data into a nested dictionary - a dictionary of dictionaries:
```
AppUsers_dictDict = {
'sammy': {'username': 'sammy-shark', 'online': True, 'points': 120, 'followers': 987},
'jesse': {'username': 'JOctopus' , 'online': False, 'points': 723, 'followers': 481},
'drew' : {'username': 'squidly' , 'online': False, 'points': 652, 'followers': 532}
}
```
... or we coul generate a dictionary nesting information in lists:
```
AppUsers_dictList = {
'names' : ['sammy', 'jesse', 'drew' ] ,
'usernames': ['sammy-shark', 'JOctopus', 'squidly' ] ,
'online' : [True, False, False] ,
'points' : [120, 723, 652 ] ,
'followers': [987, 481, 532 ]
}
```
... alternatively, dictionaries in a list:
```
AppUsers_listDict = [
{'name': 'sammy', 'username': 'sammy-shark', 'online': True, 'points': 120, 'followers': 987},
{'name': 'jesse', 'username': 'JOctopus' , 'online': False, 'points': 723, 'followers': 481},
{'name': 'drew' , 'username': 'squidly' , 'online': False, 'points': 652, 'followers': 532}
]
```
To access the individual elements of such nested objects, the syntax has to follow the hierarchy of the nested elements. For example, referencing a nested list-dictionary combination is has to be achieved through a combination of dictionary keys and list indexes.
Let's retrieve the username of jesse from the three nested objects. Elements in nested dictionaries can be referenced through keys of the various nesting levels:
`dictname[‘keyLevel1’][‘keyLevel2’][...]`
For the example `AppUsers_dictDict`, the respective literal is:
```
AppUsers_dictDict['jesse']['username']
```
If lists and dictionaries were combined, keys and indexes have to be combined respectively:
`dictname[‘key’][indexnumber]` or `dictname[indexnumber][‘key’]`
For the examples `AppUsers_dictList` and `AppUsers_listDict` above:
```
AppUsers_dictList['usernames'][1]
AppUsers_listDict[1]['username']
```
# Summary
Dictionaries are made up of key-value pairs and provide a way to store data without relying on indexing. This allows us to retrieve values based on their meaning and relation to other data types.
* Elements in dictionaries are directly accessible by keys.
* Keys have to be of immutable object type, like numbers or strings.
* Lists are mutable, they can't be used as keys, but they can be used as nested values.
* A list comprehension performed on a dictionary iterates over its keys by default. The keys will appear in an arbitrary order.
Most common specific operations (methods) are: `pop`, `keys`, `values`, `items`, `get`. A comprehensive overview of built-in dictionary operations, functions and methods is provided here: https://www.tutorialspoint.com/python/python_dictionary.htm
| github_jupyter |
```
import numpy as np
from astropy import units as u
import matplotlib.pyplot as plt
from astroquery.gaia import Gaia
from astropy.coordinates import SkyCoord
from gaiadr2ruwetools import ruwetools
from astropy.table import Table, Column
from tqdm import tqdm_notebook
from ffd_tools import *
plt.rcParams['font.size'] = 16
#flares = Table.read('all_flares_param_catalog_ruwe.tab', format='csv')
catalog= Table.read('all_star_param_catalog_ruwe.tab', format='csv')
from matplotlib.colors import LinearSegmentedColormap
clist0 = np.array(['EA8F3C', 'EB6A41', '69469D', '241817'])
clist1 = np.array(['66C6C6', '2B8D9D', '19536C', '123958', '121422'])
def hex_to_rgb(h):
if '#' in h:
h = h.lstrip('#')
hlen = int(len(h))
rgb = tuple(int(h[i:int(i+hlen/3)], 16) / 255.0 for i in range(0, hlen, int(hlen/3)))
return rgb
def make_cmap(clist):
rgb_tuples = []
for c in clist:
rgb_tuples.append(hex_to_rgb(c))
cm = LinearSegmentedColormap.from_list(
'sequential', rgb_tuples, N=2048)
return cm
cm = make_cmap(clist0)
cm1 = make_cmap(clist1)
uwe = np.sqrt( catalog['astrometric_chi2_al'] / (catalog['astrometric_n_good_obs_al']-5) )
u0fit = ruwetools.U0Interpolator()
u0 = u0fit.get_u0(catalog['phot_g_mean_mag'],
catalog['bp_rp'])
ruwe = uwe/u0
catalog.add_column(Column(ruwe, 'RUWE'))
catalog.write('all_star_param_catalog_ruwe.tab', format='csv')
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14,10),
sharex=True, sharey=True)
ruwe_cutoff = 2.0
fig.set_facecolor('w')
ax1.plot(catalog['teff'], catalog['lum'], '.',
c='#b3b3b3', ms=2, alpha=0.3, zorder=0)
im = ax1.scatter(catalog['teff'][catalog['RUWE']>=ruwe_cutoff],
catalog['lum'][catalog['RUWE']>=ruwe_cutoff],
c=catalog['RUWE'][catalog['RUWE']>=ruwe_cutoff], s=10,
vmin=ruwe_cutoff, vmax=5, zorder=3,
cmap=cm1.reversed())
fig.colorbar(im, ax=ax1, label='RUWE')
#ax1.colorbar(label='RUWE')
inds = np.where((catalog['teff'] > 6000) &
(catalog['lum']>3) &
(catalog['N_flares_per_day']>2) &
(catalog['RUWE'] < ruwe_cutoff))[0]
good_inds = np.delete(np.arange(0,len(catalog),1,dtype=int), inds)
ax2.plot(catalog['teff'][good_inds], catalog['lum'][good_inds], '.',
c='#b3b3b3', ms=2, alpha=0.3, zorder=0)
good_inds = catalog['RUWE'] > ruwe_cutoff
im = ax2.scatter(catalog['teff'][good_inds], catalog['lum'][good_inds],
c=catalog['N_flares_per_day'][good_inds], s=10, vmin=0, vmax=1,
cmap=cm.reversed(), zorder=3)
fig.colorbar(im, ax=ax2, label='Flare Rate [day$^{-1}$]')
#ax2.colorbar(label='Flare Rate')
plt.xlim(12000,2300)
plt.yscale('log')
plt.ylim(10**-3.5, 10**3)
ax1.set_xlabel('$T_{eff}$ [K]')
ax2.set_xlabel('$T_{eff}$ [K]')
ax1.set_ylabel('Luminosity [L/L$_\odot$]')
ax1.set_rasterized(True)
ax2.set_rasterized(True)
plt.savefig('ruwe_hr.pdf', dpi=250, rasterize=True, bbox_inches='tight')
catalog
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14,10),
sharex=True, sharey=True)
absmag = catalog['phot_g_mean_mag'] - 5*np.log10(catalog['TICv8_d']/10)
ruwe_cutoff = 1.4
fig.set_facecolor('w')
ax1.plot(catalog['bp_rp'], absmag, '.',
c='#b3b3b3', ms=2, alpha=0.3, zorder=0)
im = ax1.scatter(catalog['bp_rp'][catalog['RUWE']>=ruwe_cutoff],
absmag[catalog['RUWE']>=ruwe_cutoff],
c=catalog['RUWE'][catalog['RUWE']>=ruwe_cutoff], s=10,
vmin=ruwe_cutoff, vmax=5, zorder=3,
cmap=cm1.reversed())
fig.colorbar(im, ax=ax1, label='RUWE')
#ax1.colorbar(label='RUWE')
inds = np.where((catalog['teff'] > 6000) &
(catalog['lum']>3) &
(catalog['N_flares_per_day']>2) &
(catalog['RUWE'] < ruwe_cutoff))[0]
good_inds = np.delete(np.arange(0,len(catalog),1,dtype=int), inds)
ax2.plot(catalog['bp_rp'][good_inds],
absmag[good_inds], '.',
c='#b3b3b3', ms=2, alpha=0.3, zorder=0)
good_inds = catalog['RUWE'] > ruwe_cutoff
im = ax2.scatter(catalog['bp_rp'][good_inds],
absmag[good_inds],
c=catalog['N_flares_per_day'][good_inds], s=10,
vmin=0, vmax=0.5,
cmap=cm.reversed(), zorder=3)
fig.colorbar(im, ax=ax2, label='Flare Rate [day$^{-1}$]')
#ax2.colorbar(label='Flare Rate')
plt.xlim(-1,5)
#plt.yscale('log')
plt.ylim(17,-5)
ax1.set_xlabel('Gaia B$_p$ - R$_p$')
ax2.set_xlabel('Gaia B$_p$ - R$_p$')
ax1.set_ylabel('Gaia G Mag')
ax1.set_rasterized(True)
ax2.set_rasterized(True)
plt.savefig('ruwe_hr.pdf', dpi=250, rasterize=True, bbox_inches='tight')
def amp_slope_fit(data, bins, i=0, j=-1):
n, _ = np.histogram(data['amp']*100, bins=bins)
y, binedges, _ = plt.hist(data['amp']*100,
bins=bins,
weights=np.full(len(data['amp']),
1.0/np.nansum(data['weights'])),
alpha=0.4)
plt.yscale('log')
plt.show()
plt.close()
x = binedges[1:] + 0.0
logx = np.log10(x)
logn = np.log10(n)
q = logn > 0
plt.plot(logx[i:j], np.log10(n[i:j]), '.', c='k')
plt.plot(logx[i:j], linear([-2.5, 7], logx[i:j]), '--', c='w', linewidth=3)
plt.show()
results = minimize(linear_fit, x0=[-2.5, 7],
args=(logx[q][i:j-1]-np.diff(logx[q][i:j])/2.,
logn[q][i:j-1], np.sqrt(logn[q][i:j-1]) ),
bounds=( (-10.0, 10.0), (-100, 100)),
method='L-BFGS-B', tol=1e-8)
results.x[1] = 10**results.x[1]
results2 = leastsq(power_law_resid, results.x,
args=(x[q][i:j-1]-np.diff(x[q][i:j])/2.,
n[q][i:j-1],
np.sqrt(n[q][i:j-1]) ),
full_output=True)
fit_params = results2[0]
slope_err = np.sqrt(results2[1][0][0])
model = linear([fit_params[0], np.log10(fit_params[1])], logx)
#plt.plot(logx, model, c='r')
#plt.show()
#print(fit_params[0], slope_err)
return fit_params[0], slope_err, binedges, y
temp_bins = [2300,4500, 6000, 12000]
slopes_high = np.zeros(len(temp_bins)-1)
errs_high = np.zeros(len(temp_bins)-1)
slopes_low = np.zeros(len(temp_bins)-1)
errs_low = np.zeros(len(temp_bins)-1)
logx_high = []
logx_low = []
ruwe_cutoff = 2.0
bins = np.linspace(1,300,30)
for i in range(len(temp_bins)-1):
dat = flares[(flares['teff']>=temp_bins[i]) &
(flares['teff']<=temp_bins[i+1]) &
(flares['RUWE']>=ruwe_cutoff)]
slope, err, x, n = amp_slope_fit(dat, bins=bins)
slopes_high[i] = slope
errs_high[i] = err
logx_high.append([x, n])
dat = flares[(flares['teff']>=temp_bins[i]) &
(flares['teff']<=temp_bins[i+1]) &
(flares['RUWE']<ruwe_cutoff)]
slope, err, x, n = amp_slope_fit(dat, bins=bins, i=0, j=-1)
slopes_low[i] = slope
errs_low[i] = err
logx_low.append([x, n])
fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(14,4), sharex=True, sharey=True)
fig.set_facecolor('w')
axes = [ax1, ax2, ax3]
for i in range(len(axes)):
dat = flares[(flares['teff']>=temp_bins[i]) &
(flares['teff']<=temp_bins[i+1]) &
(flares['RUWE']<ruwe_cutoff)]
axes[i].hist(dat['amp']*100, bins=bins, weights=np.full(len(dat['amp']),
1.0/np.nansum(dat['weights'])),
color='deepskyblue', alpha=0.6)
dat = flares[(flares['teff']>=temp_bins[i]) &
(flares['teff']<=temp_bins[i+1]) &
(flares['RUWE']>=ruwe_cutoff)]
axes[i].hist(dat['amp']*100, bins=bins, weights=np.full(len(dat['amp']),
1.0/np.nansum(dat['weights'])),
color='k', alpha=0.7)
axes[i].set_title('{0}-{1} K'.format(temp_bins[i], temp_bins[i+1]))
plt.yscale('log')
ax2.set_xlabel('Flare Amplitude [%]')
ax1.set_ylabel('Flare Rate [day$^{-1}$]')
plt.savefig('ruwe_hists.pdf', dpi=250, rasterize=True, bbox_inches='tight')
fig = plt.figure(figsize=(8,4))
fig.set_facecolor('w')
for i in range(len(slopes_high)):
plt.errorbar((temp_bins[i]+temp_bins[i+1])/2.0,
slopes_high[i], yerr=errs_high[i], marker='o', color='k')
plt.errorbar((temp_bins[i]+temp_bins[i+1])/2.0,
slopes_low[i], yerr=errs_low[i], marker='o', color='deepskyblue')
plt.plot(1,1,'ko', label='RUWE >= {}'.format(ruwe_cutoff))
plt.plot(1,1,'o', c='deepskyblue', label='RUWE < 2.0')
plt.legend()
plt.ylim(-2.5,-5)
plt.ylabel('FFD Slope')
plt.xlim(3000,9500)
plt.xlabel('Median of T$_{eff}$ Bin [K]')
plt.savefig('ruwe.png', dpi=250, rasterize=True, bbox_inches='tight')
```
| github_jupyter |
```
# required for jupyter notebook
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(rc={'figure.figsize':(8,6)}) # set sns figure size
import os
import math
def show_corr_heatmap(df):
# https://medium.com/@szabo.bibor/how-to-create-a-seaborn-correlation-heatmap-in-python-834c0686b88e
plt.figure(figsize=(20, 10))
corr_matrix = df.corr()
# mask to hide the upper triangle of the symmetric corr-matrix
# mask = np.triu(np.ones_like(corr_matrix, dtype=np.bool))
heatmap = sns.heatmap(
# correlation matrix
corr_matrix,
# mask the top triangle of the matrix
# mask=mask,
# two-contrast color, different color for + -
cmap="PiYG",
# color map range
vmin=-1, vmax=1,
# show corr values in the cells
annot=True
)
# set a title
heatmap.set_title('Correlation Heatmap', fontdict={'fontsize':20}, pad=16);
plt.show()
# read raw csv by marking dropping missing values
missing_values = ['NIL', 'nil', '']
raw_df = pd.read_csv(os.path.join('..', '..', 'Datasets', 'brri-datasets', 'all-station_raw.csv'),
na_values=missing_values)
raw_df.head()
raw_df.info()
def show_max_min(_df):
df = _df.copy()
for column in df.columns:
print(f'{column}: max={raw_df[column].max()}, min={raw_df[column].min()}\n')
# show_max_min(raw_df)
```
**Drop invalid datas**
- Drop Max/Min Temp > 50
- Relative Humidity (afternoon, %) > 100,
- Sunshine/Cloudy (hour/day) > 24,
- Solar Radiation (cal/cm^2/day) > 20000 (from the box plot)
```
# _=raw_df.boxplot(column=['Solar Radiation (cal/cm^2/day)'], vert=False)
raw_df.drop(raw_df.index[raw_df['Max Temp. (degree Celcius)'] > 50], inplace=True)
raw_df.drop(raw_df.index[raw_df['Min Temp. (degree Celcius)'] > 50], inplace=True)
raw_df.drop(raw_df.index[raw_df['Relative Humidity (afternoon, %)'] > 100], inplace=True)
raw_df.drop(raw_df.index[raw_df['Sunshine (hour/day)'] > 24], inplace=True)
raw_df.drop(raw_df.index[raw_df['Cloudy (hour/day)'] > 24], inplace=True)
raw_df.drop(raw_df.index[raw_df['Solar Radiation (cal/cm^2/day)'] > 20000], inplace=True)
# show_max_min(raw_df)
# _=raw_df.boxplot(column=['Solar Radiation (cal/cm^2/day)'], vert=False)
# len(raw_df[raw_df['Solar Radiation (cal/cm^2/day)']>1000])
```
**Drop 'Solar Radiation (cal/cm^2/day)' > 1000**
```
raw_df.drop(raw_df.index[raw_df['Solar Radiation (cal/cm^2/day)'] > 1000], inplace=True)
# show_max_min(raw_df)
# _=raw_df.boxplot(column=['Solar Radiation (cal/cm^2/day)'], vert=False)
```
## Get station-wise dataframes
```
# read Gazipur raw csv by marking dropping missing values
gazipur_raw_df = raw_df[raw_df['Station']=='Gazipur']
gazipur_raw_df.head()
# read Rangpur raw csv by marking dropping missing values
rangpur_raw_df = raw_df[raw_df['Station']=='Rangpur']
rangpur_raw_df.head()
# read Barisal raw csv by marking dropping missing values
barisal_raw_df = raw_df[raw_df['Station']=='Barisal']
barisal_raw_df.head()
# read Habiganj raw csv by marking dropping missing values
habiganj_raw_df = raw_df[raw_df['Station']=='Habiganj']
habiganj_raw_df.head()
def get_val_freq_map(df, column):
'''
get map of value counts of a dataframe for a particular column
'''
mp = {}
for val in raw_df[column]:
if val in mp:
mp[val]+=1
else:
mp[val]=1
return mp
```
# Analyze all station Rainfall data
```
rainfall_column = 'Rainfall (mm)'
rainfall_df = raw_df[[rainfall_column]].copy()
rainfall_df.head()
rainfall_df.value_counts()
print(rainfall_df.max())
rainfall_df[rainfall_column].hist(bins=10)
def group_column_vals(df, column, diff=10):
group_labels = []
group_freqs = []
length = math.ceil(df[column].max()/diff)
for i in range(length+1):
group_freqs.append(0)
if i==0:
group_labels.append('0')
else:
group_labels.append(str(1+(i-1)*diff) + '-' + str(i*diff))
for val in df[column]:
if math.isnan(val):
continue
group_freqs[math.ceil(val/diff)]+=1
mp = {}
total_freq = sum(group_freqs)
for i in range(length+1):
# store percantage of each group
mp[group_labels[i]] = round((group_freqs[i]/total_freq) * 100, 2)
return mp
group_column_vals(df=rainfall_df, column=rainfall_column, diff=20)
```
## Analyze Staion-wise Rainfall
### Gazipur
```
gazipur_rainfall_df = gazipur_raw_df[[rainfall_column]].copy()
# gazipur_rainfall_df.head()
gazipur_rainfall_df[rainfall_column].hist(bins=10)
group_column_vals(gazipur_rainfall_df, rainfall_column, 20)
```
### Rangpur
```
rangpur_rainfall_df = rangpur_raw_df[[rainfall_column]].copy()
# rangpur_rainfall_df.head()
rangpur_rainfall_df[rainfall_column].hist(bins=10)
group_column_vals(rangpur_rainfall_df, rainfall_column, 20)
```
### Barisal
```
barisal_rainfall_df = barisal_raw_df[[rainfall_column]].copy()
# barisal_rainfall_df.head()
barisal_rainfall_df[rainfall_column].hist(bins=10)
group_column_vals(barisal_rainfall_df, rainfall_column, 20)
```
### Habiganj
```
habiganj_rainfall_df = habiganj_raw_df[[rainfall_column]].copy()
# habiganj_rainfall_df.head()
habiganj_rainfall_df[rainfall_column].hist(bins=10)
group_column_vals(habiganj_rainfall_df, rainfall_column, 20)
```
## Analyze Rainfall Per Year
```
raw_df_2016 = raw_df[raw_df['Year']==2016]
raw_df_2017 = raw_df[raw_df['Year']==2017]
raw_df_2018 = raw_df[raw_df['Year']==2018]
raw_df_2019 = raw_df[raw_df['Year']==2019]
raw_df_2020 = raw_df[raw_df['Year']==2020]
# raw_df_2020.head()
```
### Year 2016
```
# raw_df_2016[rainfall_column].hist(bins=10)
group_column_vals(raw_df_2016, rainfall_column, 20)
```
### Year 2017
```
# raw_df_2017[rainfall_column].hist(bins=10)
group_column_vals(raw_df_2017, rainfall_column, 20)
```
### Year 2018
```
# raw_df_2018[rainfall_column].hist(bins=10)
group_column_vals(raw_df_2018, rainfall_column, 20)
```
### Year 2019
```
# raw_df_2019[rainfall_column].hist(bins=10)
group_column_vals(raw_df_2019, rainfall_column, 20)
```
### Year 2020
```
# raw_df_2020[rainfall_column].hist(bins=10)
group_column_vals(raw_df_2020, rainfall_column, 20)
```
## Monthly Rainfall Analysis
```
raw_df_month = raw_df[raw_df['Month'].isin([5,6,7,8])]
raw_df_month.head()
# raw_df_month[rainfall_column].hist(bins=10)
group_column_vals(raw_df_month, rainfall_column, 15)
```
# Correlation Heatmap
### Whole dataset
```
show_corr_heatmap(raw_df)
```
### Monthly dataset
```
show_corr_heatmap(raw_df_month)
```
# Scatter plots
```
_=sns.scatterplot(data=raw_df, x='Month', y=rainfall_column, hue='Station')
_=sns.scatterplot(data=raw_df, x='Year', y=rainfall_column, hue='Station')
# sns.pairplot(raw_df[['Rainfall (mm)', 'Month', 'Station']], hue = 'Station', height = 5)
```
| github_jupyter |
<a href="https://www.bigdatauniversity.com"><img src="https://ibm.box.com/shared/static/cw2c7r3o20w9zn8gkecaeyjhgw3xdgbj.png" width="400" align="center"></a>
<h1><center>K-Means Clustering</center></h1>
## Introduction
There are many models for **clustering** out there. In this notebook, we will be presenting the model that is considered one of the simplest models amongst them. Despite its simplicity, the **K-means** is vastly used for clustering in many data science applications, especially useful if you need to quickly discover insights from **unlabeled data**. In this notebook, you will learn how to use k-Means for customer segmentation.
Some real-world applications of k-means:
- Customer segmentation
- Understand what the visitors of a website are trying to accomplish
- Pattern recognition
- Machine learning
- Data compression
In this notebook we practice k-means clustering with 2 examples:
- k-means on a random generated dataset
- Using k-means for customer segmentation
<h1>Table of contents</h1>
<div class="alert alert-block alert-info" style="margin-top: 20px">
<ul>
<li><a href="#random_generated_dataset">k-Means on a randomly generated dataset</a></li>
<ol>
<li><a href="#setting_up_K_means">Setting up K-Means</a></li>
<li><a href="#creating_visual_plot">Creating the Visual Plot</a></li>
</ol>
<li><a href="#customer_segmentation_K_means">Customer Segmentation with K-Means</a></li>
<ol>
<li><a href="#pre_processing">Pre-processing</a></li>
<li><a href="#modeling">Modeling</a></li>
<li><a href="#insights">Insights</a></li>
</ol>
</ul>
</div>
<br>
<hr>
### Import libraries
Lets first import the required libraries.
Also run <b> %matplotlib inline </b> since we will be plotting in this section.
```
import random
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets.samples_generator import make_blobs
%matplotlib inline
```
<h1 id="random_generated_dataset">k-Means on a randomly generated dataset</h1>
Lets create our own dataset for this lab!
First we need to set up a random seed. Use <b>numpy's random.seed()</b> function, where the seed will be set to <b>0</b>
```
np.random.seed(0)
```
Next we will be making <i> random clusters </i> of points by using the <b> make_blobs </b> class. The <b> make_blobs </b> class can take in many inputs, but we will be using these specific ones. <br> <br>
<b> <u> Input </u> </b>
<ul>
<li> <b>n_samples</b>: The total number of points equally divided among clusters. </li>
<ul> <li> Value will be: 5000 </li> </ul>
<li> <b>centers</b>: The number of centers to generate, or the fixed center locations. </li>
<ul> <li> Value will be: [[4, 4], [-2, -1], [2, -3],[1,1]] </li> </ul>
<li> <b>cluster_std</b>: The standard deviation of the clusters. </li>
<ul> <li> Value will be: 0.9 </li> </ul>
</ul>
<br>
<b> <u> Output </u> </b>
<ul>
<li> <b>X</b>: Array of shape [n_samples, n_features]. (Feature Matrix)</li>
<ul> <li> The generated samples. </li> </ul>
<li> <b>y</b>: Array of shape [n_samples]. (Response Vector)</li>
<ul> <li> The integer labels for cluster membership of each sample. </li> </ul>
</ul>
```
X, y = make_blobs(n_samples=5000, centers=[[4,4], [-2, -1], [2, -3], [1, 1]], cluster_std=0.9)
```
Display the scatter plot of the randomly generated data.
```
plt.scatter(X[:, 0], X[:, 1], marker='.')
```
<h2 id="setting_up_K_means">Setting up K-Means</h2>
Now that we have our random data, let's set up our K-Means Clustering.
The KMeans class has many parameters that can be used, but we will be using these three:
<ul>
<li> <b>init</b>: Initialization method of the centroids. </li>
<ul>
<li> Value will be: "k-means++" </li>
<li> k-means++: Selects initial cluster centers for k-mean clustering in a smart way to speed up convergence.</li>
</ul>
<li> <b>n_clusters</b>: The number of clusters to form as well as the number of centroids to generate. </li>
<ul> <li> Value will be: 4 (since we have 4 centers)</li> </ul>
<li> <b>n_init</b>: Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. </li>
<ul> <li> Value will be: 12 </li> </ul>
</ul>
Initialize KMeans with these parameters, where the output parameter is called <b>k_means</b>.
```
k_means = KMeans(init = "k-means++", n_clusters = 4, n_init = 12)
```
Now let's fit the KMeans model with the feature matrix we created above, <b> X </b>
```
k_means.fit(X)
```
Now let's grab the labels for each point in the model using KMeans' <b> .labels\_ </b> attribute and save it as <b> k_means_labels </b>
```
k_means_labels = k_means.labels_
k_means_labels
```
We will also get the coordinates of the cluster centers using KMeans' <b> .cluster_centers_ </b> and save it as <b> k_means_cluster_centers </b>
```
k_means_cluster_centers = k_means.cluster_centers_
k_means_cluster_centers
```
<h2 id="creating_visual_plot">Creating the Visual Plot</h2>
So now that we have the random data generated and the KMeans model initialized, let's plot them and see what it looks like!
Please read through the code and comments to understand how to plot the model.
```
# Initialize the plot with the specified dimensions.
fig = plt.figure(figsize=(6, 4))
# Colors uses a color map, which will produce an array of colors based on
# the number of labels there are. We use set(k_means_labels) to get the
# unique labels.
colors = plt.cm.Spectral(np.linspace(0, 1, len(set(k_means_labels))))
# Create a plot
ax = fig.add_subplot(1, 1, 1)
# For loop that plots the data points and centroids.
# k will range from 0-3, which will match the possible clusters that each
# data point is in.
for k, col in zip(range(len([[4,4], [-2, -1], [2, -3], [1, 1]])), colors):
# Create a list of all data points, where the data poitns that are
# in the cluster (ex. cluster 0) are labeled as true, else they are
# labeled as false.
my_members = (k_means_labels == k)
# Define the centroid, or cluster center.
cluster_center = k_means_cluster_centers[k]
# Plots the datapoints with color col.
ax.plot(X[my_members, 0], X[my_members, 1], 'w', markerfacecolor=col, marker='.')
# Plots the centroids with specified color, but with a darker outline
ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6)
# Title of the plot
ax.set_title('KMeans')
# Remove x-axis ticks
ax.set_xticks(())
# Remove y-axis ticks
ax.set_yticks(())
# Show the plot
plt.show()
```
## Practice
Try to cluster the above dataset into 3 clusters.
Notice: do not generate data again, use the same dataset as above.
```
k_means3 = KMeans(init = "k-means++", n_clusters = 3, n_init = 12)
k_means3.fit(X)
fig = plt.figure(figsize=(6, 4))
colors = plt.cm.Spectral(np.linspace(0, 1, len(set(k_means3.labels_))))
ax = fig.add_subplot(1, 1, 1)
for k, col in zip(range(len(k_means3.cluster_centers_)), colors):
my_members = (k_means3.labels_ == k)
cluster_center = k_means3.cluster_centers_[k]
ax.plot(X[my_members, 0], X[my_members, 1], 'w', markerfacecolor=col, marker='.')
ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6)
plt.show()
```
Double-click __here__ for the solution.
<!-- Your answer is below:
k_means3 = KMeans(init = "k-means++", n_clusters = 3, n_init = 12)
k_means3.fit(X)
fig = plt.figure(figsize=(6, 4))
colors = plt.cm.Spectral(np.linspace(0, 1, len(set(k_means3.labels_))))
ax = fig.add_subplot(1, 1, 1)
for k, col in zip(range(len(k_means3.cluster_centers_)), colors):
my_members = (k_means3.labels_ == k)
cluster_center = k_means3.cluster_centers_[k]
ax.plot(X[my_members, 0], X[my_members, 1], 'w', markerfacecolor=col, marker='.')
ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6)
plt.show()
-->
<h1 id="customer_segmentation_K_means">Customer Segmentation with K-Means</h1>
Imagine that you have a customer dataset, and you need to apply customer segmentation on this historical data.
Customer segmentation is the practice of partitioning a customer base into groups of individuals that have similar characteristics. It is a significant strategy as a business can target these specific groups of customers and effectively allocate marketing resources. For example, one group might contain customers who are high-profit and low-risk, that is, more likely to purchase products, or subscribe for a service. A business task is to retaining those customers. Another group might include customers from non-profit organizations. And so on.
Lets download the dataset. To download the data, we will use **`!wget`** to download it from IBM Object Storage.
__Did you know?__ When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC)
```
!wget -O Cust_Segmentation.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/Cust_Segmentation.csv
```
### Load Data From CSV File
Before you can work with the data, you must use the URL to get the Cust_Segmentation.csv.
```
import pandas as pd
cust_df = pd.read_csv("Cust_Segmentation.csv")
cust_df.head()
```
<h2 id="pre_processing">Pre-processing</h2
As you can see, __Address__ in this dataset is a categorical variable. k-means algorithm isn't directly applicable to categorical variables because Euclidean distance function isn't really meaningful for discrete variables. So, lets drop this feature and run clustering.
```
df = cust_df.drop('Address', axis=1)
df.head()
```
#### Normalizing over the standard deviation
Now let's normalize the dataset. But why do we need normalization in the first place? Normalization is a statistical method that helps mathematical-based algorithms to interpret features with different magnitudes and distributions equally. We use __StandardScaler()__ to normalize our dataset.
```
from sklearn.preprocessing import StandardScaler
X = df.values[:,1:]
X = np.nan_to_num(X)
Clus_dataSet = StandardScaler().fit_transform(X)
Clus_dataSet
```
<h2 id="modeling">Modeling</h2>
In our example (if we didn't have access to the k-means algorithm), it would be the same as guessing that each customer group would have certain age, income, education, etc, with multiple tests and experiments. However, using the K-means clustering we can do all this process much easier.
Lets apply k-means on our dataset, and take look at cluster labels.
```
clusterNum = 3
k_means = KMeans(init = "k-means++", n_clusters = clusterNum, n_init = 12)
k_means.fit(X)
labels = k_means.labels_
print(labels)
```
<h2 id="insights">Insights</h2>
We assign the labels to each row in dataframe.
```
df["Clus_km"] = labels
df.head(5)
```
We can easily check the centroid values by averaging the features in each cluster.
```
df.groupby('Clus_km').mean()
```
Now, lets look at the distribution of customers based on their age and income:
```
area = np.pi * ( X[:, 1])**2
plt.scatter(X[:, 0], X[:, 3], s=area, c=labels.astype(np.float), alpha=0.5)
plt.xlabel('Age', fontsize=18)
plt.ylabel('Income', fontsize=16)
plt.show()
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(1, figsize=(8, 6))
plt.clf()
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
plt.cla()
# plt.ylabel('Age', fontsize=18)
# plt.xlabel('Income', fontsize=16)
# plt.zlabel('Education', fontsize=16)
ax.set_xlabel('Education')
ax.set_ylabel('Age')
ax.set_zlabel('Income')
ax.scatter(X[:, 1], X[:, 0], X[:, 3], c= labels.astype(np.float))
```
k-means will partition your customers into mutually exclusive groups, for example, into 3 clusters. The customers in each cluster are similar to each other demographically.
Now we can create a profile for each group, considering the common characteristics of each cluster.
For example, the 3 clusters can be:
- AFFLUENT, EDUCATED AND OLD AGED
- MIDDLE AGED AND MIDDLE INCOME
- YOUNG AND LOW INCOME
<h2>Want to learn more?</h2>
IBM SPSS Modeler is a comprehensive analytics platform that has many machine learning algorithms. It has been designed to bring predictive intelligence to decisions made by individuals, by groups, by systems – by your enterprise as a whole. A free trial is available through this course, available here: <a href="http://cocl.us/ML0101EN-SPSSModeler">SPSS Modeler</a>
Also, you can use Watson Studio to run these notebooks faster with bigger datasets. Watson Studio is IBM's leading cloud solution for data scientists, built by data scientists. With Jupyter notebooks, RStudio, Apache Spark and popular libraries pre-packaged in the cloud, Watson Studio enables data scientists to collaborate on their projects without having to install anything. Join the fast-growing community of Watson Studio users today with a free account at <a href="https://cocl.us/ML0101EN_DSX">Watson Studio</a>
<h3>Thanks for completing this lesson!</h3>
<h4>Author: <a href="https://ca.linkedin.com/in/saeedaghabozorgi">Saeed Aghabozorgi</a></h4>
<p><a href="https://ca.linkedin.com/in/saeedaghabozorgi">Saeed Aghabozorgi</a>, PhD is a Data Scientist in IBM with a track record of developing enterprise level applications that substantially increases clients’ ability to turn data into actionable knowledge. He is a researcher in data mining field and expert in developing advanced analytic methods like machine learning and statistical modelling on large datasets.</p>
<hr>
<p>Copyright © 2018 <a href="https://cocl.us/DX0108EN_CC">Cognitive Class</a>. This notebook and its source code are released under the terms of the <a href="https://bigdatauniversity.com/mit-license/">MIT License</a>.</p>
| github_jupyter |
```
from warnings import filterwarnings
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import pymc as pm
from sklearn.linear_model import LinearRegression
%load_ext lab_black
%load_ext watermark
filterwarnings("ignore")
```
# A Simple Regression
From [Codes for Unit 1](https://www2.isye.gatech.edu/isye6420/supporting.html).
Associated lecture video: Unit 1 Lesson 4
You don't usually need to set inits in PyMC. The default method of generating inits is 'jitter+adapt_diag', which chooses them based on the model and input data while adding some randomness.
If you do want to set an initial value, pass a dictionary to the start parameter of pm.sample.
```python
inits = {
"alpha": np.array(0.0),
"beta": np.array(0.0)
}
trace = pm.sample(2000, start=inits)
```
```
X = np.array([1, 2, 3, 4, 5])
y = np.array([1, 3, 3, 3, 5])
x_bar = np.mean(X)
with pm.Model() as m:
# priors
alpha = pm.Normal("alpha", sigma=100)
beta = pm.Normal("beta", sigma=100)
# using precision for direct comparison with BUGS output
tau = pm.Gamma("tau", alpha=0.001, beta=0.001)
sigma = 1 / pm.math.sqrt(tau)
mu = alpha + beta * (X - x_bar)
likelihood = pm.Normal("likelihood", mu=mu, sigma=sigma, observed=y)
# start sampling
trace = pm.sample(
3000, # samples
chains=4,
tune=500,
init="jitter+adapt_diag",
random_seed=1,
cores=4, # parallel processing of chains
return_inferencedata=True, # return arviz inferencedata object
)
```
PyMC3 uses the tuning step specified in the pm.sample call to adjust various parameters in the No-U-Turn Sampler [(NUTS) algorithm](https://arxiv.org/abs/1111.4246), which is a form of Hamiltonian Monte Carlo. BUGS also silently uses different types of tuning depending on the algorithm it [chooses](https://www.york.ac.uk/depts/maths/histstat/pml1/bayes/winbugsinfo/cowles_winbugs.pdf). The professor often burns some number of samples in his examples. Note that this is separate from the tuning phase for both programs!
For some more detail on tuning, see [this post](https://colcarroll.github.io/hmc_tuning_talk/).
```
# this burns the first 500 samples
trace_burned = trace.sel(draw=slice(500, None))
```
Arviz has a variety of functions to view the results of the model. One of the most useful is az.summary. Professor Vidakovic arbitrarily asks for the 95% credible set (also called the highest density interval), so we can specify hdi_prob=.95 to get that. This is the HPD, or minimum-width, credible set.
```
az.summary(trace_burned, hdi_prob=0.95)
```
You can also get the HDIs directly:
```
az.hdi(trace_burned, hdi_prob=0.95)["beta"].values
```
There are a variety of plots available. Commonly used to diagnose problems are the trace (see [When Traceplots go Bad](https://jpreszler.rbind.io/post/2019-09-28-bad-traceplots/)) and rank plots (see the Maybe it's time to let traceplots die section from [this post](https://statmodeling.stat.columbia.edu/2019/03/19/maybe-its-time-to-let-the-old-ways-die-or-we-broke-r-hat-so-now-we-have-to-fix-it/)).
```
az.plot_trace(trace_burned)
plt.show()
az.plot_rank(trace_burned)
plt.show()
```
There are many ways to manipulate Arviz [InferenceData](https://arviz-devs.github.io/arviz/api/generated/arviz.InferenceData.html) objects to calculate statistics after sampling is complete.
```
# alpha - beta * x.bar
intercept = (
trace_burned.posterior.alpha.mean() - trace_burned.posterior.beta.mean() * x_bar
)
intercept.values
```
OpenBugs results:
| | mean | sd | MC_error | val2.5pc | median | val97.5pc | start | sample |
|-------|--------|--------|----------|----------|--------|-----------|-------|--------|
| alpha | 2.995 | 0.5388 | 0.005863 | 1.947 | 3.008 | 4.015 | 1000 | 9001 |
| beta | 0.7963 | 0.3669 | 0.003795 | 0.08055 | 0.7936 | 1.526 | 1000 | 9001 |
| tau | 1.88 | 1.524 | 0.02414 | 0.1416 | 1.484 | 5.79 | 1000 | 9001 |
Sometimes you might want to do a sanity check with classical regression. If your Bayesian regression has noninformative priors, the results should be close.
```
reg = LinearRegression().fit(X.reshape(-1, 1), y)
# compare with intercept and beta from above
reg.intercept_, reg.coef_
%watermark --iversions -v
```
| github_jupyter |
# Example Notebook for the tunneling Fermions
This Notebook is based on the following [paper](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.114.080402) from the Jochim group. In these experiments two fermions of different spins are put into a single tweezer and then coupled to a second tweezer. The dynamics is then controlled by two competing effects. The interactions and the tunneling.
Let us first start by looking at the data, then look how the can be described in the Hamiltonian language and finally in the gate language.
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data_murmann_no_int = pd.read_csv('Data/Murmann_No_Int.csv', names = ['time', "nR"])
data_murmann_with_int = pd.read_csv('Data/Murmann_With_Int.csv', names = ['time', "nR"])
#plt.figure(dpi=96)
f, (ax1, ax2) = plt.subplots(2,1, sharex = True, sharey = True);
ax1.plot(data_murmann_no_int.time, data_murmann_no_int.nR, 'ro', label="U = 0", markersize=4)
ax2.plot(data_murmann_with_int.time, data_murmann_with_int.nR, 'bo', label="U = J", markersize=4)
ax1.set_ylabel(r'atoms in right valley')
ax2.set_ylabel(r'atoms in right valley')
ax2.set_xlabel(r'time (ms)')
ax1.legend()
ax2.legend()
```
## Analytical prediction
For the two atoms the Hamiltonian can be written down in the basis $\{LL, LR, RL, RR\}$ as:
$$
H = \left(\begin{array}{cccc}
U & -J & -J & 0\\
-J & 0 & 0 &-J\\
-J & 0 & 0 &-J\\
0 & -J & -J & U
\end{array}
\right)
$$
And we start out in the basis state $|LL\rangle$. So we can write
```
from scipy.sparse.linalg import expm
J = np.pi*134; # in units of hbar
U = 0.7*J;
Nt_an = 50;
t_analytical = np.linspace(0, 20, Nt_an)*1e-3;
H_With_Int = np.array([[U, -J,-J,0],[-J,0,0,-J],[-J,0,0,-J],[0, -J,-J,U]])
H_Wo_Int = np.array([[0, -J,-J,0],[-J,0,0,-J],[-J,0,0,-J],[0, -J,-J,0]])
psi0 = np.zeros(4)*1j
psi0[0] = 1.+0j
print(psi0)
psis_wo_int = 1j*np.zeros((4,Nt_an))
psis_w_int = 1j*np.zeros((4,Nt_an))
for ii in np.arange(Nt_an):
U_wo = expm(-1j*t_analytical[ii]*H_Wo_Int);
psis_wo_int[:,ii] = np.dot(U_wo,psi0);
U_w = expm(-1j*t_analytical[ii]*H_With_Int);
psis_w_int[:,ii] = np.dot(U_w,psi0);
ps_wo = np.abs(psis_wo_int)**2
ps_w = np.abs(psis_w_int)**2
nR_wo = ps_wo[1,:]+ps_wo[2,:]+2*ps_wo[3,:];
nR_w = ps_w[1,:]+ps_w[2,:]+2*ps_w[3,:];
f, (ax1, ax2) = plt.subplots(2,1, sharex = True, sharey = True);
ax1.plot(t_analytical*1e3, nR_wo, 'r-', label="U = 0", linewidth=4, alpha = 0.5)
ax1.plot(data_murmann_no_int.time, data_murmann_no_int.nR, 'ro', label="U = 0", markersize=4)
ax2.plot(t_analytical*1e3, nR_w, 'b-', label="U = 0", linewidth=4, alpha = 0.5)
ax2.plot(data_murmann_with_int.time, data_murmann_with_int.nR, 'bo', label="U = J", markersize=4)
ax1.set_ylabel(r'atoms in right valley')
ax2.set_ylabel(r'atoms in right valley')
ax2.set_xlabel(r'time (ms)')
ax2.set_xlim(0,20)
ax1.legend()
ax2.legend()
from qiskit_cold_atom.providers import ColdAtomProvider
provider = ColdAtomProvider()
backend = provider.get_backend("fermionic_tweezer_simulator")
# give initial occupations separated by spin species
qc = backend.initialize_circuit([[1, 0,0,0], [1, 0,0,0]])
qc.draw(output='mpl')
from qiskit_cold_atom.providers import ColdAtomProvider
provider = ColdAtomProvider()
backend = provider.get_backend("fermionic_tweezer_simulator")
# give initial occupations separated by spin species
qc = backend.initialize_circuit([[1, 0,0,0], [1, 0,0,0]])
qc.draw(output='mpl')
```
initialize the full dynamics
```
time =3*1e-3;
from qiskit_cold_atom.fermions.fermion_gate_library import FermiHubbard
qc = backend.initialize_circuit([[1, 0,0,0], [1, 0,0,0]])
all_modes=range(8)
qc.append(FermiHubbard(num_modes=8, j=[J*time,0,0], u=U*time, mu=[0*time,0,0,0]), qargs=all_modes)
qc.measure_all()
# alternatively append the FH gate directly:
# qc.FH(j=[0.5, 1., -1.], u=5., mu=[0., -1., 1., 0.], modes=all_modes)
qc.draw(output='mpl')
job = backend.run(qc, shots=100)
print("counts: ", job.result().get_counts())
def get_left_right_occupation(counts):
sum_counts = 0;
nL = 0;
nR = 0;
for k, v in counts.items():
# look for lefties
sum_counts += v;
if int(k[0]):
nL += v
if int(k[4]):
nL += v
if int(k[1]):
nR += v
if int(k[5]):
nR += v
return nL/sum_counts, nR/sum_counts
get_left_right_occupation(job.result().get_counts())
```
## No interaction
In a first set of experiments there are no interactions and the two atoms are simply allowed to hop. The experiment is then described by the following very simple circuit.
now let us simulate the time evolution
```
Ntimes = 25;
times = np.linspace(0, 20, Ntimes)*1e-3;
means = np.zeros(Ntimes);
for i in range(Ntimes):
time = times[i]
qc = backend.initialize_circuit([[1, 0,0,0], [1, 0,0,0]])
all_modes=range(8)
qc.append(FermiHubbard(num_modes=8, j=[J*time,0,0], u=0*time, mu=[0*time,0,0,0]), qargs=all_modes)
qc.measure_all()
job = backend.run(qc, shots=100)
counts = job.result().get_counts()
_, means[i] = get_left_right_occupation(counts)
if i%10==0:
print("step", i)
# Calculate the resulting states after each rotation
```
and compare to the data
```
f, ax1 = plt.subplots(1,1, sharex = True, sharey = True);
ax1.plot(times*1e3, means, 'r-', label="U = 0", linewidth=4, alpha = 0.5)
ax1.plot(data_murmann_no_int.time, data_murmann_no_int.nR, 'ro', label="U = 0", markersize=4)
ax1.set_xlim(0,20)
```
## Hopping with interactions
In a next step the atoms are interacting. The circuit description of the experiment is the application of the hopping gate and the interaction gate. It can be written as
```
Ntimes = 25;
times = np.linspace(0, 20, Ntimes)*1e-3;
means_int = np.zeros(Ntimes);
for i in range(Ntimes):
time = times[i]
qc = backend.initialize_circuit([[1, 0,0,0], [1, 0,0,0]])
all_modes=range(8)
qc.append(FermiHubbard(num_modes=8, j=[J*time,0,0], u=U*time, mu=[0*time,0,0,0]), qargs=all_modes)
qc.measure_all()
job = backend.run(qc, shots=100)
counts = job.result().get_counts()
_, means_int[i] = get_left_right_occupation(counts)
if i%10==0:
print("step", i)
# Calculate the resulting states after each rotation
```
And we compare to the data to obtain
```
f, ax2 = plt.subplots(1,1, sharex = True, sharey = True);
ax2.plot(times*1e3, means_int, 'b-', label="simulation", linewidth=4, alpha = 0.5)
ax2.plot(data_murmann_with_int.time, data_murmann_with_int.nR, 'bo', label="U = J", markersize=4)
ax2.set_ylabel(r'atoms in right valley')
ax2.set_xlabel(r'time (ms)')
ax2.legend()
ax2.set_xlim(0,20)
```
## Summary
And finally we can compare the experimental data with all the descriptions.
```
f, (ax1, ax2) = plt.subplots(2,1, sharex = True, sharey = True);
ax1.plot(times*1e3, means, 'r-', label="qiskit", linewidth=4, alpha = 0.5)
ax1.plot(t_analytical*1e3, nR_wo, 'r-.', label="analytical", linewidth=4, alpha = 0.5)
ax1.plot(data_murmann_no_int.time, data_murmann_no_int.nR, 'ro', label="experiment", markersize=4)
ax2.plot(times*1e3, means_int, 'b-', label="qiskit", linewidth=4, alpha = 0.5)
ax2.plot(t_analytical*1e3, nR_w, 'b-.', label="analytical", linewidth=4, alpha = 0.5)
ax2.plot(data_murmann_with_int.time, data_murmann_with_int.nR, 'bo', label="experiment", markersize=4)
ax1.set_ylabel(r'atoms in right valley')
ax2.set_ylabel(r'atoms in right valley')
ax2.set_xlabel(r'time (ms)')
ax1.legend(loc='upper right')
ax2.legend(loc='upper right')
ax1.set_xlim(-1,20)
```
| github_jupyter |
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png">
*This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).*
*The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please consider supporting the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!*
<!--NAVIGATION-->
< [Computation on Arrays: Broadcasting](02.05-Computation-on-arrays-broadcasting.ipynb) | [Contents](Index.ipynb) | [Fancy Indexing](02.07-Fancy-Indexing.ipynb) >
<a href="https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/02.06-Boolean-Arrays-and-Masks.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open and Execute in Google Colaboratory"></a>
# Comparisons, Masks, and Boolean Logic
This section covers the use of Boolean masks to examine and manipulate values within NumPy arrays.
Masking comes up when you want to extract, modify, count, or otherwise manipulate values in an array based on some criterion: for example, you might wish to count all values greater than a certain value, or perhaps remove all outliers that are above some threshold.
In NumPy, Boolean masking is often the most efficient way to accomplish these types of tasks.
## Example: Counting Rainy Days
Imagine you have a series of data that represents the amount of precipitation each day for a year in a given city.
For example, here we'll load the daily rainfall statistics for the city of Seattle in 2014, using Pandas (which is covered in more detail in [Chapter 3](03.00-Introduction-to-Pandas.ipynb)):
```
import numpy as np
import pandas as pd
# use pandas to extract rainfall inches as a NumPy array
rainfall = pd.read_csv('data/Seattle2014.csv')['PRCP'].values
inches = rainfall / 254.0 # 1/10mm -> inches
inches.shape
```
The array contains 365 values, giving daily rainfall in inches from January 1 to December 31, 2014.
As a first quick visualization, let's look at the histogram of rainy days, which was generated using Matplotlib (we will explore this tool more fully in [Chapter 4](04.00-Introduction-To-Matplotlib.ipynb)):
```
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn; seaborn.set() # set plot styles
plt.hist(inches, 40);
```
This histogram gives us a general idea of what the data looks like: despite its reputation, the vast majority of days in Seattle saw near zero measured rainfall in 2014.
But this doesn't do a good job of conveying some information we'd like to see: for example, how many rainy days were there in the year? What is the average precipitation on those rainy days? How many days were there with more than half an inch of rain?
### Digging into the data
One approach to this would be to answer these questions by hand: loop through the data, incrementing a counter each time we see values in some desired range.
For reasons discussed throughout this chapter, such an approach is very inefficient, both from the standpoint of time writing code and time computing the result.
We saw in [Computation on NumPy Arrays: Universal Functions](02.03-Computation-on-arrays-ufuncs.ipynb) that NumPy's ufuncs can be used in place of loops to do fast element-wise arithmetic operations on arrays; in the same way, we can use other ufuncs to do element-wise *comparisons* over arrays, and we can then manipulate the results to answer the questions we have.
We'll leave the data aside for right now, and discuss some general tools in NumPy to use *masking* to quickly answer these types of questions.
## Comparison Operators as ufuncs
In [Computation on NumPy Arrays: Universal Functions](02.03-Computation-on-arrays-ufuncs.ipynb) we introduced ufuncs, and focused in particular on arithmetic operators. We saw that using ``+``, ``-``, ``*``, ``/``, and others on arrays leads to element-wise operations.
NumPy also implements comparison operators such as ``<`` (less than) and ``>`` (greater than) as element-wise ufuncs.
The result of these comparison operators is always an array with a Boolean data type.
All six of the standard comparison operations are available:
```
x = np.array([1, 2, 3, 4, 5])
x < 3 # less than
x > 3 # greater than
x <= 3 # less than or equal
x >= 3 # greater than or equal
x != 3 # not equal
x == 3 # equal
```
It is also possible to do an element-wise comparison of two arrays, and to include compound expressions:
```
(2 * x) == (x ** 2)
```
As in the case of arithmetic operators, the comparison operators are implemented as ufuncs in NumPy; for example, when you write ``x < 3``, internally NumPy uses ``np.less(x, 3)``.
A summary of the comparison operators and their equivalent ufunc is shown here:
| Operator | Equivalent ufunc || Operator | Equivalent ufunc |
|---------------|---------------------||---------------|---------------------|
|``==`` |``np.equal`` ||``!=`` |``np.not_equal`` |
|``<`` |``np.less`` ||``<=`` |``np.less_equal`` |
|``>`` |``np.greater`` ||``>=`` |``np.greater_equal`` |
Just as in the case of arithmetic ufuncs, these will work on arrays of any size and shape.
Here is a two-dimensional example:
```
rng = np.random.RandomState(0)
x = rng.randint(10, size=(3, 4))
x
x < 6
```
In each case, the result is a Boolean array, and NumPy provides a number of straightforward patterns for working with these Boolean results.
## Working with Boolean Arrays
Given a Boolean array, there are a host of useful operations you can do.
We'll work with ``x``, the two-dimensional array we created earlier.
```
print(x)
```
### Counting entries
To count the number of ``True`` entries in a Boolean array, ``np.count_nonzero`` is useful:
```
# how many values less than 6?
np.count_nonzero(x < 6)
```
We see that there are eight array entries that are less than 6.
Another way to get at this information is to use ``np.sum``; in this case, ``False`` is interpreted as ``0``, and ``True`` is interpreted as ``1``:
```
np.sum(x < 6)
```
The benefit of ``sum()`` is that like with other NumPy aggregation functions, this summation can be done along rows or columns as well:
```
# how many values less than 6 in each row?
np.sum(x < 6, axis=1)
```
This counts the number of values less than 6 in each row of the matrix.
If we're interested in quickly checking whether any or all the values are true, we can use (you guessed it) ``np.any`` or ``np.all``:
```
# are there any values greater than 8?
np.any(x > 8)
# are there any values less than zero?
np.any(x < 0)
# are all values less than 10?
np.all(x < 10)
# are all values equal to 6?
np.all(x == 6)
```
``np.all`` and ``np.any`` can be used along particular axes as well. For example:
```
# are all values in each row less than 8?
np.all(x < 8, axis=1)
```
Here all the elements in the first and third rows are less than 8, while this is not the case for the second row.
Finally, a quick warning: as mentioned in [Aggregations: Min, Max, and Everything In Between](02.04-Computation-on-arrays-aggregates.ipynb), Python has built-in ``sum()``, ``any()``, and ``all()`` functions. These have a different syntax than the NumPy versions, and in particular will fail or produce unintended results when used on multidimensional arrays. Be sure that you are using ``np.sum()``, ``np.any()``, and ``np.all()`` for these examples!
### Boolean operators
We've already seen how we might count, say, all days with rain less than four inches, or all days with rain greater than two inches.
But what if we want to know about all days with rain less than four inches and greater than one inch?
This is accomplished through Python's *bitwise logic operators*, ``&``, ``|``, ``^``, and ``~``.
Like with the standard arithmetic operators, NumPy overloads these as ufuncs which work element-wise on (usually Boolean) arrays.
For example, we can address this sort of compound question as follows:
```
np.sum((inches > 0.5) & (inches < 1))
```
So we see that there are 29 days with rainfall between 0.5 and 1.0 inches.
Note that the parentheses here are important–because of operator precedence rules, with parentheses removed this expression would be evaluated as follows, which results in an error:
``` python
inches > (0.5 & inches) < 1
```
Using the equivalence of *A AND B* and *NOT (NOT A OR NOT B)* (which you may remember if you've taken an introductory logic course), we can compute the same result in a different manner:
```
np.sum(~( (inches <= 0.5) | (inches >= 1) ))
```
Combining comparison operators and Boolean operators on arrays can lead to a wide range of efficient logical operations.
The following table summarizes the bitwise Boolean operators and their equivalent ufuncs:
| Operator | Equivalent ufunc || Operator | Equivalent ufunc |
|---------------|---------------------||---------------|---------------------|
|``&`` |``np.bitwise_and`` ||| |``np.bitwise_or`` |
|``^`` |``np.bitwise_xor`` ||``~`` |``np.bitwise_not`` |
Using these tools, we might start to answer the types of questions we have about our weather data.
Here are some examples of results we can compute when combining masking with aggregations:
```
print("Number days without rain: ", np.sum(inches == 0))
print("Number days with rain: ", np.sum(inches != 0))
print("Days with more than 0.5 inches:", np.sum(inches > 0.5))
print("Rainy days with < 0.2 inches :", np.sum((inches > 0) &
(inches < 0.2)))
```
## Boolean Arrays as Masks
In the preceding section we looked at aggregates computed directly on Boolean arrays.
A more powerful pattern is to use Boolean arrays as masks, to select particular subsets of the data themselves.
Returning to our ``x`` array from before, suppose we want an array of all values in the array that are less than, say, 5:
```
x
```
We can obtain a Boolean array for this condition easily, as we've already seen:
```
x < 5
```
Now to *select* these values from the array, we can simply index on this Boolean array; this is known as a *masking* operation:
```
x[x < 5]
```
What is returned is a one-dimensional array filled with all the values that meet this condition; in other words, all the values in positions at which the mask array is ``True``.
We are then free to operate on these values as we wish.
For example, we can compute some relevant statistics on our Seattle rain data:
```
# construct a mask of all rainy days
rainy = (inches > 0)
# construct a mask of all summer days (June 21st is the 172nd day)
days = np.arange(365)
summer = (days > 172) & (days < 262)
print("Median precip on rainy days in 2014 (inches): ",
np.median(inches[rainy]))
print("Median precip on summer days in 2014 (inches): ",
np.median(inches[summer]))
print("Maximum precip on summer days in 2014 (inches): ",
np.max(inches[summer]))
print("Median precip on non-summer rainy days (inches):",
np.median(inches[rainy & ~summer]))
```
By combining Boolean operations, masking operations, and aggregates, we can very quickly answer these sorts of questions for our dataset.
## Aside: Using the Keywords and/or Versus the Operators &/|
One common point of confusion is the difference between the keywords ``and`` and ``or`` on one hand, and the operators ``&`` and ``|`` on the other hand.
When would you use one versus the other?
The difference is this: ``and`` and ``or`` gauge the truth or falsehood of *entire object*, while ``&`` and ``|`` refer to *bits within each object*.
When you use ``and`` or ``or``, it's equivalent to asking Python to treat the object as a single Boolean entity.
In Python, all nonzero integers will evaluate as True. Thus:
```
bool(42), bool(0)
bool(42 and 0)
bool(42 or 0)
```
When you use ``&`` and ``|`` on integers, the expression operates on the bits of the element, applying the *and* or the *or* to the individual bits making up the number:
```
bin(42)
bin(59)
bin(42 & 59)
bin(42 | 59)
```
Notice that the corresponding bits of the binary representation are compared in order to yield the result.
When you have an array of Boolean values in NumPy, this can be thought of as a string of bits where ``1 = True`` and ``0 = False``, and the result of ``&`` and ``|`` operates similarly to above:
```
A = np.array([1, 0, 1, 0, 1, 0], dtype=bool)
B = np.array([1, 1, 1, 0, 1, 1], dtype=bool)
A | B
```
Using ``or`` on these arrays will try to evaluate the truth or falsehood of the entire array object, which is not a well-defined value:
```
A or B
```
Similarly, when doing a Boolean expression on a given array, you should use ``|`` or ``&`` rather than ``or`` or ``and``:
```
x = np.arange(10)
(x > 4) & (x < 8)
```
Trying to evaluate the truth or falsehood of the entire array will give the same ``ValueError`` we saw previously:
```
(x > 4) and (x < 8)
```
So remember this: ``and`` and ``or`` perform a single Boolean evaluation on an entire object, while ``&`` and ``|`` perform multiple Boolean evaluations on the content (the individual bits or bytes) of an object.
For Boolean NumPy arrays, the latter is nearly always the desired operation.
<!--NAVIGATION-->
< [Computation on Arrays: Broadcasting](02.05-Computation-on-arrays-broadcasting.ipynb) | [Contents](Index.ipynb) | [Fancy Indexing](02.07-Fancy-Indexing.ipynb) >
<a href="https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/02.06-Boolean-Arrays-and-Masks.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open and Execute in Google Colaboratory"></a>
| github_jupyter |
# scRNAseq Analysis of Tabula muris data
```
#
import matplotlib.pyplot as plt
import pandas as pd
import scanpy as sc
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
from scipy.stats import ttest_ind
#
brain_counts = pd.read_csv("data/brain_counts.csv", index_col=0)
# check the data
brain_counts
# rows: cell names (unique identifiers)
# columns: genes
#
brain_counts.shape
# load metadata
metadata = pd.read_csv("data/brain_metadata.csv", index_col=0)
# check the metadata
metadata
#
metadata.shape
# check value counts for each column
col = 0
for i in metadata.columns.values:
print("*** " + metadata.columns[col] + " ***")
print(metadata[i].value_counts())
print("-"*50)
col+=1
# build a AnnData object (=annotated data)
annotated_data = sc.AnnData(X=brain_counts, obs=metadata)
annotated_data
# check the AnnData obj
print("Gene names: ")
print(annotated_data.var_names)
# find spike-ins
spike_ins = {}
num_spike_ins = 0
for gene in annotated_data.var_names:
if 'ERCC' in gene:
spike_ins[gene] = True
num_spike_ins += 1
else:
spike_ins[gene] = False
annotated_data.var['ERCC'] = pd.Series(spike_ins)
print('Number of spike-ins: ', num_spike_ins)
#
annotated_data
# save AnnData
#annotated_data.write("../data/brain_annotated_data_obj.h5ad")
```
## Data Preprocessing - Quality control
```
# load annotated AnnData object
#annotated_data = sc.read("../data/brain_annotated_data_obj.h5ad")
# computation of qc metrics (for cells and for genes)
#
quality_ctrl = sc.pp.calculate_qc_metrics(annotated_data)
print(type(quality_ctrl))
quality_ctrl
# get additional information about the spike-ins
quality_ctrl = sc.pp.calculate_qc_metrics(annotated_data, qc_vars=["ERCC"])
quality_ctrl
# store the cell quality ctrl and the gene quality ctrl in extra vars
cell_quality = quality_ctrl[0]
gene_quality = quality_ctrl[1]
# check cell quality
cell_quality
# check gene quality
gene_quality
```
### QC for cells
```
# plot total number of reads per cell and check for existing cell with less than 50.000 reads
plt.figure(figsize=(12, 8))
plt.hist(cell_quality['total_counts'], bins=5000)
plt.axvline(50.000, color='red')
plt.title('Total Number of Reads per Cell')
plt.xlabel('Total Counts')
plt.ylabel('Number of Cells')
plt.show()
# plot number of unique genes per cell
plt.figure(figsize=(12, 8))
plt.hist(cell_quality['n_genes_by_counts'], bins=1000)
plt.title('Number of Unique Genes per Cell')
plt.xlabel('Number of Genes')
plt.ylabel('Number of Cells')
plt.axvline(1000, color='red')
plt.show()
# plot percentage of spike-ins
plt.figure(figsize=(12, 8))
plt.hist(cell_quality['pct_counts_ERCC'], bins=1000)
plt.title('Percentage Distribution of Spike-ins')
plt.xlabel('Percentage of Spike-ins')
plt.ylabel('Number of Cells')
plt.axvline(10, color='red')
plt.show()
# remove cells with more than 10 % spike-ins
less_10_spike_ins = cell_quality['pct_counts_ERCC'] < 10
annotated_data = annotated_data[less_10_spike_ins]
```
### QC for genes
```
annotated_data
# reserve only cells with minimum of 750 genes
sc.pp.filter_cells(annotated_data, min_genes=750)
# plot number of cells vs number of genes
plt.figure(figsize=(12, 8))
plt.hist(gene_quality['n_cells_by_counts'], bins=1000)
# "n_cells_by_counts": number of cells containing genes with an expression > 0
plt.title('Number of Cells vs Number of Genes where expression > 0')
plt.xlabel('Number of Cells')
plt.ylabel('log(Number of Genes)')
plt.yscale('log')
plt.axvline(2, color='red')
plt.show()
# plot total expression in genes
plt.figure(figsize=(12, 9))
plt.hist(gene_quality['total_counts'], bins=1000)
# "total_counts": sum of expression values for a given gene
plt.title('Total Expression of Genes')
plt.xlabel('Total Expression')
plt.ylabel('log(Number of Genes)')
plt.yscale('log')
plt.axvline(10, color='red')
plt.show()
# check number of genes before filtering
annotated_data
# filter genes
# Definition of a detectable gene:
# 2 cells need to contain > 5 reads from the gene
sc.pp.filter_genes(annotated_data, min_cells=2)
sc.pp.filter_genes(annotated_data, min_counts=10)
# check number of genes after filtering
annotated_data
# store annotated data
#annotated_data.write("../data/brain_annotated_data_quality.h5ad")
```
## Data Preprocessing - PCA
```
# apply PCA on data
sc.pp.pca(annotated_data)
# plot PCA results
plt.figure(figsize=(12, 12))
sc.pl.pca_overview(annotated_data, color='mouse.id', return_fig=False)
# 1st) PC1 vs PC2 diagram
# 2nd) Loadings = how much contributes a variable to a PC
# 3rd) how much contributes a PC to the variation of the data
```
## Data preprocessing - Normalization
### Normalization using CPM (counts per million)
- convert data to counts per million by dividing each cell (row) by a size factor (= sum of all counts in the row) and then multiply by 1x10⁶
```
# apply CPM
data_cpm = annotated_data.copy()
data_cpm.raw = data_cpm
sc.pp.normalize_per_cell(data_cpm, counts_per_cell_after=1e6)
# apply PCA on normalized data
sc.pp.pca(data_cpm)
# show PCA results
sc.pl.pca_overview(data_cpm, color='mouse.id')
# apply normalization using CPM and exclude highly expressed genes from the size factor calculation
data_cpm_ex_high_expressed = data_cpm.copy()
sc.pp.normalize_total(data_cpm_ex_high_expressed, target_sum=1e6, exclude_highly_expressed=True)
# apply PCA
sc.pp.pca(data_cpm_ex_high_expressed)
# show PCA results
sc.pl.pca_overview(data_cpm, color='mouse.id')
```
##### Normalizing gene expression
```
# remove gene Rn45s and apply PCA again
mask_Rn45s = data_cpm.var.index != 'Rn45s'
data_without_Rn45s = data_cpm[:, mask_Rn45s]
# apply PCA
sc.pp.pca(data_without_Rn45s)
# show PCA results
sc.pl.pca_overview(data_without_Rn45s, color='mouse.id')
```
##### Scaling the expression values
```
# log(1+x) of each value
sc.pp.log1p(data_cpm)
# scaling each value using z-score
sc.pp.scale(data_cpm)
# PCA
sc.pp.pca(data_cpm)
# PCA results
sc.pl.pca_overview(data_cpm, color='plate.barcode')
# store normalized data
#data_cpm.write("../data/brain_annotated_data_normalized.h5ad")
```
## Data Analysis - Dimensionality Reduction
### tSNE (t-Distributed Stochastic Neighbor Embedding)
```
# apply tSNE and show results
sc.tl.tsne(data_cpm, perplexity=45, learning_rate=800, random_state=42)
sc.pl.tsne(data_cpm, color='cell_ontology_class')
# store tSNE results
#data_cpm.write('data/brain_annotated_data_tsne.h5ad')
```
## Data Analysis - Clustering
### k-Means Clustering
```
# extract coordinates of the tSNE data
tsne_data = data_cpm
tsne_coords = tsne_data.obsm['X_tsne']
# apply kmeans
kmeans = KMeans(n_clusters=4, random_state=42)
kmeans.fit(tsne_coords)
# add labels to meta data column
tsne_data.obs['kmeans'] = kmeans.labels_
tsne_data.obs['kmeans'] = tsne_data.obs['kmeans'].astype(str)
# plot results
sc.pl.tsne(tsne_data, color='kmeans')
```
### Adjusted Rand Index
```
# evalutate the clustering results using the adj rand idx
adj_rand_idx = adjusted_rand_score(labels_true=tsne_data.obs['cell_ontology_class'],
labels_pred=tsne_data.obs['kmeans'])
round(adj_rand_idx, 2)
# store cluster results
tsne_data.write('data/brain_cluster_results.h5ad')
```
## Data Analysis - Differential Expression
```
# load/store cluster data
#cluster_data = sc.read('data/brain_cluster_results.h5ad')
cluster_data = tsne_data
# store raw data
raw_data = pd.DataFrame(data=cluster_data.raw.X, index=cluster_data.raw.obs_names,
columns=cluster_data.raw.var_names)
# define a gene of interest
astrocyte_marker = 'Gja1'
# astrocyte are cluster 2
cluster_2 = raw_data[cluster_data.obs['kmeans'] == '2']
without_cluster_2 = raw_data[cluster_data.obs['kmeans'] != '2']
# histograms
cluster_2_marker = cluster_2[astrocyte_marker]
plt.hist(cluster_2_marker.values, bins=100, color='purple',
label='Cluster 2', alpha=.5)
without_cluster_2_marker = without_cluster_2[astrocyte_marker]
plt.hist(without_cluster_2_marker.values, bins=1000, color='black', label='Other Clusters')
plt.xlabel(f'{astrocyte_marker} Expression')
plt.ylabel('Number of Cells')
plt.yscale('log')
plt.legend()
plt.show()
# use independent t-test to check whether clusters reveal statistical significant difference
ttest = ttest_ind(cluster_2_marker, without_cluster_2_marker, equal_var=False, nan_policy='omit')
print(ttest)
print(round(ttest.statistic, 2))
print(round(ttest.pvalue, 2))
```
| github_jupyter |
# CSX46
## Class session 6: BFS
Objective: write and test a function that can compute single-vertex shortest paths in an unweighted simple graph. Compare to the results that we get using `igraph.Graph.get_shortest_paths()`.
We're going to need several packages for this notebook; let's import them first
```
import random
import igraph
import numpy as np
import math
import collections
```
Let's set the random number seed using `random.seed` and with seed value 1337, so that we are all starting with the same graph structure. Make a simple 10-vertex random (Barabasi-Albert model) graph. Set the random number seed so that the graph is always the same, for purposes of reproducibility (we want to know that the "hub" vertex will be vertex 2, and we will test your BFS function starting at that "hub" vertex).
Let's plot the graph, using `bbox=[0,0,200,200]` so it is not huge, and using `vertex_label=` to display the vertex IDs.
Let's look at an adjacency list representation of the graph, using the method `igraph.Graph.get_adjlist`
Let's look at the degrees of the vertices using the `igraph.Graph.degree` method and the `enumerate` built-in function and list comprehension:
OK, let's implement a function to compute shortest-path (geodesic path) distances to all vertices in the graph, starting at a single vertex `p_vertex`. We'll implement the
breadth-first search (BFS) algorithm in order to compute these geodesic path distances.
We'll start by implementing the queue data structure "by hand" with our own `read_ptr` and `write_ptr` exactly as described on page 320 of Newman's book. Newman says to use an "array" to implement the queue. As it turns out, Python's native `list` data type is internally implemented as a (resizeable) array, so we can just use a `list` here. We'll call our function `bfs_single_vertex_newman`.
```
# compute N, the number of vertices by calling len() on the VertexSet obtained from graph.vs()
# initialize "queue" array (length N, containing np.nan)
# initialize distances array (length N, containing np.nan)
# set "p_vertex" entry of distances array to be 0
# while write_ptr is gerater than read_ptr:
# obtain the vertex ID of the entry at index "read_ptr" in the queue array, as cur_vertex_num
# increment read_ptr
# get the distance to cur_vertex_num, from the "distances" array
# get the neighbors of vertex cur_vertex_num in the graph, using the igraph "neighbors" func
# for each vertex_neighbor in the array vertex_neighbors
# if the distances[vertex_neighbor] is nan:
# (1) set the distance to vertex_neighbor (in "distances" vector) to the distance to
# cur_vertex_num, plus one
# (2) add neighbor to the queue
# put vertex_neighbor at position write_ptr in the queue array
# increment write_ptr
# end-while
# return "distances"
```
Let's test out our implementation of `bfs_single_vertex_newman`, on vertex 0 of the graph. Do the results make sense?
Now let's re-implement the single-vertex BFS distance function using a convenient queue data structure, `collections.deque` (note, `deque` is actually a *double-ended* queue, so it is a bit more fancy than we need, but that's OK, we just will only be using its methods `popleft` and `append`)
```
# compute N, the number of vertices by calling len() on the VertexSet obtained from graph.vs()
# create a deque data structure called "queue" and initialize it to contain p_vertex
# while the queue is not empty:
# pop vertex_id off of the left of the queue
# get the vertex_id entry of the distances vector, call it "vertex_dist"
# for each neighbor_id of vertex_id:
# if the neighbor_id entry of the distances vector is nan:
# set the neighbor_id entry of the distances vector to vertex_dist + 1
# append neighbor_id to the queue
# return "distances"
```
Compare the code implementations of `bfs_single_vertex_newman` and `bfs_single_vertex`. Which is easier to read and understand?
Test out your function `bfs_single_vertex` on vertex 0. Do we get the same result as when we used `bfs_single_vertex_newman`?
If the graph was a lot bigger, how could we systematically check that the results of `bfs_single_vertex` (from vertex 0) are correctly calculated? We can use the `igraph.Graph.get_shortest_paths` method, and specify `v=0`. Let's look at the results of calling `get_shortest_paths` with `v=0`:
So, clearly, we need to calculate the length of the list of vertices in each entry of this ragged list. But the *path* length is one less than the length of the list of vertices, so we have to subtract one in order to get the correct path length. Now we are ready to compare our BFS-based single-vertex geodesic distances with the results from calling `igraph.Graph.get_shortest_paths`:
Now let's implement a function that can compute a numpy.matrix of geodesic path distances for all pairs of vertices. The pythonic way to do this is probably to use the list-of-lists constructor for np.array, and to use list comprehension.
```
def sp_matrix(p_graph):
return FILL IN HERE
```
How about if we want to implement it using a plain old for loop?
```
def sp_matrix_forloop(p_graph):
N = FILL IN HERE
geo_dists = FILL IN HERE
FILL IN HERE
return geo_dists
```
Let's run it on our little ten-vertex graph:
| github_jupyter |
##### Copyright 2020 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Better ML Engineering with ML Metadata
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tfx/tutorials/mlmd_tutorial"><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/tfx/blob/master/docs/tutorials/mlmd_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/docs/blob/master/tools/templates/notebook.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/tools/templates/notebook.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
Assume a scenario where you set up a production ML pipeline to classify pictures of iris flowers. The pipeline ingests your training data, trains and evaluates a model, and pushes it to production.
However, when you later try using this model with a larger dataset that contains images of different kinds of flowers, you observe that your model does not behave as expected and starts classifying roses and lilies as types of irises.
At this point, you are interested in knowing:
* What is the most efficient way to debug the model when the only available artifact is the model in production?
* Which training dataset was used to train the model?
* Which training run led to this erroneous model?
* Where are the model evaluation results?
* Where to begin debugging?
[ML Metadata (MLMD)](https://github.com/google/ml-metadata) is a library that leverages the metadata associated with ML models to help you answer these questions and more. A helpful analogy is to think of this metadata as the equivalent of logging in software development. MLMD enables you to reliably track the artifacts and lineage associated with the various components of your ML pipeline.
In this tutorial, you set up a TFX Pipeline to create a model that classifies Iris flowers into three species - Iris setosa, Iris virginica, and Iris versicolor based on the length and width measurements of their petals and sepals. You then use MLMD to track the lineage of pipeline components.
## TFX Pipelines in Colab
Colab is a lightweight development environment which differs significantly from a production environment. In production, you may have various pipeline components like data ingestion, transformation, model training, run histories, etc. across multiple, distributed systems. For this tutorial, you should be aware that siginificant differences exist in Orchestration and Metadata storage - it is all handled locally within Colab. Learn more about TFX in Colab [here](https://www.tensorflow.org/tfx/tutorials/tfx/components_keras#background).
## Setup
Import all required libraries.
### Install and import TFX
```
!pip install --quiet tfx==0.23.0
```
You must restart the Colab runtime after installing TFX. Select **Runtime > Restart runtime** from the Colab menu.
Do not proceed with the rest of this tutorial without first restarting the runtime.
### Import other libraries
```
import base64
import csv
import json
import os
import requests
import tempfile
import urllib
import pprint
import numpy as np
import pandas as pd
pp = pprint.PrettyPrinter()
import tensorflow as tf
import tfx
```
Import [TFX component](https://tensorflow.google.cn/tfx/tutorials/tfx/components_keras) classes.
```
from tfx.components.evaluator.component import Evaluator
from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen
from tfx.components.pusher.component import Pusher
from tfx.components.schema_gen.component import SchemaGen
from tfx.components.statistics_gen.component import StatisticsGen
from tfx.components.trainer.component import Trainer
from tfx.components.base import executor_spec
from tfx.components.trainer.executor import GenericExecutor
from tfx.orchestration.experimental.interactive.interactive_context import InteractiveContext
from tfx.proto import evaluator_pb2
from tfx.proto import pusher_pb2
from tfx.proto import trainer_pb2
from tfx.utils.dsl_utils import external_input
from tensorflow_metadata.proto.v0 import anomalies_pb2
from tensorflow_metadata.proto.v0 import schema_pb2
from tensorflow_metadata.proto.v0 import statistics_pb2
import tensorflow_model_analysis as tfma
from tfx.components import ResolverNode
from tfx.dsl.experimental import latest_blessed_model_resolver
from tfx.types import Channel
from tfx.types.standard_artifacts import Model
from tfx.types.standard_artifacts import ModelBlessing
```
Import the MLMD library.
```
import ml_metadata as mlmd
from ml_metadata.proto import metadata_store_pb2
```
## Download the dataset
Download the [Iris dataset](https://archive.ics.uci.edu/ml/datasets/iris) dataset to use in this tutorial. The dataset contains data about the length and width measurements of sepals and petals for 150 Iris flowers. You use this data to classify irises into one of three species - Iris setosa, Iris virginica, and Iris versicolor.
```
DATA_PATH = 'https://raw.githubusercontent.com/tensorflow/tfx/master/tfx/examples/iris/data/iris.csv'
_data_root = tempfile.mkdtemp(prefix='tfx-data')
_data_filepath = os.path.join(_data_root, "iris.csv")
urllib.request.urlretrieve(DATA_PATH, _data_filepath)
```
## Create an InteractiveContext
To run TFX components interactively in this notebook, create an `InteractiveContext`. The `InteractiveContext` uses a temporary directory with an ephemeral MLMD database instance. Note that calls to `InteractiveContext` are no-ops outside the Colab environment.
In general, it is a good practice to group similar pipeline runs under a `Context`.
```
interactive_context = InteractiveContext()
```
## Construct the TFX Pipeline
A TFX pipeline consists of several components that perform different aspects of the ML workflow. In this notebook, you create and run the `ExampleGen`, `StatisticsGen`, `SchemaGen`, and `TrainerGen` components and use the `Evaluator` and `Pusher` component to evaluate and push the trained model.
Refer to the [components tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/components_keras) for more information on TFX pipeline components.
Note: Constructing a TFX Pipeline by setting up the individual components involves a lot of boilerplate code. For the purpose of this tutorial, it is alright if you do not fully understand every line of code in the pipeline setup.
### Instantiate and run the ExampleGen Component
```
input_data = external_input(_data_root)
example_gen = CsvExampleGen(input=input_data)
# Run the ExampleGen component using the InteractiveContext
interactive_context.run(example_gen)
```
### Instantiate and run the StatisticsGen Component
```
statistics_gen = StatisticsGen(examples=example_gen.outputs['examples'])
# Run the StatisticsGen component using the InteractiveContext
interactive_context.run(statistics_gen)
```
### Instantiate and run the SchemaGen Component
```
infer_schema = SchemaGen(statistics=statistics_gen.outputs['statistics'],
infer_feature_shape = True)
# Run the SchemaGen component using the InteractiveContext
interactive_context.run(infer_schema)
```
### Instantiate and run the Trainer Component
```
# Define the module file for the Trainer component
trainer_module_file = 'iris_trainer.py'
%%writefile {trainer_module_file}
# Define the training algorithm for the Trainer module file
import os
from typing import List, Text
import tensorflow as tf
from tensorflow import keras
from tfx.components.trainer.executor import TrainerFnArgs
from tfx.components.trainer.fn_args_utils import FnArgs
# The iris dataset has 150 records, and is split into training and evaluation
# datasets in a 2:1 split
_TRAIN_DATA_SIZE = 100
_EVAL_DATA_SIZE = 50
_TRAIN_BATCH_SIZE = 100
_EVAL_BATCH_SIZE = 50
# Features used for classification - sepal length and width, petal length and
# width, and variety (species of flower)
_FEATURES = {
'sepal_length': tf.io.FixedLenFeature([], dtype=tf.float32, default_value=0),
'sepal_width': tf.io.FixedLenFeature([], dtype=tf.float32, default_value=0),
'petal_length': tf.io.FixedLenFeature([], dtype=tf.float32, default_value=0),
'petal_width': tf.io.FixedLenFeature([], dtype=tf.float32, default_value=0),
'variety': tf.io.FixedLenFeature([], dtype=tf.int64, default_value=0)
}
_LABEL_KEY = 'variety'
_FEATURE_KEYS = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
def _gzip_reader_fn(filenames):
return tf.data.TFRecordDataset(filenames, compression_type='GZIP')
def _input_fn(file_pattern: List[Text],
batch_size: int = 200):
dataset = tf.data.experimental.make_batched_features_dataset(
file_pattern=file_pattern,
batch_size=batch_size,
features=_FEATURES,
reader=_gzip_reader_fn,
label_key=_LABEL_KEY)
return dataset
def _build_keras_model():
inputs = [keras.layers.Input(shape = (1,), name = f) for f in _FEATURE_KEYS]
d = keras.layers.concatenate(inputs)
d = keras.layers.Dense(8, activation = 'relu')(d)
d = keras.layers.Dense(8, activation = 'relu')(d)
outputs = keras.layers.Dense(3, activation = 'softmax')(d)
model = keras.Model(inputs=inputs, outputs=outputs)
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics= [keras.metrics.SparseCategoricalAccuracy()])
return model
def run_fn(fn_args: TrainerFnArgs):
train_dataset = _input_fn(fn_args.train_files, batch_size=_TRAIN_BATCH_SIZE)
eval_dataset = _input_fn(fn_args.eval_files, batch_size=_EVAL_BATCH_SIZE)
model = _build_keras_model()
steps_per_epoch = _TRAIN_DATA_SIZE / _TRAIN_BATCH_SIZE
model.fit(train_dataset,
epochs=int(fn_args.train_steps / steps_per_epoch),
steps_per_epoch=steps_per_epoch,
validation_data=eval_dataset,
validation_steps=fn_args.eval_steps)
model.save(fn_args.serving_model_dir, save_format='tf')
```
Run the `Trainer` component.
```
trainer = Trainer(
module_file=os.path.abspath(trainer_module_file),
custom_executor_spec=executor_spec.ExecutorClassSpec(GenericExecutor),
examples=example_gen.outputs['examples'],
schema=infer_schema.outputs['schema'],
train_args=trainer_pb2.TrainArgs(num_steps=100),
eval_args=trainer_pb2.EvalArgs(num_steps=50))
interactive_context.run(trainer)
```
### Evaluate and push the model
Use the `Evaluator` component to evaluate and 'bless' the model before using the `Pusher` component to push the model to a serving directory.
```
_serving_model_dir = os.path.join(tempfile.mkdtemp(), 'serving_model/iris_classification')
eval_config = tfma.EvalConfig(model_specs=[tfma.ModelSpec(label_key ='variety')],
metrics_specs =[tfma.MetricsSpec(metrics =
[tfma.MetricConfig(class_name='ExampleCount'),
tfma.MetricConfig(class_name='BinaryAccuracy',
threshold=tfma.MetricThreshold(
value_threshold=tfma.GenericValueThreshold(
lower_bound={'value': 0.5}),
change_threshold=tfma.GenericChangeThreshold(
direction=tfma.MetricDirection.HIGHER_IS_BETTER,
absolute={'value': -1e-10})))])],
slicing_specs = [tfma.SlicingSpec(),
tfma.SlicingSpec(feature_keys=['sepal_length'])])
model_resolver = ResolverNode(
instance_name='latest_blessed_model_resolver',
resolver_class=latest_blessed_model_resolver.LatestBlessedModelResolver,
model=Channel(type=Model),
model_blessing=Channel(type=ModelBlessing))
interactive_context.run(model_resolver)
evaluator = Evaluator(
examples=example_gen.outputs['examples'],
model=trainer.outputs['model'],
baseline_model=model_resolver.outputs['model'],
eval_config=eval_config)
interactive_context.run(evaluator)
pusher = Pusher(
model=trainer.outputs['model'],
model_blessing=evaluator.outputs['blessing'],
push_destination=pusher_pb2.PushDestination(
filesystem=pusher_pb2.PushDestination.Filesystem(
base_directory=_serving_model_dir)))
interactive_context.run(pusher)
```
Running the TFX pipeline populates the MLMD Database. In the next section, you use the MLMD API to query this database for metadata information.
## Query the MLMD Database
The MLMD database stores three types of metadata:
* Metadata about the pipeline and lineage information associated with the pipeline components
* Metadata about artifacts that were generated during the pipeline run
* Metadata about the executions of the pipeline
A typical production environment pipeline serves multiple models as new data arrives. When you encounter erroneous results in served models, you can query the MLMD database to isolate the erroneous models. You can then trace the lineage of the pipeline components that correspond to these models to debug your models
Set up the metadata (MD) store with the `InteractiveContext` defined previously to query the MLMD database.
```
#md_store = mlmd.MetadataStore(interactive_context.metadata_connection_config)
store = mlmd.MetadataStore(interactive_context.metadata_connection_config)
# All TFX artifacts are stored in the base directory
base_dir = interactive_context.metadata_connection_config.sqlite.filename_uri.split('metadata.sqlite')[0]
```
Create some helper functions to view the data from the MD store.
```
def display_types(types):
# Helper function to render dataframes for the artifact and execution types
table = {'id': [], 'name': []}
for a_type in types:
table['id'].append(a_type.id)
table['name'].append(a_type.name)
return pd.DataFrame(data=table)
def display_artifacts(store, artifacts):
# Helper function to render dataframes for the input artifacts
table = {'artifact id': [], 'type': [], 'uri': []}
for a in artifacts:
table['artifact id'].append(a.id)
artifact_type = store.get_artifact_types_by_id([a.type_id])[0]
table['type'].append(artifact_type.name)
table['uri'].append(a.uri.replace(base_dir, './'))
return pd.DataFrame(data=table)
def display_properties(store, node):
# Helper function to render dataframes for artifact and execution properties
table = {'property': [], 'value': []}
for k, v in node.properties.items():
table['property'].append(k)
table['value'].append(
v.string_value if v.HasField('string_value') else v.int_value)
for k, v in node.custom_properties.items():
table['property'].append(k)
table['value'].append(
v.string_value if v.HasField('string_value') else v.int_value)
return pd.DataFrame(data=table)
```
First, query the MD store for a list of all its stored `ArtifactTypes`.
```
display_types(store.get_artifact_types())
```
Next, query all `PushedModel` artifacts.
```
pushed_models = store.get_artifacts_by_type("PushedModel")
display_artifacts(store, pushed_models)
```
Query the MD store for the latest pushed model. This tutorial has only one pushed model.
```
pushed_model = pushed_models[-1]
display_properties(store, pushed_model)
```
One of the first steps in debugging a pushed model is to look at which trained model is pushed and to see which training data is used to train that model.
MLMD provides traversal APIs to walk through the provenance graph, which you can use to analyze the model provenance.
```
def get_one_hop_parent_artifacts(store, artifacts):
# Get a list of artifacts within a 1-hop neighborhood of the artifacts of interest
artifact_ids = [artifact.id for artifact in artifacts]
executions_ids = set(
event.execution_id
for event in store.get_events_by_artifact_ids(artifact_ids)
if event.type == metadata_store_pb2.Event.OUTPUT)
artifacts_ids = set(
event.artifact_id
for event in store.get_events_by_execution_ids(executions_ids)
if event.type == metadata_store_pb2.Event.INPUT)
return [artifact for artifact in store.get_artifacts_by_id(artifacts_ids)]
```
Query the parent artifacts for the pushed model.
```
parent_artifacts = get_one_hop_parent_artifacts(store, [pushed_model])
display_artifacts(store, parent_artifacts)
```
Query the properties for the model.
```
exported_model = parent_artifacts[0]
display_properties(store, exported_model)
```
Query the upstream artifacts for the model.
```
model_parents = get_one_hop_parent_artifacts(store, [exported_model])
display_artifacts(store, model_parents)
```
Get the training data the model trained with.
```
used_data = model_parents[0]
display_properties(store, used_data)
```
Now that you have the training data that the model trained with, query the database again to find the training step (execution). Query the MD store for a list of the registered execution types.
```
display_types(store.get_execution_types())
```
The training step is the `ExecutionType` named `tfx.components.trainer.component.Trainer`. Traverse the MD store to get the trainer run that corresponds to the pushed model.
```
def find_producer_execution(store, artifact):
executions_ids = set(
event.execution_id
for event in store.get_events_by_artifact_ids([artifact.id])
if event.type == metadata_store_pb2.Event.OUTPUT)
return store.get_executions_by_id(executions_ids)[0]
trainer = find_producer_execution(store, exported_model)
display_properties(store, trainer)
```
## Summary
In this tutorial, you learned about how you can leverage MLMD to trace the lineage of your TFX pipeline components and resolve issues.
To learn more about how to use MLMD, check out these additional resources:
* [MLMD API documentation](https://www.tensorflow.org/tfx/ml_metadata/api_docs/python/mlmd)
* [MLMD guide](https://www.tensorflow.org/tfx/guide/mlmd)
| github_jupyter |
# Robot Class
In this project, we'll be localizing a robot in a 2D grid world. The basis for simultaneous localization and mapping (SLAM) is to gather information from a robot's sensors and motions over time, and then use information about measurements and motion to re-construct a map of the world.
### Uncertainty
As you've learned, robot motion and sensors have some uncertainty associated with them. For example, imagine a car driving up hill and down hill; the speedometer reading will likely overestimate the speed of the car going up hill and underestimate the speed of the car going down hill because it cannot perfectly account for gravity. Similarly, we cannot perfectly predict the *motion* of a robot. A robot is likely to slightly overshoot or undershoot a target location.
In this notebook, we'll look at the `robot` class that is *partially* given to you for the upcoming SLAM notebook. First, we'll create a robot and move it around a 2D grid world. Then, **you'll be tasked with defining a `sense` function for this robot that allows it to sense landmarks in a given world**! It's important that you understand how this robot moves, senses, and how it keeps track of different landmarks that it sees in a 2D grid world, so that you can work with it's movement and sensor data.
---
Before we start analyzing robot motion, let's load in our resources and define the `robot` class. You can see that this class initializes the robot's position and adds measures of uncertainty for motion. You'll also see a `sense()` function which is not yet implemented, and you will learn more about that later in this notebook.
```
# import some resources
import numpy as np
import matplotlib.pyplot as plt
import random
%matplotlib inline
# the robot class
class robot:
# --------
# init:
# creates a robot with the specified parameters and initializes
# the location (self.x, self.y) to the center of the world
#
def __init__(self, world_size = 100.0, measurement_range = 30.0,
motion_noise = 1.0, measurement_noise = 1.0):
self.measurement_noise = 0.0
self.world_size = world_size
self.measurement_range = measurement_range
self.x = world_size / 2.0
self.y = world_size / 2.0
self.motion_noise = motion_noise
self.measurement_noise = measurement_noise
self.landmarks = []
self.num_landmarks = 0
# returns a positive, random float
def rand(self):
return random.random() * 2.0 - 1.0
# --------
# move: attempts to move robot by dx, dy. If outside world
# boundary, then the move does nothing and instead returns failure
#
def move(self, dx, dy):
x = self.x + dx + self.rand() * self.motion_noise
y = self.y + dy + self.rand() * self.motion_noise
if x < 0.0 or x > self.world_size or y < 0.0 or y > self.world_size:
return False
else:
self.x = x
self.y = y
return True
# --------
# sense: returns x- and y- distances to landmarks within visibility range
# because not all landmarks may be in this range, the list of measurements
# is of variable length. Set measurement_range to -1 if you want all
# landmarks to be visible at all times
#
## TODO: complete the sense function
def sense(self):
''' This function does not take in any parameters, instead it references internal variables
(such as self.landamrks) to measure the distance between the robot and any landmarks
that the robot can see (that are within its measurement range).
This function returns a list of landmark indices, and the measured distances (dx, dy)
between the robot's position and said landmarks.
This function should account for measurement_noise and measurement_range.
One item in the returned list should be in the form: [landmark_index, dx, dy].
'''
measurements = []
## TODO: iterate through all of the landmarks in a world
for i, lm in enumerate(self.landmarks):
## 1. compute dx and dy, the distances between the robot and the landmark
dx = lm[0] - self.x
dy = lm[1] - self.y
## TODO: For each landmark
## 2. account for measurement noise by *adding* a noise component to dx and dy
dx += self.rand() * self.measurement_noise
dy += self.rand() * self.measurement_noise
## - The noise component should be a random value between [-1.0, 1.0)*measurement_noise
## - Feel free to use the function self.rand() to help calculate this noise component
## - It may help to reference the `move` function for noise calculation
## 3. If either of the distances, dx or dy, fall outside of the internal var, measurement_range
## then we cannot record them; if they do fall in the range, then add them to the measurements list
## as list.append([index, dx, dy]), this format is important for data creation done later
if abs(dx) <= self.measurement_range and abs(dy) <= self.measurement_range:
measurements.append([i, dx, dy])
## TODO: return the final, complete list of measurements
return measurements
# --------
# make_landmarks:
# make random landmarks located in the world
#
def make_landmarks(self, num_landmarks):
self.landmarks = []
for i in range(num_landmarks):
self.landmarks.append([round(random.random() * self.world_size),
round(random.random() * self.world_size)])
self.num_landmarks = num_landmarks
# called when print(robot) is called; prints the robot's location
def __repr__(self):
return 'Robot: [x=%.5f y=%.5f]' % (self.x, self.y)
```
## Define a world and a robot
Next, let's instantiate a robot object. As you can see in `__init__` above, the robot class takes in a number of parameters including a world size and some values that indicate the sensing and movement capabilities of the robot.
In the next example, we define a small 10x10 square world, a measurement range that is half that of the world and small values for motion and measurement noise. These values will typically be about 10 times larger, but we ust want to demonstrate this behavior on a small scale. You are also free to change these values and note what happens as your robot moves!
```
world_size = 10.0 # size of world (square)
measurement_range = 5.0 # range at which we can sense landmarks
motion_noise = 0.2 # noise in robot motion
measurement_noise = 0.2 # noise in the measurements
# instantiate a robot, r
r = robot(world_size, measurement_range, motion_noise, measurement_noise)
# print out the location of r
print(r)
```
## Visualizing the World
In the given example, we can see/print out that the robot is in the middle of the 10x10 world at (x, y) = (5.0, 5.0), which is exactly what we expect!
However, it's kind of hard to imagine this robot in the center of a world, without visualizing the grid itself, and so in the next cell we provide a helper visualization function, `display_world`, that will display a grid world in a plot and draw a red `o` at the location of our robot, `r`. The details of how this function wors can be found in the `helpers.py` file in the home directory; you do not have to change anything in this `helpers.py` file.
```
# import helper function
from helpers import display_world
# define figure size
plt.rcParams["figure.figsize"] = (5,5)
# call display_world and display the robot in it's grid world
print(r)
display_world(int(world_size), [r.x, r.y])
```
## Movement
Now you can really picture where the robot is in the world! Next, let's call the robot's `move` function. We'll ask it to move some distance `(dx, dy)` and we'll see that this motion is not perfect by the placement of our robot `o` and by the printed out position of `r`.
Try changing the values of `dx` and `dy` and/or running this cell multiple times; see how the robot moves and how the uncertainty in robot motion accumulates over multiple movements.
#### For a `dx` = 1, does the robot move *exactly* one spot to the right? What about `dx` = -1? What happens if you try to move the robot past the boundaries of the world?
```
# choose values of dx and dy (negative works, too)
dx = 1
dy = 2
r.move(dx, dy)
# print out the exact location
print(r)
# display the world after movement, not that this is the same call as before
# the robot tracks its own movement
display_world(int(world_size), [r.x, r.y])
```
## Landmarks
Next, let's create landmarks, which are measurable features in the map. You can think of landmarks as things like notable buildings, or something smaller such as a tree, rock, or other feature.
The robot class has a function `make_landmarks` which randomly generates locations for the number of specified landmarks. Try changing `num_landmarks` or running this cell multiple times to see where these landmarks appear. We have to pass these locations as a third argument to the `display_world` function and the list of landmark locations is accessed similar to how we find the robot position `r.landmarks`.
Each landmark is displayed as a purple `x` in the grid world, and we also print out the exact `[x, y]` locations of these landmarks at the end of this cell.
```
# create any number of landmarks
num_landmarks = 3
r.make_landmarks(num_landmarks)
# print out our robot's exact location
print(r)
# display the world including these landmarks
display_world(int(world_size), [r.x, r.y], r.landmarks)
# print the locations of the landmarks
print('Landmark locations [x,y]: ', r.landmarks)
```
## Sense
Once we have some landmarks to sense, we need to be able to tell our robot to *try* to sense how far they are away from it. It will be up t you to code the `sense` function in our robot class.
The `sense` function uses only internal class parameters and returns a list of the the measured/sensed x and y distances to the landmarks it senses within the specified `measurement_range`.
### TODO: Implement the `sense` function
Follow the `##TODO's` in the class code above to complete the `sense` function for the robot class. Once you have tested out your code, please **copy your complete `sense` code to the `robot_class.py` file in the home directory**. By placing this complete code in the `robot_class` Python file, we will be able to refernce this class in a later notebook.
The measurements have the format, `[i, dx, dy]` where `i` is the landmark index (0, 1, 2, ...) and `dx` and `dy` are the measured distance between the robot's location (x, y) and the landmark's location (x, y). This distance will not be perfect since our sense function has some associated `measurement noise`.
---
In the example in the following cell, we have a given our robot a range of `5.0` so any landmarks that are within that range of our robot's location, should appear in a list of measurements. Not all landmarks are guaranteed to be in our visibility range, so this list will be variable in length.
*Note: the robot's location is often called the **pose** or `[Pxi, Pyi]` and the landmark locations are often written as `[Lxi, Lyi]`. You'll see this notation in the next notebook.*
```
# try to sense any surrounding landmarks
measurements = r.sense()
# this will print out an empty list if `sense` has not been implemented
print(measurements)
```
**Refer back to the grid map above. Do these measurements make sense to you? Are all the landmarks captured in this list (why/why not)?**
---
## Data
#### Putting it all together
To perform SLAM, we'll collect a series of robot sensor measurements and motions, in that order, over a defined period of time. Then we'll use only this data to re-construct the map of the world with the robot and landmar locations. You can think of SLAM as peforming what we've done in this notebook, only backwards. Instead of defining a world and robot and creating movement and sensor data, it will be up to you to use movement and sensor measurements to reconstruct the world!
In the next notebook, you'll see this list of movements and measurements (which you'll use to re-construct the world) listed in a structure called `data`. This is an array that holds sensor measurements and movements in a specific order, which will be useful to call upon when you have to extract this data and form constraint matrices and vectors.
`data` is constructed over a series of time steps as follows:
```
data = []
# after a robot first senses, then moves (one time step)
# that data is appended like so:
data.append([measurements, [dx, dy]])
# for our example movement and measurement
print(data)
# in this example, we have only created one time step (0)
time_step = 0
# so you can access robot measurements:
print('Measurements: ', data[time_step][0])
# and its motion for a given time step:
print('Motion: ', data[time_step][1])
```
### Final robot class
Before moving on to the last notebook in this series, please make sure that you have copied your final, completed `sense` function into the `robot_class.py` file in the home directory. We will be using this file in the final implementation of slam!
| github_jupyter |
# Matrix Solutions
## Introduction to Linear Programming
This gives some foundational methods of working with arrays to do matrix multiplication
```
import numpy as np
#Let's put in a m(rows) x n(columns)
quant = np.array([[8, 5, 8, 0],
[8, 2, 4, 0],
[8, 7, 7, 5]])
price = np.array([75,50,10,105])
#This prints a 3 x 4 matrix
quant
#Price is a 1 x 4
price
#This performance the transpose operation on the matrix.
#This turns a 3 x 4 matrix to a 4 x 3 matrix
quant.T
```
If vectors are identified with row matrices, the dot product can also be written as a matrix product


```
#Remember that the dot product is the same as the sumproduct here.
#Here multipying a 3 x 4 by a 1 x 4 matrix.
#The 1 x 4 matrix is really a 4 x 1 because the dot product involves the
#The transpose of the matrix.
sum_cost= quant.dot(price)
sum_cost
#Notice when multiplying we have to keep the inner numbers the same.
# 1 x 4 by a 4 x 3
price.dot(quant.T)
!pip install pulp
#Import some required packages.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```

```
#Initialize the model as a minimization problem.
import pulp as pl
opt_model = pl.LpProblem("MIPModel", pl.LpMinimize)
#Set the variables. Notice this is where we put
# the "non-negativity" constraint
for x in range(1,4):
for y in range(1,4):
var='x'+str(x)+str(y)
print(var)
#this systematically creates all the variables.
exec(var +' = pl.LpVariable(cat=pl.LpInteger, lowBound=0, name="$'+var+'$")')
#x1 =pl.LpVariable(cat=pl.LpInteger, lowBound=0, name="$x_{1}$")
#x2 =pl.LpVariable(cat=pl.LpInteger, lowBound=0, name="$x_{2}$")
#Set the objective function
opt_model += np.array([x11, x12, x13], \
[x21, x22, x23],\
[x11, x12, x13]])
#Set the Constraints
opt_model += 2 * x1 + 4* x2 >= 16
opt_model += 4 * x1 + 3 * x2 >= 24
```
## Review Model
Now that we have created the model we can review it.
```
opt_model
```
## Markdown of output
If we copy the above text into a markdown cell you will see the implications of the varous models.
MIPModel:
MINIMIZE
6*$x_{1}$ + 3*$x_{2}$ + 0
SUBJECT TO
_C1: 2 $x_{1}$ + 4 $x_{2}$ >= 16
_C2: 4 $x_{1}$ + 3 $x_{2}$ >= 24
VARIABLES
0 <= $x_{1}$ Integer
0 <= $x_{2}$ Integer
## Solve
We now solve the system of equations with the solve command.
```
#Solve the program
opt_model.solve()
```
## Check the Status
Here are 5 status codes:
* **Not Solved**: Status prior to solving the problem.
* **Optimal**: An optimal solution has been found.
* **Infeasible**: There are no feasible solutions (e.g. if you set the constraints x <= 1 and x >=2).
* **Unbounded**: The constraints are not bounded, maximising the solution will tend towards infinity (e.g. if the only constraint was x >= 3).
* **Undefined**: The optimal solution may exist but may not have been found.
```
pl.LpStatus[opt_model.status]
for variable in opt_model.variables():
print(variable.name," = ", variable.varValue)
```
## Hurray!
We got the same answer as we did before.
## Exercise
Solve the LP problem for Beaver Creek Pottery using the maximization model type (`pl.LpMaximize`).
### Product mix problem - Beaver Creek Pottery Company
How many bowls and mugs should be produced to maximize profits given labor and materials constraints?
Product resource requirements and unit profit:
Decision Variables:
$x_{1}$ = number of bowls to produce per day
$x_{2}$ = number of mugs to produce per day
Profit (Z) Mazimization
Z = 40$x_{1}$ + 50$x_{2}$
Labor Constraint Check
1$x_{1}$ + 2$x_{2}$ <= 40
Clay (Physicial Resource) Constraint Check
4$x_{1}$ + 3$x_{2}$ <= 120
Negative Production Constaint Check
$x_{1}$ > 0
$x_{2}$ > 0
## Sensitivity Analysis
```
for name, c in opt_model.constraints.items():
print (name, ":", c, "\t", c.pi, "\t\t", c.slack)
```
| github_jupyter |
## Binary search
El método de búsqueda binaria funciona, únicamente, sobre conjunto de datos ordenados.
El método consiste en dividir el intervalo de búsqueda en dos partes y compara el elemento que ocupa la posición central del conjunto. Si el elemento del conjunto no es igual al elemento buscado se redefinen los extremos del intervalo, dependiendo de si el elemento central es mayor o menor que el elemento buscado, reduciendo así el espacio de búsqueda.
```
%pylab inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
def binary_iterative_search(intList, intValue):
lowIndex = 0
highIndex = len(intList)-1
while lowIndex != highIndex:
medium = (highIndex + lowIndex)//2
if intList[medium] == intValue:
return medium
else:
if intValue < intList[medium]:
highIndex = medium
else:
lowIndex = medium + 1
if intList[lowIndex] == intValue:
return lowIndex
else:
return -1
TAM_LIST = 2001
TAM_RANDOM_INT = 1000
#val = random.randint(1, TAM_RANDOM_INT)
val = 2000
cont = 0
l = []
for i in range(1, TAM_LIST, 1):
l.append(random.randint(1, TAM_RANDOM_INT))
l.sort()
res = binary_iterative_search(l, val)
if res == -1:
print('La llave', val,'no se encuentra en el conjunto')
else:
print('El valor', val,'se encuentra en la posición', res)
class Node:
def __init__(self, number, name, lastname, email, sex):
self.identifier = number
self.name = name
self.last_name = lastname
self.email = email
self.sex = sex[0]
def __str__(self):
return self.name + ": " + self.email
def bubble_sort_node(nodeList):
times = 0
cont = 0
comp = 0
aux = 0
while cont < len(nodeList)-1:
times += 1
comp = len(nodeList)-1
while comp > cont:
times += 1
if nodeList[comp-1].name > nodeList[comp].name:
aux = nodeList[comp-1]
nodeList[comp-1] = nodeList[comp]
nodeList[comp] = aux
comp = comp - 1
cont = cont + 1
return times
def binary_iterative_node_search(nodeList, nodeValue):
lowIndex = 0
highIndex = len(nodeList)-1
while lowIndex != highIndex:
medium = (highIndex + lowIndex)//2
if nodeList[medium].name == nodeValue.name:
return medium
else:
if nodeValue.name < nodeList[medium].name:
highIndex = medium
else:
lowIndex = medium + 1
if nodeList[lowIndex].name == nodeValue.name:
return lowIndex
else:
return -1
nodeList = []
file = open("DATA_10.csv", "r")
for line in file:
fields = line.split(",")
nodeList.append(Node(fields[0], fields[1], fields[2], fields[3], fields[4]))
print("List")
for node in nodeList:
print(node)
bubble_sort_node(nodeList)
print("\nBubble sort")
for node in nodeList:
print(node)
value = nodeList[random.randint(0, len(nodeList)-1)]
print("\nSearch ", value.name)
print(binary_iterative_node_search(nodeList, value))
def binary_iterative_node_search_graph(nodeList, nodeValue):
cont = 0
lowIndex = 0
highIndex = len(nodeList)-1
while lowIndex != highIndex:
cont += 1
medium = (highIndex + lowIndex)//2
if nodeList[medium].name == nodeValue.name:
return cont
else:
if nodeValue.name < nodeList[medium].name:
highIndex = medium
else:
lowIndex = medium + 1
cont += 1
if nodeList[lowIndex].name == nodeValue.name:
return cont
else:
return cont
TAM = 101
x = list(range(1,TAM,1))
y_omega = []
y_efedeene = []
y_omicron = []
L = []
for num in x:
iter = 1
file = open("DATA_10000.csv", "r")
L = []
for line in file:
fields = line.split(",")
L.append(Node(fields[0], fields[1], fields[2], fields[3], fields[4]))
if iter == num:
break
iter += 1
res = bubble_sort_node(L)
# average case
value = L[random.randint(0, len(L)-1)]
y_efedeene.append(binary_iterative_node_search_graph(L, value)+res)
# best case
value = L[(len(L)-1)//2]
y_omega.append(binary_iterative_node_search_graph(L, value)+res)
# worst case
value = Node(0, "zzzzzzzzzzzz", "zzzzzzzzzzzz", "zzzzzzzzzzzz", "zzzzzzzzzzzz")
y_omicron.append(binary_iterative_node_search_graph(L, value)+res)
fig, ax = plt.subplots(facecolor='w', edgecolor='k')
ax.plot(x, y_omega, marker="o",color="b", linestyle='None')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True)
ax.legend(["Binary iterative search"])
plt.title('Binary iterative search (best case)')
plt.show()
fig, ax = plt.subplots(facecolor='w', edgecolor='k')
ax.plot(x, y_efedeene, marker="o",color="b", linestyle='None')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True)
ax.legend(["Binary iterative search"])
plt.title('Binary iterative search (average case)')
plt.show()
fig, ax = plt.subplots(facecolor='w', edgecolor='k')
ax.plot(x, y_omicron, marker="o",color="b", linestyle='None')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True)
ax.legend(["Binary iterative search"])
plt.title('Binary iterative search (worst case)')
plt.show()
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.