code stringlengths 2.5k 150k | kind stringclasses 1 value |
|---|---|
# Distributional DQN
The final improvement to the DQN agent [1] is using distributions instead of simple average values for learning the q value function. This algorithm was presented by Bellemare et al. (2018) [2]. In their math heavy manuscript, the authors introduce the distributional Belman operator and show that it defines a contraction for the policy evaluation case. Bellemare et al. suggest that using distributions leads to a "significantly better behaved" [2] reinforcement learning and underline their theoretical findings with much better results on the Arcade Learning Environment [3]. Distributional DQN is also one of the improvements that seem to have one of the biggest impact in the Rainbow manuscript [4].
## Implementation
The distributional part of the algorithm is maybe the most influenced by the Deep Reinforcement Learning Hands-On book [5]. To get a good understanding of both, the distributional Bellman operator and how to use it in the DQN agent, I thoroughly studied the book's implementation as a starting point. I later implemented the distributional operator in a way that appears slightly more elegant to me, even though I still did not manage to get rid of the special treatment for the last step of an episode.
Some of the functionality for distributions was implemented in a DistributionalNetHelper class.
This way other neural network architectures can just inherit this functionality, even though at this point I only implemented DuelingDQN with distrbutions.
## Results
I start by comparing the Distributional DQN agent with two other agents. The different agents I compare are:
1. run024, which is the DQN agent with DDQN, Dueling DQN, n-step-reward and Prioritized Experience Replay. This agent so far had the most convincing results over the entire set of experiments.
2. run028, which uses all of the improvements mentioned above as wel as using Noisy Networks
3. run029 as run028 but using distributions instead of simple averages.
The values for the support in the distributional agent were chosen similar to the manuscript [2]; the number of atoms was 51 with values between -10 and 10. These values are not optimal for some of the experiments, as will become evident later.
On the radar plot, it appears that the distributional agent has the worst performance of all three agents. However, the barplot reveals that the DistributionalDQN agent shows good results on bandit, catch and catch_scale.


The problem that the DistributionalDQN agent faces is its use of a fixed support while the different experiments have very different reward scales. In the bandit experiment the final reward (and thus the q-value) varies between 0 and 1, while the cartpole experiment, for example, has q-values somewhere between 0 and 1001.
To investigate if using more appropriate vmin and vmax values yields better performance, I ran four of the experiments one more time with slightly different settings:
4. run030 uses the same settings as run029 but vmin = -1000 and vmax = 0, these settings were used for mountaincar and mountaincar_scale
5. run032 uses the same settings as run29 but vmin = 0, vmax = 1000, these settings were used for cartpole and cartpole_scale.
The results are shown below. It is apparent that the performance greatly improves when an appropriate scale is chosen.

In the scaled versions of the experiments, one can observe that the fine-tuned agent (run031) only performed well for the scale of 1.0, while the first set of parameters was better for smaller scales. This shows how strongly the choice of the support for the distribution influences the results.

## Discussion
The results above show that the DistributionalDQN agent can learn good policies very well if an appropriate scale for the support is chosen. However, this is also the obvious problem of the approach in the form presented in [2].
When the support is not chosen in an appropriate way, using a simple average value is probably more robust than using distributions.
In [2], distributions were used to improve the convergence properties of the DQN algorithms.
Using distributions has even more potential. One could use the distributions to improve action selection, for example in the case of multimodal distributions with very different (non-deterministic) rewards and probabilities.
Consider one action that certainly gives a reward of +1 and another action that gives a reward of +100 with a probability of 1\%. Even though both actions yield an average reward of 1 they certainly have very different risk profiles, and this could be assesed when the whole distributional information is available.
## References
The figures here were produced by the analysis Jupyter Notebook from [the BSuite code repository](https://github.com/deepmind/bsuite) and [6].
[1] Mnih, Volodymyr, et al. Human-level control through deep reinforcement learning. Nature, 2015.
[2] Bellemare, Marc G., Will Dabney, and Rémi Munos. "A distributional perspective on reinforcement learning." Proceedings of the 34th International Conference on Machine Learning-Volume 70. JMLR. org, 2017.
[3] Bellemare, Marc G., et al. "The arcade learning environment: An evaluation platform for general agents." Journal of Artificial Intelligence Research 47 (2013): 253-279.
[4] Hessel, Matteo, et al. Rainbow: Combining improvements in deep reinforcement learning. In: Thirty-Second AAAI Conference on Artificial Intelligence. 2018.
[5] Lapan, Maxim. Deep Reinforcement Learning Hands-On, Packt Publishing Ltd, 2018.
| github_jupyter |
# Regularization
Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that **overfitting can be a serious problem**, if the training dataset is not big enough. Sure it does well on the training set, but the learned network **doesn't generalize to new examples** that it has never seen!
**You will learn to:** Use regularization in your deep learning models.
Let's first import the packages you are going to use.
```
# import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
import sklearn.datasets
import scipy.io
from testCases import *
%matplotlib inline
plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
```
**Problem Statement**: You have just been hired as an AI expert by the French Football Corporation. They would like you to recommend positions where France's goal keeper should kick the ball so that the French team's players can then hit it with their head.
<img src="images/field_kiank.png" style="width:600px;height:350px;">
<caption><center> <u> **Figure 1** </u>: **Football field**<br> The goal keeper kicks the ball in the air, the players of each team are fighting to hit the ball with their head </center></caption>
They give you the following 2D dataset from France's past 10 games.
```
train_X, train_Y, test_X, test_Y = load_2D_dataset()
```
Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head after the French goal keeper has shot the ball from the left side of the football field.
- If the dot is blue, it means the French player managed to hit the ball with his/her head
- If the dot is red, it means the other team's player hit the ball with their head
**Your goal**: Use a deep learning model to find the positions on the field where the goalkeeper should kick the ball.
**Analysis of the dataset**: This dataset is a little noisy, but it looks like a diagonal line separating the upper left half (blue) from the lower right half (red) would work well.
You will first try a non-regularized model. Then you'll learn how to regularize it and decide which model you will choose to solve the French Football Corporation's problem.
## 1 - Non-regularized model
You will use the following neural network (already implemented for you below). This model can be used:
- in *regularization mode* -- by setting the `lambd` input to a non-zero value. We use "`lambd`" instead of "`lambda`" because "`lambda`" is a reserved keyword in Python.
- in *dropout mode* -- by setting the `keep_prob` to a value less than one
You will first try the model without any regularization. Then, you will implement:
- *L2 regularization* -- functions: "`compute_cost_with_regularization()`" and "`backward_propagation_with_regularization()`"
- *Dropout* -- functions: "`forward_propagation_with_dropout()`" and "`backward_propagation_with_dropout()`"
In each part, you will run this model with the correct inputs so that it calls the functions you've implemented. Take a look at the code below to familiarize yourself with the model.
```
def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1):
"""
Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (output size, number of examples)
learning_rate -- learning rate of the optimization
num_iterations -- number of iterations of the optimization loop
print_cost -- If True, print the cost every 10000 iterations
lambd -- regularization hyperparameter, scalar
keep_prob - probability of keeping a neuron active during drop-out, scalar.
Returns:
parameters -- parameters learned by the model. They can then be used to predict.
"""
grads = {}
costs = [] # to keep track of the cost
m = X.shape[1] # number of examples
layers_dims = [X.shape[0], 20, 3, 1]
# Initialize parameters dictionary.
parameters = initialize_parameters(layers_dims)
# Loop (gradient descent)
for i in range(0, num_iterations):
# Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.
if keep_prob == 1:
a3, cache = forward_propagation(X, parameters)
elif keep_prob < 1:
a3, cache = forward_propagation_with_dropout(X, parameters, keep_prob)
# Cost function
if lambd == 0:
cost = compute_cost(a3, Y)
else:
cost = compute_cost_with_regularization(a3, Y, parameters, lambd)
# Backward propagation.
assert(lambd==0 or keep_prob==1) # it is possible to use both L2 regularization and dropout,
# but this assignment will only explore one at a time
if lambd == 0 and keep_prob == 1:
grads = backward_propagation(X, Y, cache)
elif lambd != 0:
grads = backward_propagation_with_regularization(X, Y, cache, lambd)
elif keep_prob < 1:
grads = backward_propagation_with_dropout(X, Y, cache, keep_prob)
# Update parameters.
parameters = update_parameters(parameters, grads, learning_rate)
# Print the loss every 10000 iterations
if print_cost and i % 10000 == 0:
print("Cost after iteration {}: {}".format(i, cost))
if print_cost and i % 1000 == 0:
costs.append(cost)
# plot the cost
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (x1,000)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
```
Let's train the model without any regularization, and observe the accuracy on the train/test sets.
```
parameters = model(train_X, train_Y)
print ("On the training set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)
```
The train accuracy is 94.8% while the test accuracy is 91.5%. This is the **baseline model** (you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model.
```
plt.title("Model without regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
```
The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting.
## 2 - L2 Regularization
The standard way to avoid overfitting is called **L2 regularization**. It consists of appropriately modifying your cost function, from:
$$J = -\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} \tag{1}$$
To:
$$J_{regularized} = \small \underbrace{-\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} }_\text{cross-entropy cost} + \underbrace{\frac{1}{m} \frac{\lambda}{2} \sum\limits_l\sum\limits_k\sum\limits_j W_{k,j}^{[l]2} }_\text{L2 regularization cost} \tag{2}$$
Let's modify your cost and observe the consequences.
**Exercise**: Implement `compute_cost_with_regularization()` which computes the cost given by formula (2). To calculate $\sum\limits_k\sum\limits_j W_{k,j}^{[l]2}$ , use :
```python
np.sum(np.square(Wl))
```
Note that you have to do this for $W^{[1]}$, $W^{[2]}$ and $W^{[3]}$, then sum the three terms and multiply by $ \frac{1}{m} \frac{\lambda}{2} $.
```
# GRADED FUNCTION: compute_cost_with_regularization
def compute_cost_with_regularization(A3, Y, parameters, lambd):
"""
Implement the cost function with L2 regularization. See formula (2) above.
Arguments:
A3 -- post-activation, output of forward propagation, of shape (output size, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
parameters -- python dictionary containing parameters of the model
Returns:
cost - value of the regularized loss function (formula (2))
"""
m = Y.shape[1]
W1 = parameters["W1"]
W2 = parameters["W2"]
W3 = parameters["W3"]
cross_entropy_cost = compute_cost(A3, Y) # This gives you the cross-entropy part of the cost
### START CODE HERE ### (approx. 1 line)
L2_regularization_cost = None
### END CODER HERE ###
cost = cross_entropy_cost + L2_regularization_cost
return cost
A3, Y_assess, parameters = compute_cost_with_regularization_test_case()
print("cost = " + str(compute_cost_with_regularization(A3, Y_assess, parameters, lambd = 0.1)))
```
**Expected Output**:
<table>
<tr>
<td>
**cost**
</td>
<td>
1.78648594516
</td>
</tr>
</table>
Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost.
**Exercise**: Implement the changes needed in backward propagation to take into account regularization. The changes only concern dW1, dW2 and dW3. For each, you have to add the regularization term's gradient ($\frac{d}{dW} ( \frac{1}{2}\frac{\lambda}{m} W^2) = \frac{\lambda}{m} W$).
```
# GRADED FUNCTION: backward_propagation_with_regularization
def backward_propagation_with_regularization(X, Y, cache, lambd):
"""
Implements the backward propagation of our baseline model to which we added an L2 regularization.
Arguments:
X -- input dataset, of shape (input size, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
cache -- cache output from forward_propagation()
lambd -- regularization hyperparameter, scalar
Returns:
gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
"""
m = X.shape[1]
(Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache
dZ3 = A3 - Y
### START CODE HERE ### (approx. 1 line)
dW3 = 1./m * np.dot(dZ3, A2.T) + None
### END CODE HERE ###
db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)
dA2 = np.dot(W3.T, dZ3)
dZ2 = np.multiply(dA2, np.int64(A2 > 0))
### START CODE HERE ### (approx. 1 line)
dW2 = 1./m * np.dot(dZ2, A1.T) + None
### END CODE HERE ###
db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)
dA1 = np.dot(W2.T, dZ2)
dZ1 = np.multiply(dA1, np.int64(A1 > 0))
### START CODE HERE ### (approx. 1 line)
dW1 = 1./m * np.dot(dZ1, X.T) + None
### END CODE HERE ###
db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)
gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2,
"dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1,
"dZ1": dZ1, "dW1": dW1, "db1": db1}
return gradients
X_assess, Y_assess, cache = backward_propagation_with_regularization_test_case()
grads = backward_propagation_with_regularization(X_assess, Y_assess, cache, lambd = 0.7)
print ("dW1 = "+ str(grads["dW1"]))
print ("dW2 = "+ str(grads["dW2"]))
print ("dW3 = "+ str(grads["dW3"]))
```
**Expected Output**:
<table>
<tr>
<td>
**dW1**
</td>
<td>
[[-0.25604646 0.12298827 -0.28297129]
[-0.17706303 0.34536094 -0.4410571 ]]
</td>
</tr>
<tr>
<td>
**dW2**
</td>
<td>
[[ 0.79276486 0.85133918]
[-0.0957219 -0.01720463]
[-0.13100772 -0.03750433]]
</td>
</tr>
<tr>
<td>
**dW3**
</td>
<td>
[[-1.77691347 -0.11832879 -0.09397446]]
</td>
</tr>
</table>
Let's now run the model with L2 regularization $(\lambda = 0.7)$. The `model()` function will call:
- `compute_cost_with_regularization` instead of `compute_cost`
- `backward_propagation_with_regularization` instead of `backward_propagation`
```
parameters = model(train_X, train_Y, lambd = 0.7)
print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)
```
Congrats, the test set accuracy increased to 93%. You have saved the French football team!
You are not overfitting the training data anymore. Let's plot the decision boundary.
```
plt.title("Model with L2-regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
```
**Observations**:
- The value of $\lambda$ is a hyperparameter that you can tune using a dev set.
- L2 regularization makes your decision boundary smoother. If $\lambda$ is too large, it is also possible to "oversmooth", resulting in a model with high bias.
**What is L2-regularization actually doing?**:
L2-regularization relies on the assumption that a model with small weights is simpler than a model with large weights. Thus, by penalizing the square values of the weights in the cost function you drive all the weights to smaller values. It becomes too costly for the cost to have large weights! This leads to a smoother model in which the output changes more slowly as the input changes.
<font color='blue'>
**What you should remember** -- the implications of L2-regularization on:
- The cost computation:
- A regularization term is added to the cost
- The backpropagation function:
- There are extra terms in the gradients with respect to weight matrices
- Weights end up smaller ("weight decay"):
- Weights are pushed to smaller values.
## 3 - Dropout
Finally, **dropout** is a widely used regularization technique that is specific to deep learning.
**It randomly shuts down some neurons in each iteration.** Watch these two videos to see what this means!
<!--
To understand drop-out, consider this conversation with a friend:
- Friend: "Why do you need all these neurons to train your network and classify images?".
- You: "Because each neuron contains a weight and can learn specific features/details/shape of an image. The more neurons I have, the more featurse my model learns!"
- Friend: "I see, but are you sure that your neurons are learning different features and not all the same features?"
- You: "Good point... Neurons in the same layer actually don't talk to each other. It should be definitly possible that they learn the same image features/shapes/forms/details... which would be redundant. There should be a solution."
!-->
<center>
<video width="620" height="440" src="images/dropout1_kiank.mp4" type="video/mp4" controls>
</video>
</center>
<br>
<caption><center> <u> Figure 2 </u>: Drop-out on the second hidden layer. <br> At each iteration, you shut down (= set to zero) each neuron of a layer with probability $1 - keep\_prob$ or keep it with probability $keep\_prob$ (50% here). The dropped neurons don't contribute to the training in both the forward and backward propagations of the iteration. </center></caption>
<center>
<video width="620" height="440" src="images/dropout2_kiank.mp4" type="video/mp4" controls>
</video>
</center>
<caption><center> <u> Figure 3 </u>: Drop-out on the first and third hidden layers. <br> $1^{st}$ layer: we shut down on average 40% of the neurons. $3^{rd}$ layer: we shut down on average 20% of the neurons. </center></caption>
When you shut some neurons down, you actually modify your model. The idea behind drop-out is that at each iteration, you train a different model that uses only a subset of your neurons. With dropout, your neurons thus become less sensitive to the activation of one other specific neuron, because that other neuron might be shut down at any time.
### 3.1 - Forward propagation with dropout
**Exercise**: Implement the forward propagation with dropout. You are using a 3 layer neural network, and will add dropout to the first and second hidden layers. We will not apply dropout to the input layer or output layer.
**Instructions**:
You would like to shut down some neurons in the first and second layers. To do that, you are going to carry out 4 Steps:
1. In lecture, we dicussed creating a variable $d^{[1]}$ with the same shape as $a^{[1]}$ using `np.random.rand()` to randomly get numbers between 0 and 1. Here, you will use a vectorized implementation, so create a random matrix $D^{[1]} = [d^{[1](1)} d^{[1](2)} ... d^{[1](m)}] $ of the same dimension as $A^{[1]}$.
2. Set each entry of $D^{[1]}$ to be 0 with probability (`1-keep_prob`) or 1 with probability (`keep_prob`), by thresholding values in $D^{[1]}$ appropriately. Hint: to set all the entries of a matrix X to 0 (if entry is less than 0.5) or 1 (if entry is more than 0.5) you would do: `X = (X < 0.5)`. Note that 0 and 1 are respectively equivalent to False and True.
3. Set $A^{[1]}$ to $A^{[1]} * D^{[1]}$. (You are shutting down some neurons). You can think of $D^{[1]}$ as a mask, so that when it is multiplied with another matrix, it shuts down some of the values.
4. Divide $A^{[1]}$ by `keep_prob`. By doing this you are assuring that the result of the cost will still have the same expected value as without drop-out. (This technique is also called inverted dropout.)
```
# GRADED FUNCTION: forward_propagation_with_dropout
def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):
"""
Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
Arguments:
X -- input dataset, of shape (2, number of examples)
parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":
W1 -- weight matrix of shape (20, 2)
b1 -- bias vector of shape (20, 1)
W2 -- weight matrix of shape (3, 20)
b2 -- bias vector of shape (3, 1)
W3 -- weight matrix of shape (1, 3)
b3 -- bias vector of shape (1, 1)
keep_prob - probability of keeping a neuron active during drop-out, scalar
Returns:
A3 -- last activation value, output of the forward propagation, of shape (1,1)
cache -- tuple, information stored for computing the backward propagation
"""
np.random.seed(1)
# retrieve parameters
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
W3 = parameters["W3"]
b3 = parameters["b3"]
# LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
Z1 = np.dot(W1, X) + b1
A1 = relu(Z1)
### START CODE HERE ### (approx. 4 lines) # Steps 1-4 below correspond to the Steps 1-4 described above.
D1 = None # Step 1: initialize matrix D1 = np.random.rand(..., ...)
D1 = None # Step 2: convert entries of D1 to 0 or 1 (using keep_prob as the threshold)
A1 = None # Step 3: shut down some neurons of A1
A1 = None # Step 4: scale the value of neurons that haven't been shut down
### END CODE HERE ###
Z2 = np.dot(W2, A1) + b2
A2 = relu(Z2)
### START CODE HERE ### (approx. 4 lines)
D2 = None # Step 1: initialize matrix D2 = np.random.rand(..., ...)
D2 = None # Step 2: convert entries of D2 to 0 or 1 (using keep_prob as the threshold)
A2 = None # Step 3: shut down some neurons of A2
A2 = None # Step 4: scale the value of neurons that haven't been shut down
### END CODE HERE ###
Z3 = np.dot(W3, A2) + b3
A3 = sigmoid(Z3)
cache = (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3)
return A3, cache
X_assess, parameters = forward_propagation_with_dropout_test_case()
A3, cache = forward_propagation_with_dropout(X_assess, parameters, keep_prob = 0.7)
print ("A3 = " + str(A3))
```
**Expected Output**:
<table>
<tr>
<td>
**A3**
</td>
<td>
[[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
</td>
</tr>
</table>
### 3.2 - Backward propagation with dropout
**Exercise**: Implement the backward propagation with dropout. As before, you are training a 3 layer network. Add dropout to the first and second hidden layers, using the masks $D^{[1]}$ and $D^{[2]}$ stored in the cache.
**Instruction**:
Backpropagation with dropout is actually quite easy. You will have to carry out 2 Steps:
1. You had previously shut down some neurons during forward propagation, by applying a mask $D^{[1]}$ to `A1`. In backpropagation, you will have to shut down the same neurons, by reapplying the same mask $D^{[1]}$ to `dA1`.
2. During forward propagation, you had divided `A1` by `keep_prob`. In backpropagation, you'll therefore have to divide `dA1` by `keep_prob` again (the calculus interpretation is that if $A^{[1]}$ is scaled by `keep_prob`, then its derivative $dA^{[1]}$ is also scaled by the same `keep_prob`).
```
# GRADED FUNCTION: backward_propagation_with_dropout
def backward_propagation_with_dropout(X, Y, cache, keep_prob):
"""
Implements the backward propagation of our baseline model to which we added dropout.
Arguments:
X -- input dataset, of shape (2, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
cache -- cache output from forward_propagation_with_dropout()
keep_prob - probability of keeping a neuron active during drop-out, scalar
Returns:
gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
"""
m = X.shape[1]
(Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3) = cache
dZ3 = A3 - Y
dW3 = 1./m * np.dot(dZ3, A2.T)
db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)
dA2 = np.dot(W3.T, dZ3)
### START CODE HERE ### (≈ 2 lines of code)
dA2 = None # Step 1: Apply mask D2 to shut down the same neurons as during the forward propagation
dA2 = None # Step 2: Scale the value of neurons that haven't been shut down
### END CODE HERE ###
dZ2 = np.multiply(dA2, np.int64(A2 > 0))
dW2 = 1./m * np.dot(dZ2, A1.T)
db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)
dA1 = np.dot(W2.T, dZ2)
### START CODE HERE ### (≈ 2 lines of code)
dA1 = None # Step 1: Apply mask D1 to shut down the same neurons as during the forward propagation
dA1 = None # Step 2: Scale the value of neurons that haven't been shut down
### END CODE HERE ###
dZ1 = np.multiply(dA1, np.int64(A1 > 0))
dW1 = 1./m * np.dot(dZ1, X.T)
db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)
gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2,
"dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1,
"dZ1": dZ1, "dW1": dW1, "db1": db1}
return gradients
X_assess, Y_assess, cache = backward_propagation_with_dropout_test_case()
gradients = backward_propagation_with_dropout(X_assess, Y_assess, cache, keep_prob = 0.8)
print ("dA1 = " + str(gradients["dA1"]))
print ("dA2 = " + str(gradients["dA2"]))
```
**Expected Output**:
<table>
<tr>
<td>
**dA1**
</td>
<td>
[[ 0.36544439 0. -0.00188233 0. -0.17408748]
[ 0.65515713 0. -0.00337459 0. -0. ]]
</td>
</tr>
<tr>
<td>
**dA2**
</td>
<td>
[[ 0.58180856 0. -0.00299679 0. -0.27715731]
[ 0. 0.53159854 -0. 0.53159854 -0.34089673]
[ 0. 0. -0.00292733 0. -0. ]]
</td>
</tr>
</table>
Let's now run the model with dropout (`keep_prob = 0.86`). It means at every iteration you shut down each neurons of layer 1 and 2 with 24% probability. The function `model()` will now call:
- `forward_propagation_with_dropout` instead of `forward_propagation`.
- `backward_propagation_with_dropout` instead of `backward_propagation`.
```
parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3)
print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)
```
Dropout works great! The test accuracy has increased again (to 95%)! Your model is not overfitting the training set and does a great job on the test set. The French football team will be forever grateful to you!
Run the code below to plot the decision boundary.
```
plt.title("Model with dropout")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
```
**Note**:
- A **common mistake** when using dropout is to use it both in training and testing. You should use dropout (randomly eliminate nodes) only in training.
- Deep learning frameworks like [tensorflow](https://www.tensorflow.org/api_docs/python/tf/nn/dropout), [PaddlePaddle](http://doc.paddlepaddle.org/release_doc/0.9.0/doc/ui/api/trainer_config_helpers/attrs.html), [keras](https://keras.io/layers/core/#dropout) or [caffe](http://caffe.berkeleyvision.org/tutorial/layers/dropout.html) come with a dropout layer implementation. Don't stress - you will soon learn some of these frameworks.
<font color='blue'>
**What you should remember about dropout:**
- Dropout is a regularization technique.
- You only use dropout during training. Don't use dropout (randomly eliminate nodes) during test time.
- Apply dropout both during forward and backward propagation.
- During training time, divide each dropout layer by keep_prob to keep the same expected value for the activations. For example, if keep_prob is 0.5, then we will on average shut down half the nodes, so the output will be scaled by 0.5 since only the remaining half are contributing to the solution. Dividing by 0.5 is equivalent to multiplying by 2. Hence, the output now has the same expected value. You can check that this works even when keep_prob is other values than 0.5.
## 4 - Conclusions
**Here are the results of our three models**:
<table>
<tr>
<td>
**model**
</td>
<td>
**train accuracy**
</td>
<td>
**test accuracy**
</td>
</tr>
<td>
3-layer NN without regularization
</td>
<td>
95%
</td>
<td>
91.5%
</td>
<tr>
<td>
3-layer NN with L2-regularization
</td>
<td>
94%
</td>
<td>
93%
</td>
</tr>
<tr>
<td>
3-layer NN with dropout
</td>
<td>
93%
</td>
<td>
95%
</td>
</tr>
</table>
Note that regularization hurts training set performance! This is because it limits the ability of the network to overfit to the training set. But since it ultimately gives better test accuracy, it is helping your system.
Congratulations for finishing this assignment! And also for revolutionizing French football. :-)
<font color='blue'>
**What we want you to remember from this notebook**:
- Regularization will help you reduce overfitting.
- Regularization will drive your weights to lower values.
- L2 regularization and Dropout are two very effective regularization techniques.
| github_jupyter |
# Style Transfer
In this notebook we will implement the style transfer technique from ["Image Style Transfer Using Convolutional Neural Networks" (Gatys et al., CVPR 2015)](http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Gatys_Image_Style_Transfer_CVPR_2016_paper.pdf).
The general idea is to take two images, and produce a new image that reflects the content of one but the artistic "style" of the other. We will do this by first formulating a loss function that matches the content and style of each respective image in the feature space of a deep network, and then performing gradient descent on the pixels of the image itself.
The deep network we use as a feature extractor is [SqueezeNet](https://arxiv.org/abs/1602.07360), a small model that has been trained on ImageNet. You could use any network, but we chose SqueezeNet here for its small size and efficiency.
Here's an example of the images you'll be able to produce by the end of this notebook:

## Setup
```
import os
import numpy as np
from scipy.misc import imread, imresize
import matplotlib.pyplot as plt
import tensorflow as tf
# Helper functions to deal with image preprocessing
from cs231n.image_utils import load_image, preprocess_image, deprocess_image
from cs231n.classifiers.squeezenet import SqueezeNet
%matplotlib inline
%load_ext autoreload
%autoreload 2
def rel_error(x,y):
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
# Older versions of scipy.misc.imresize yield different results
# from newer versions, so we check to make sure scipy is up to date.
def check_scipy():
import scipy
version = scipy.__version__.split('.')
if int(version[0]) < 1:
assert int(version[1]) >= 16, "You must install SciPy >= 0.16.0 to complete this notebook."
check_scipy()
```
Load the pretrained SqueezeNet model. This model has been ported from PyTorch, see `cs231n/classifiers/squeezenet.py` for the model architecture.
To use SqueezeNet, you will need to first **download the weights** by descending into the `cs231n/datasets` directory and running `get_squeezenet_tf.sh` . Note that if you ran `get_assignment3_data.sh` then SqueezeNet will already be downloaded.
```
# Load pretrained SqueezeNet model
SAVE_PATH = 'cs231n/datasets/squeezenet.ckpt'
if not os.path.exists(SAVE_PATH + ".index"):
raise ValueError("You need to download SqueezeNet!")
model=SqueezeNet()
model.load_weights(SAVE_PATH)
model.trainable=False
# Load data for testing
content_img_test = preprocess_image(load_image('styles/tubingen.jpg', size=192))[None]
style_img_test = preprocess_image(load_image('styles/starry_night.jpg', size=192))[None]
answers = np.load('style-transfer-checks-tf.npz')
```
## Computing Loss
We're going to compute the three components of our loss function now. The loss function is a weighted sum of three terms: content loss + style loss + total variation loss. You'll fill in the functions that compute these weighted terms below.
## Content loss
We can generate an image that reflects the content of one image and the style of another by incorporating both in our loss function. We want to penalize deviations from the content of the content image and deviations from the style of the style image. We can then use this hybrid loss function to perform gradient descent **not on the parameters** of the model, but instead **on the pixel values** of our original image.
Let's first write the content loss function. Content loss measures how much the feature map of the generated image differs from the feature map of the source image. We only care about the content representation of one layer of the network (say, layer $\ell$), that has feature maps $A^\ell \in \mathbb{R}^{1 \times H_\ell \times W_\ell \times C_\ell}$. $C_\ell$ is the number of filters/channels in layer $\ell$, $H_\ell$ and $W_\ell$ are the height and width. We will work with reshaped versions of these feature maps that combine all spatial positions into one dimension. Let $F^\ell \in \mathbb{R}^{M_\ell \times C_\ell}$ be the feature map for the current image and $P^\ell \in \mathbb{R}^{M_\ell \times C_\ell}$ be the feature map for the content source image where $M_\ell=H_\ell\times W_\ell$ is the number of elements in each feature map. Each row of $F^\ell$ or $P^\ell$ represents the vectorized activations of a particular filter, convolved over all positions of the image. Finally, let $w_c$ be the weight of the content loss term in the loss function.
Then the content loss is given by:
$L_c = w_c \times \sum_{i,j} (F_{ij}^{\ell} - P_{ij}^{\ell})^2$
```
def content_loss(content_weight, content_current, content_original):
"""
Compute the content loss for style transfer.
Inputs:
- content_weight: scalar constant we multiply the content_loss by.
- content_current: features of the current image, Tensor with shape [1, height, width, channels]
- content_target: features of the content image, Tensor with shape [1, height, width, channels]
Returns:
- scalar content loss
"""
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# We provide this helper code which takes an image, a model (cnn), and returns a list of
# feature maps, one per layer.
def extract_features(x, cnn):
"""
Use the CNN to extract features from the input image x.
Inputs:
- x: A Tensor of shape (N, H, W, C) holding a minibatch of images that
will be fed to the CNN.
- cnn: A Tensorflow model that we will use to extract features.
Returns:
- features: A list of feature for the input images x extracted using the cnn model.
features[i] is a Tensor of shape (N, H_i, W_i, C_i); recall that features
from different layers of the network may have different numbers of channels (C_i) and
spatial dimensions (H_i, W_i).
"""
features = []
prev_feat = x
for i, layer in enumerate(cnn.net.layers[:-2]):
next_feat = layer(prev_feat)
features.append(next_feat)
prev_feat = next_feat
return features
```
Test your content loss. The error should be less than 1e-8.
```
def content_loss_test(correct):
content_layer = 2
content_weight = 6e-2
c_feats = extract_features(content_img_test, model)[content_layer]
bad_img = tf.zeros(content_img_test.shape)
feats = extract_features(bad_img, model)[content_layer]
student_output = content_loss(content_weight, c_feats, feats)
error = rel_error(correct, student_output)
print('Maximum error is {:.3f}'.format(error))
content_loss_test(answers['cl_out'])
```
## Style loss
Now we can tackle the style loss. For a given layer $\ell$, the style loss is defined as follows:
First, compute the Gram matrix G which represents the correlations between the responses of each filter, where F is as above. The Gram matrix is an approximation to the covariance matrix -- we want the activation statistics of our generated image to match the activation statistics of our style image, and matching the (approximate) covariance is one way to do that. There are a variety of ways you could do this, but the Gram matrix is nice because it's easy to compute and in practice shows good results.
Given a feature map $F^\ell$ of shape $(M_\ell, C_\ell)$, the Gram matrix has shape $(C_\ell, C_\ell)$ and its elements are given by:
$$G_{ij}^\ell = \sum_k F^{\ell}_{ki} F^{\ell}_{kj}$$
Assuming $G^\ell$ is the Gram matrix from the feature map of the current image, $A^\ell$ is the Gram Matrix from the feature map of the source style image, and $w_\ell$ a scalar weight term, then the style loss for the layer $\ell$ is simply the weighted Euclidean distance between the two Gram matrices:
$$L_s^\ell = w_\ell \sum_{i, j} \left(G^\ell_{ij} - A^\ell_{ij}\right)^2$$
In practice we usually compute the style loss at a set of layers $\mathcal{L}$ rather than just a single layer $\ell$; then the total style loss is the sum of style losses at each layer:
$$L_s = \sum_{\ell \in \mathcal{L}} L_s^\ell$$
Begin by implementing the Gram matrix computation below:
```
def gram_matrix(features, normalize=True):
"""
Compute the Gram matrix from features.
Inputs:
- features: Tensor of shape (1, H, W, C) giving features for
a single image.
- normalize: optional, whether to normalize the Gram matrix
If True, divide the Gram matrix by the number of neurons (H * W * C)
Returns:
- gram: Tensor of shape (C, C) giving the (optionally normalized)
Gram matrices for the input image.
"""
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
```
Test your Gram matrix code. You should see errors less than 0.001.
```
def gram_matrix_test(correct):
gram = gram_matrix(extract_features(style_img_test, model)[4]) ### 4 instead of 5 - second MaxPooling layer
error = rel_error(correct, gram)
print('Maximum error is {:.3f}'.format(error))
gram_matrix_test(answers['gm_out'])
```
Next, implement the style loss:
```
def style_loss(feats, style_layers, style_targets, style_weights):
"""
Computes the style loss at a set of layers.
Inputs:
- feats: list of the features at every layer of the current image, as produced by
the extract_features function.
- style_layers: List of layer indices into feats giving the layers to include in the
style loss.
- style_targets: List of the same length as style_layers, where style_targets[i] is
a Tensor giving the Gram matrix of the source style image computed at
layer style_layers[i].
- style_weights: List of the same length as style_layers, where style_weights[i]
is a scalar giving the weight for the style loss at layer style_layers[i].
Returns:
- style_loss: A Tensor containing the scalar style loss.
"""
# Hint: you can do this with one for loop over the style layers, and should
# not be short code (~5 lines). You will need to use your gram_matrix function.
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
```
Test your style loss implementation. The error should be less than 0.001.
```
def style_loss_test(correct):
style_layers = [0, 3, 5, 6]
style_weights = [300000, 1000, 15, 3]
c_feats = extract_features(content_img_test, model)
feats = extract_features(style_img_test, model)
style_targets = []
for idx in style_layers:
style_targets.append(gram_matrix(feats[idx]))
s_loss = style_loss(c_feats, style_layers, style_targets, style_weights)
error = rel_error(correct, s_loss)
print('Error is {:.3f}'.format(error))
style_loss_test(answers['sl_out'])
```
## Total-variation regularization
It turns out that it's helpful to also encourage smoothness in the image. We can do this by adding another term to our loss that penalizes wiggles or "total variation" in the pixel values.
You can compute the "total variation" as the sum of the squares of differences in the pixel values for all pairs of pixels that are next to each other (horizontally or vertically). Here we sum the total-variation regualarization for each of the 3 input channels (RGB), and weight the total summed loss by the total variation weight, $w_t$:
$L_{tv} = w_t \times \left(\sum_{c=1}^3\sum_{i=1}^{H-1}\sum_{j=1}^{W} (x_{i+1,j,c} - x_{i,j,c})^2 + \sum_{c=1}^3\sum_{i=1}^{H}\sum_{j=1}^{W - 1} (x_{i,j+1,c} - x_{i,j,c})^2\right)$
In the next cell, fill in the definition for the TV loss term. To receive full credit, your implementation should not have any loops.
```
def tv_loss(img, tv_weight):
"""
Compute total variation loss.
Inputs:
- img: Tensor of shape (1, H, W, 3) holding an input image.
- tv_weight: Scalar giving the weight w_t to use for the TV loss.
Returns:
- loss: Tensor holding a scalar giving the total variation loss
for img weighted by tv_weight.
"""
# Your implementation should be vectorized and not require any loops!
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
```
Test your TV loss implementation. Error should be less than 0.001.
```
def tv_loss_test(correct):
tv_weight = 2e-2
t_loss = tv_loss(content_img_test, tv_weight)
error = rel_error(correct, t_loss)
print('Error is {:.3f}'.format(error))
tv_loss_test(answers['tv_out'])
```
## Style Transfer
Lets put it all together and make some beautiful images! The `style_transfer` function below combines all the losses you coded up above and optimizes for an image that minimizes the total loss.
```
def style_transfer(content_image, style_image, image_size, style_size, content_layer, content_weight,
style_layers, style_weights, tv_weight, init_random = False):
"""Run style transfer!
Inputs:
- content_image: filename of content image
- style_image: filename of style image
- image_size: size of smallest image dimension (used for content loss and generated image)
- style_size: size of smallest style image dimension
- content_layer: layer to use for content loss
- content_weight: weighting on content loss
- style_layers: list of layers to use for style loss
- style_weights: list of weights to use for each layer in style_layers
- tv_weight: weight of total variation regularization term
- init_random: initialize the starting image to uniform random noise
"""
# Extract features from the content image
content_img = preprocess_image(load_image(content_image, size=image_size))
feats = extract_features(content_img[None], model)
content_target = feats[content_layer]
# Extract features from the style image
style_img = preprocess_image(load_image(style_image, size=style_size))
s_feats = extract_features(style_img[None], model)
style_targets = []
# Compute list of TensorFlow Gram matrices
for idx in style_layers:
style_targets.append(gram_matrix(s_feats[idx]))
# Set up optimization hyperparameters
initial_lr = 3.0
decayed_lr = 0.1
decay_lr_at = 180
max_iter = 200
step = tf.Variable(0, trainable=False)
boundaries = [decay_lr_at]
values = [initial_lr, decayed_lr]
learning_rate_fn = tf.keras.optimizers.schedules.PiecewiseConstantDecay(boundaries, values)
# Later, whenever we perform an optimization step, we pass in the step.
learning_rate = learning_rate_fn(step)
optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
# Initialize the generated image and optimization variables
f, axarr = plt.subplots(1,2)
axarr[0].axis('off')
axarr[1].axis('off')
axarr[0].set_title('Content Source Img.')
axarr[1].set_title('Style Source Img.')
axarr[0].imshow(deprocess_image(content_img))
axarr[1].imshow(deprocess_image(style_img))
plt.show()
plt.figure()
# Initialize generated image to content image
if init_random:
initializer = tf.random_uniform_initializer(0, 1)
img = initializer(shape=content_img[None].shape)
img_var = tf.Variable(img)
print("Intializing randomly.")
else:
img_var = tf.Variable(content_img[None])
print("Initializing with content image.")
for t in range(max_iter):
with tf.GradientTape() as tape:
tape.watch(img_var)
feats = extract_features(img_var, model)
# Compute loss
c_loss = content_loss(content_weight, feats[content_layer], content_target)
s_loss = style_loss(feats, style_layers, style_targets, style_weights)
t_loss = tv_loss(img_var, tv_weight)
loss = c_loss + s_loss + t_loss
# Compute gradient
grad = tape.gradient(loss, img_var)
optimizer.apply_gradients([(grad, img_var)])
img_var.assign(tf.clip_by_value(img_var, -1.5, 1.5))
if t % 100 == 0:
print('Iteration {}'.format(t))
plt.imshow(deprocess_image(img_var[0].numpy(), rescale=True))
plt.axis('off')
plt.show()
print('Iteration {}'.format(t))
plt.imshow(deprocess_image(img_var[0].numpy(), rescale=True))
plt.axis('off')
plt.show()
```
## Generate some pretty pictures!
Try out `style_transfer` on the three different parameter sets below. Make sure to run all three cells. Feel free to add your own, but make sure to include the results of style transfer on the third parameter set (starry night) in your submitted notebook.
* The `content_image` is the filename of content image.
* The `style_image` is the filename of style image.
* The `image_size` is the size of smallest image dimension of the content image (used for content loss and generated image).
* The `style_size` is the size of smallest style image dimension.
* The `content_layer` specifies which layer to use for content loss.
* The `content_weight` gives weighting on content loss in the overall loss function. Increasing the value of this parameter will make the final image look more realistic (closer to the original content).
* `style_layers` specifies a list of which layers to use for style loss.
* `style_weights` specifies a list of weights to use for each layer in style_layers (each of which will contribute a term to the overall style loss). We generally use higher weights for the earlier style layers because they describe more local/smaller scale features, which are more important to texture than features over larger receptive fields. In general, increasing these weights will make the resulting image look less like the original content and more distorted towards the appearance of the style image.
* `tv_weight` specifies the weighting of total variation regularization in the overall loss function. Increasing this value makes the resulting image look smoother and less jagged, at the cost of lower fidelity to style and content.
Below the next three cells of code (in which you shouldn't change the hyperparameters), feel free to copy and paste the parameters to play around them and see how the resulting image changes.
```
# Composition VII + Tubingen
params1 = {
'content_image' : 'styles/tubingen.jpg',
'style_image' : 'styles/composition_vii.jpg',
'image_size' : 192,
'style_size' : 512,
'content_layer' : 2,
'content_weight' : 5e-2,
'style_layers' : (0, 3, 5, 6),
'style_weights' : (20000, 500, 12, 1),
'tv_weight' : 5e-2
}
style_transfer(**params1)
# Scream + Tubingen
params2 = {
'content_image':'styles/tubingen.jpg',
'style_image':'styles/the_scream.jpg',
'image_size':192,
'style_size':224,
'content_layer':2,
'content_weight':3e-2,
'style_layers':[0, 3, 5, 6],
'style_weights':[200000, 800, 12, 1],
'tv_weight':2e-2
}
style_transfer(**params2)
# Starry Night + Tubingen
params3 = {
'content_image' : 'styles/tubingen.jpg',
'style_image' : 'styles/starry_night.jpg',
'image_size' : 192,
'style_size' : 192,
'content_layer' : 2,
'content_weight' : 6e-2,
'style_layers' : [0, 3, 5, 6],
'style_weights' : [300000, 1000, 15, 3],
'tv_weight' : 2e-2
}
style_transfer(**params3)
```
## Feature Inversion
The code you've written can do another cool thing. In an attempt to understand the types of features that convolutional networks learn to recognize, a recent paper [1] attempts to reconstruct an image from its feature representation. We can easily implement this idea using image gradients from the pretrained network, which is exactly what we did above (but with two different feature representations).
Now, if you set the style weights to all be 0 and initialize the starting image to random noise instead of the content source image, you'll reconstruct an image from the feature representation of the content source image. You're starting with total noise, but you should end up with something that looks quite a bit like your original image.
(Similarly, you could do "texture synthesis" from scratch if you set the content weight to 0 and initialize the starting image to random noise, but we won't ask you to do that here.)
Run the following cell to try out feature inversion.
[1] Aravindh Mahendran, Andrea Vedaldi, "Understanding Deep Image Representations by Inverting them", CVPR 2015
```
# Feature Inversion -- Starry Night + Tubingen
params_inv = {
'content_image' : 'styles/tubingen.jpg',
'style_image' : 'styles/starry_night.jpg',
'image_size' : 192,
'style_size' : 192,
'content_layer' : 2,
'content_weight' : 6e-2,
'style_layers' : [0, 3, 5, 6],
'style_weights' : [0, 0, 0, 0], # we discard any contributions from style to the loss
'tv_weight' : 2e-2,
'init_random': True # we want to initialize our image to be random
}
style_transfer(**params_inv)
```
| github_jupyter |
# Lya Quasar Weighting
```
%pylab inline
import astropy.table
```
## Quasar Value
Read quasar values $V(r, z)$ tabulated on a grid of r-mag and redshift. For details see [here](https://desi.lbl.gov/trac/wiki/ValueQSO):
```
def load_weights():
table = astropy.table.Table.read('quasarvalue.txt', format='ascii')
z_col, r_col, w_col = table.columns[0], table.columns[1], table.columns[2]
z_vec = np.unique(z_col)
z_edges = np.linspace(2.025, 4.025, len(z_vec) + 1)
assert np.allclose(z_vec, 0.5 * (z_edges[1:] + z_edges[:-1]))
r_vec = np.unique(r_col)
r_edges = np.linspace(18.05, 23.05, len(r_vec) + 1)
assert np.allclose(r_vec, 0.5 * (r_edges[1:] + r_edges[:-1]))
W = np.empty((len(r_vec), len(z_vec)))
k = 0
for j in range(len(z_vec)):
for i in range(len(r_vec))[::-1]:
assert r_col[k] == r_vec[i]
assert z_col[k] == z_vec[j]
W[i, j] = w_col[k]
k += 1
return W, r_edges, r_vec, z_edges, z_vec
W, r_edges, r_vec, z_edges, z_vec = load_weights()
def plot_weights(W=W):
plt.pcolormesh(r_edges, z_edges, W.T, cmap='magma')
plt.colorbar().set_label('QSO Value [arb. units]')
plt.contour(r_vec, z_vec, W.T, colors='w', alpha=0.5)
plt.xlabel('QSO r-band magnitude')
plt.ylabel('QSO redshift')
plot_weights()
```
## Quasar Luminosity Function Prior
Copied from [this notebook](https://github.com/dkirkby/ArgonneLymanAlpha/blob/master/notebooks/SampleProperties.ipynb):
```
table2015a = np.array([
15.75, 30, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
16.25, 60, 8, 4, 5, 5, 4, 4, 4, 4, 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
16.75, 117, 29, 17, 19, 18, 17, 16, 16, 15, 12, 8, 6, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
17.25, 216, 101, 62, 70, 69, 64, 61, 62, 59, 45, 32, 22, 13, 7, 4, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
17.75, 358, 312, 224, 255, 253, 235, 227, 231, 224, 171, 121, 82, 47, 25, 13, 7, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
18.25, 525, 788, 722, 855, 869, 819, 803, 824, 811, 630, 452, 309, 171, 88, 46, 22, 9, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
18.75, 703, 1563, 1890, 2393, 2544, 2493, 2507, 2612, 2622, 2112, 1572, 1096, 603, 309, 157, 76, 28, 8, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
19.25, 898, 2490, 3740, 5086, 5758, 5971, 6214, 6580, 6745, 5779, 4613, 3369, 1913, 1004, 516, 249, 93, 26, 10, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
19.75, 1125, 3445, 5827, 8319, 9913, 10805, 11590, 12422, 12937, 11839, 10261, 8011, 4902, 2771, 1499, 753, 289, 78, 31, 12, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0,
20.25, 1399, 4456, 7930, 11585, 14183, 15895, 17350, 18718, 19660, 18783, 17275, 14270, 9517, 5936, 3513, 1919, 804, 228, 91, 34, 10, 2, 1, 0, 0, 0, 0, 0, 0, 0,
20.75, 1734, 5616, 10195, 15029, 18589, 21065, 23176, 25094, 26479, 25795, 24410, 20801, 14695, 9899, 6391, 3856, 1851, 599, 248, 94, 27, 6, 1, 1, 0, 0, 0, 0, 0, 0,
21.25, 2141, 7016, 12842, 18997, 23563, 26793, 29584, 32124, 34027, 33395, 31948, 27600, 20026, 14047, 9572, 6217, 3399, 1325, 598, 241, 73, 17, 4, 1, 1, 1, 0, 0, 0, 0,
21.75, 2631, 8738, 16067, 23807, 29528, 33591, 37170, 40481, 43047, 42378, 40701, 35383, 25928, 18498, 12931, 8731, 5198, 2395, 1211, 541, 182, 45, 10, 3, 2, 2, 1, 1, 0, 0,
22.25, 3211, 10871, 20058, 29754, 36864, 41912, 46457, 50760, 54210, 53457, 51424, 44870, 32982, 23683, 16738, 11500, 7140, 3651, 2036, 1022, 394, 110, 25, 8, 6, 4, 2, 2, 1, 1,
22.75, 3875, 13520, 25026, 37157, 45968, 52212, 57971, 63564, 68202, 67344, 64840, 56742, 41732, 30041, 21339, 14774, 9334, 5003, 2969, 1636, 730, 239, 60, 21, 13, 8, 5, 3, 2, 1,
23.25, 4591, 16812, 31220, 46395, 57302, 65011, 72306, 79586, 85821, 84853, 81750, 71739, 52744, 38010, 27078, 18823, 11969, 6500, 3980, 2322, 1159, 450, 133, 48, 30, 19, 12, 7, 5, 3,
23.75, 5270, 20905, 38950, 57934, 71426, 80937, 90180, 99667, 108052, 106983, 103130, 90753, 66677, 48080, 34331, 23929, 15247, 8253, 5120, 3076, 1645, 733, 256, 102, 63, 39, 24, 15, 9, 6,
24.25, 5713, 25993, 48598, 72353, 89037, 100762, 112480, 124858, 136130, 134989, 130200, 114903, 84351, 60850, 43543, 30420, 19392, 10379, 6468, 3939, 2184, 1061, 432, 192, 119, 73, 45, 27, 17, 10,
24.75, 5464, 32318, 60643, 90374, 110997, 125444, 140309, 156474, 171625, 170467, 164509, 145614, 106798, 77072, 55275, 38702, 24667, 13006, 8110, 4969, 2803, 1428, 648, 317, 199, 123, 76, 46, 28, 17
]).reshape(19, 31)
table2015b = np.array([
15.75, 23, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,
16.25, 49, 4, 2, 2, 2, 2, 2, 2, 2, 1, 1, 16, 10, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,
16.75, 99, 16, 8, 10, 10, 9, 9, 8, 8, 5, 3, 40, 25, 12, 6, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,
17.25, 190, 69, 38, 44, 45, 41, 39, 39, 36, 24, 15, 104, 65, 32, 15, 7, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
17.75, 326, 248, 165, 196, 199, 185, 177, 176, 163, 113, 69, 268, 167, 82, 39, 17, 6, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,
18.25, 488, 699, 628, 775, 805, 763, 744, 751, 709, 501, 314, 679, 422, 211, 102, 46, 16, 5, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,
18.75, 664, 1453, 1808, 2389, 2615, 2602, 2624, 2702, 2629, 1968, 1308, 1650, 1027, 532, 262, 119, 42, 12, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,
19.25, 866, 2337, 3638, 5131, 5991, 6356, 6674, 7031, 7076, 5840, 4349, 3696, 2334, 1283, 657, 307, 111, 30, 11, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,
19.75, 1113, 3252, 5609, 8203, 9995, 11093, 11997, 12825, 13218, 11932, 10033, 7168, 4740, 2850, 1566, 769, 288, 77, 27, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,
20.25, 1423, 4274, 7646, 11336, 14053, 15897, 17425, 18758, 19553, 18488, 16711, 11689, 8346, 5597, 3399, 1817, 723, 195, 70, 23, 6, 1, 0, 0, 0, 0, 0, 0, 0, 0 ,
20.75, 1814, 5517, 9994, 14889, 18542, 21093, 23243, 25116, 26334, 25315, 23523, 16660, 12773, 9487, 6456, 3873, 1709, 482, 177, 58, 15, 3, 1, 0, 0, 0, 0, 0, 0, 0 ,
21.25, 2303, 7084, 12906, 19262, 23994, 27320, 30181, 32721, 34466, 33311, 31222, 21941, 17567, 14054, 10566, 7166, 3647, 1143, 436, 148, 38, 7, 1, 0, 0, 0, 0, 0, 0, 0 ,
21.75, 2911, 9082, 16610, 24818, 30879, 35139, 38892, 42310, 44774, 43370, 40764, 27761, 22625, 18918, 15230, 11423, 6772, 2503, 1034, 367, 96, 19, 3, 1, 0, 0, 0, 0, 0, 0 ,
22.25, 3652, 11639, 21358, 31945, 39682, 45108, 50015, 54614, 58082, 56344, 53020, 34486, 28144, 24081, 20162, 16146, 10868, 4879, 2277, 876, 241, 49, 9, 2, 1, 1, 0, 0, 0, 0 ,
22.75, 4527, 14913, 27461, 41112, 50977, 57875, 64289, 70486, 75363, 73207, 68942, 42521, 34433, 29793, 25456, 21136, 15480, 8290, 4489, 1955, 585, 122, 22, 5, 3, 1, 1, 0, 0, 0 ,
23.25, 5504, 19106, 35311, 52915, 65485, 74247, 82634, 90995, 97849, 95188, 89701, 52304, 41818, 36375, 31400, 26555, 20387, 12378, 7728, 3931, 1345, 302, 55, 14, 7, 3, 2, 1, 0, 0,
23.75, 6479, 24477, 45409, 68119, 84128, 95249, 106225, 117520, 127141, 123880, 116812, 64335, 50637, 44159, 38330, 32717, 25709, 16775, 11668, 6924, 2830, 719, 137, 35, 18, 9, 4, 2, 1, 0 ,
24.25, 7195, 31358, 58404, 87705, 108088, 122196, 136567, 151843, 165336, 161372, 152261, 79215, 61261, 53494, 46590, 39969, 31740, 21404, 15927, 10682, 5278, 1609, 337, 89, 45, 22, 11, 5, 3, 1,
24.75, 7043, 40171, 75127, 112945, 138885, 156770, 175600, 196278, 215178, 210413, 198658, 97685, 74113, 64767, 56549, 48670, 38821, 26430, 20396, 14815, 8615, 3269, 793, 220, 112, 56, 28, 13, 6, 3
]).reshape(19, 31)
def bin_index(bin_centers, low_edge):
"""Find the index of the bin with the specified low edge, where bins is an array of equally-spaced bin centers.
"""
delta = bin_centers[1] - bin_centers[0]
min_value = bin_centers[0] - 0.5 * delta
index = int(round((low_edge - min_value) / delta))
if abs((low_edge - min_value) / delta - index) > 1e-5:
raise ValueError('low_edge = {} is not aligned with specified bins.'.format(low_edge))
return index
def luminosity_function(data, z_max=6.0, area_sq_deg=10000.):
"""Transform a data array from Nathalie into a tuple gbin, zbin, nqso.
"""
ng, nz = data.shape
# g-band magnitude bin centers are in the first column.
gbin = data[:, 0]
nz = nz - 1
# Check that g-band bins are equally spaced.
assert np.allclose(np.diff(gbin), gbin[1] - gbin[0])
# redshift bins are equally spaced from 0 up to z_max.
zbin = z_max * (0.5 + np.arange(nz)) / nz
# The remaining columns give predicted numbers of QSO in a 10,000 sq.deg. sample.
# Normalize to densisities per sq.deg.
nqso = data[:, 1:].reshape((ng, nz)) / area_sq_deg
return gbin, zbin, nqso
lumi_table = luminosity_function(0.5 * (table2015a + table2015b))
def lumi_plot(magbin, zbin, nqso, mag_min=18, mag_max=23, z_min=1, z_max=4):
z_min_cut = bin_index(zbin, z_min)
z_max_cut = bin_index(zbin, z_max)
mag_min_cut = bin_index(magbin, mag_min)
mag_max_cut = bin_index(magbin, mag_max)
#
plt.figure(figsize=(8,5))
plt.imshow(nqso[mag_min_cut:mag_max_cut, z_min_cut:z_max_cut].T,
origin='lower', interpolation='bicubic', cmap='magma',
aspect='auto', extent=(mag_min, mag_max, z_min, z_max))
plt.ylim(z_min, z_max)
plt.xlim(mag_min, mag_max)
plt.ylabel('QSO redshift')
plt.xlabel('QSO g~r magnitude')
plt.colorbar().set_label(
'N(z) / sq.deg. / $(\Delta z = {:.1f})$ / $(\Delta g = {:.1f})$'
.format(zbin[1] - zbin[0], magbin[1] - magbin[0]))
plt.contour(r_vec, z_vec, W.T, colors='w', alpha=0.5)
#plt.grid(c='w')
lumi_plot(*lumi_table)
```
## Binning
Rebin weights to the redshift ranges of neural network output categories:
Given probability density $p(z|T)$ for a target $T$ to be a quasar at redshift $z$, calculate the "value" of re-observing $T$ as:
$$
t(r, z) = \int dz\, p(z|T, r) V(r, z)
$$
Write:
$$
p(z|T, r) = \frac{P(T|z) P(z, r)}{P(T)}
$$
```
def rebin_weights(new_z_edges=[2.0, 2.5, 3.0, 4.0]):
n_z = len(new_z_edges) - 1
W2 = np.empty((len(r_vec), n_z))
for i in range(len(r_vec)):
W2[i] = np.histogram(z_vec, bins=new_z_edges, weights=W[i])[0]
return W2, new_z_edges
W2, new_z_edges = rebin_weights()
def plot_reweights():
plt.pcolormesh(r_edges, new_z_edges, W2.T, cmap='magma')
plt.colorbar().set_label('QSO Value [arb. units]')
plt.contour(r_vec, z_vec, W.T, colors='w', alpha=1)
plt.xlabel('QSO r-band magnitude')
plt.ylabel('QSO redshift')
plot_reweights()
```
Calculate overall values for a quasar target based on its absolute probabilities of being a quasar in different redshift bins:
```
def get_values(r_mag, z_prob):
r_mag = np.asarray(r_mag)
z_prob = np.asarray(z_prob)
assert np.all((r_edges[0] <= r_mag) & (r_mag < r_edges[-1]))
assert z_prob.shape[-1] == len(new_z_edges) - 1
assert z_prob.shape[:-1] == r_mag.shape
assert np.all(z_prob.sum(axis=-1) <= 1.)
r_index = np.digitize(r_mag, r_edges)
return (W2[r_index] * z_prob).sum(axis=-1)
get_values([19, 19, 19], [[1,0,0],[0,1,0],[0,0,1]])
```
## Neural Network Results
```
def get_nn():
t = astropy.table.Table.read('quassifier_results_dense_prob.fits', hdu=1)
print t.colnames
print t['Prob'].shape
return t
nn = get_nn()
def plot_nn(i=8, save=None):
x = np.arange(5)
bins = np.linspace(-0.5, 4.5, 6)
plt.hist(x, bins=bins, weights=nn['Prob'][i], histtype='stepfilled', color='r')
plt.gca().get_yaxis().set_ticks([])
plt.ylabel('Relative Probability')
plt.gca().set_xticklabels(['', 'ELG', 'Galaxy', 'LyaQSO', 'TracerQSO', 'Star'])
plt.xlim(bins[0], bins[-1])
plt.tight_layout()
if save:
plt.savefig(save)
plot_nn(0, 'lyaprob.pdf')
plot_nn(1, 'bgprob.pdf')
```
| github_jupyter |
```
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.cross_validation import train_test_split, cross_val_score, KFold
from sklearn.preprocessing import LabelEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.grid_search import GridSearchCV
from IPython.display import Image
pd.set_option('chained_assignment', None)
plt.style.use('ggplot')
plt.rc('xtick.major', size=0)
plt.rc('ytick.major', size=0)
user_tags = pd.read_csv("user_tags_merge.csv")
user_tags
X = user_tags[['nail', 'person', 'sport', 'food','hair', 'wedding']]
X['mix'] = X['hair'] + X['nail'] + X['wedding']
X.tail()
y = user_tags['gender_male']
X=X.drop(['nail', 'sport','hair', 'wedding','mix'], axis=1)
X.tail()
np.random.seed = 0
xmin, xmax = -2, 12
ymin, ymax = -2, 17
index_male = y[y==1].index
index_female = y[y==0].index
fig, ax = plt.subplots()
cm = plt.cm.RdBu
cm_bright = ListedColormap(['#FF0000', '#0000FF'])
sc = ax.scatter(X.loc[index_male, 'food'],
X.loc[index_male, 'person']+(np.random.rand(len(index_male))-0.5)*0.1,
color='b', label='male', alpha=0.3)
sc = ax.scatter(X.loc[index_female, 'food'],
X.loc[index_female, 'person']+(np.random.rand(len(index_female))-0.5)*0.1,
color='r', label='female', alpha=0.3)
ax.set_xlabel('food')
ax.set_ylabel('person')
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
ax.legend(bbox_to_anchor=(1.4, 1.03))
plt.show()
X = user_tags[['nail', 'person', 'sport', 'food','coffee','cake','beer','sky']]
y = user_tags["gender_male"]
clf = LogisticRegression()
def cross_val(clf, X, y, K, random_state=0):
cv = KFold(len(y), K, shuffle=True, random_state=random_state)
scores = cross_val_score(clf, X, y, cv=cv)
return scores
scores = cross_val(clf, X, y, 6)
print('Scores:', scores)
print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2))
clf = DecisionTreeClassifier(criterion='entropy', max_depth=2, min_samples_leaf=2)
scores = cross_val(clf, X, y, 5)
print('Scores:', scores)
print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
'C': [1, 10, 100, 1000]},
{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
clf = SVC(kernel='rbf', C=100)
X = user_tags[['nail', 'person', 'sport', 'food','coffee','wedding','cake','beer']]
y = user_tags["gender_male"]
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.5, random_state=1)
clf.fit(X_train, y_train)
clf.predict(X_val)
y_val
clf.score(X_val, y_val)
XX = user_tags
XX.tail()
XX=XX.drop(['user_id', 'user_name','gender_male'], axis=1)
X
XX_train, XX_val, y_train, y_val = train_test_split(XX, y, train_size=0.5, random_state=1)
clf = LogisticRegression()
def cross_val(clf, XX, y, K, random_state=0):
cv = KFold(len(y), K, shuffle=True, random_state=random_state)
scores = cross_val_score(clf, XX, y, cv=cv)
return scores
scores = cross_val(clf, XX, y, 3)
print('Scores:', scores)
print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2))
X = user_tags[['nail','hair', 'person', 'sport', 'food','night','coffee','wedding','cake','beer', 'dog', 'animal', 'tree','blossom','cat', 'flower','sky','nature','cherry']]
y = user_tags["gender_male"]
X['animal']=X['animal']+X['dog']+X['cat']
X['cosme']=X['hair']+X['nail']
X['nature']=X['nature']+X['sky']+X['flower']+X['tree']+X['blossom']+X['cherry']
X = X.drop(['nail','hair', 'dog', 'cat', 'sky','flower','tree','blossom','cherry'],axis=1)
X.tail()
clf = LogisticRegression()
def cross_val(clf, X, y, K, random_state=0):
cv = KFold(len(y), K, shuffle=True, random_state=random_state)
scores = cross_val_score(clf, X, y, cv=cv)
return scores
for i in range(2,12):
scores = cross_val(clf, X, y, i)
print(i)
print('Scores:', scores)
print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2))
clf = SVC(kernel='rbf', C=1000)
for i in range(2,12):
scores = cross_val(clf, X, y, i)
print(i)
print('Scores:', scores)
print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2))
clf = DecisionTreeClassifier(criterion='entropy', max_depth=5, min_samples_leaf=2)
for i in range(2,12):
scores = cross_val(clf, X, y, i)
print(i)
print('Scores:', scores)
print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2))
from sklearn.externals import joblib
clf = LogisticRegression()
clf.fit(X,y)
joblib.dump(clf, 'clf.pkl')
X.tail()
```
| github_jupyter |
## Polygon Environment Building
Devising scenarios for the polygon-based environments.
```
%load_ext autoreload
%autoreload 2
from mpb import MPB, MultipleMPB
from plot_stats import plot_planner_stats, plot_smoother_stats
from utils import latexify
from table import latex_table
from definitions import *
import matplotlib as mpl
import sys, os
mpl.rcParams['mathtext.fontset'] = 'cm'
# make sure to not use Level-3 fonts
mpl.rcParams['pdf.fonttype'] = 42
import matplotlib.pyplot as plt
from copy import deepcopy
%config InlineBackend.figure_format='retina'
```
### Polygon Environments
```
def visualize(scenario: str, start: {str: float}, goal: {str: float}, robot_model: str = None):
m = MPB()
m["max_planning_time"] = 60
m["env.start"] = start
m["env.goal"] = goal
m["env.type"] = "polygon"
m["env.polygon.source"] = "polygon_mazes/%s.svg" % scenario
if robot_model:
print("Using robot model %s." % robot_model)
m["env.collision.robot_shape_source"] = robot_model
m.set_planners(['informed_rrt_star'])
m.set_planners(['bfmt'])
m["steer.car_turning_radius"] = 2
# m.set_planners(["sbpl_mha"])
m["sbpl.scaling"] = 1
if m.run(id="test_%s" % scenario, runs=1) == 0:
m.visualize_trajectories(draw_start_goal_thetas=True, plot_every_nth_polygon=10, silence=True, save_file="plots/%s.pdf" % scenario)
m.print_info()
# visualize("parking2",
# {"theta": -1.57, "x": 12.3, "y": -2.73},
# {"theta": 0, "x": 2.5, "y": -7.27})
# visualize("parking2",
# {"theta": -1.57, "x": 12.3, "y": -2.73},
# {"theta": 3.14, "x": 2.5, "y": -7.27})
scenarios = [
("parking1", {"theta": 0, "x": 2, "y": -7.27}, {"theta": -1.58, "x": 9, "y": -11.72}),
("parking2", {"theta": 0, "x": 2.5, "y": -7.27}, {"theta": -1.57, "x": 12, "y": -3}),
("parking3", {"theta": 0, "x": 3.82, "y": -13}, {"theta": 0, "x": 29, "y": -15.5}),
("warehouse", {"theta": -1.58, "x": 7.5, "y": -10}, {"theta": 1.58, "x": 76.5, "y": -10}, "polygon_mazes/warehouse_robot.svg"),
("warehouse2", {"theta": -1.58, "x": 7.5, "y": -10}, {"theta": -1.58, "x": 116, "y": -70}, "polygon_mazes/warehouse_robot.svg")
]
list(map(lambda x: visualize(*x), scenarios));
```
# Figurehead
Figure 1 to showcase Bench-MR.
```
m = MPB()
scenario = "warehouse"
m["max_planning_time"] = 30
m["env.start"] = {"theta": -1.58, "x": 7.5, "y": -10}
m["env.goal"] = {"theta": 1.58, "x": 76.5, "y": -10}
m["env.type"] = "polygon"
m["env.polygon.source"] = "polygon_mazes/%s.svg" % scenario
m["env.collision.robot_shape_source"] = "polygon_mazes/warehouse_robot.svg"
m.set_planners([])
m.set_planners(['bfmt', 'cforest', 'prm', 'prm_star', 'informed_rrt_star', 'sbpl_mha'])
m["steer.car_turning_radius"] = 2
m["sbpl.scaling"] = 1
m.run(id="test_%s" % scenario, runs=1)
m.print_info()
m.visualize_trajectories(ignore_planners='cforest, bfmt',
draw_start_goal_thetas=True,
plot_every_nth_polygon=8,
fig_width=8,
fig_height=8,
silence=True,
save_file="plots/%s.pdf" % scenario,
num_colors=10)
```
| github_jupyter |
# Classical Logic Gates with Quantum Circuits
```
from qiskit import *
from qiskit.tools.visualization import plot_histogram
import numpy as np
```
Using the NOT gate (expressed as `x` in Qiskit), the CNOT gate (expressed as `cx` in Qiskit) and the Toffoli gate (expressed as `ccx` in Qiskit) create functions to implement the XOR, AND, NAND and OR gates.
An implementation of the NOT gate is provided as an example.
## NOT gate
This function takes a binary string input (`'0'` or `'1'`) and returns the opposite binary output'.
```
def NOT(input):
q = QuantumRegister(1) # a qubit in which to encode and manipulate the input
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# We encode '0' as the qubit state |0⟩, and '1' as |1⟩
# Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'
# For an input of '1', we do an x to rotate the |0⟩ to |1⟩
if input=='1':
qc.x( q[0] )
# Now we've encoded the input, we can do a NOT on it using x
qc.x( q[0] )
# Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]
qc.measure( q[0], c[0] )
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1)
output = next(iter(job.result().get_counts()))
return output
```
## XOR gate
Takes two binary strings as input and gives one as output.
The output is `'0'` when the inputs are equal and `'1'` otherwise.
```
def XOR(input1,input2):
q = QuantumRegister(2) # two qubits in which to encode and manipulate the input
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[1],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
```
## AND gate
Takes two binary strings as input and gives one as output.
The output is `'1'` only when both the inputs are `'1'`.
```
def AND(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
```
## NAND gate
Takes two binary strings as input and gives one as output.
The output is `'0'` only when both the inputs are `'1'`.
```
def NAND(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
```
## OR gate
Takes two binary strings as input and gives one as output.
The output is `'1'` if either input is `'1'`.
```
def OR(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
```
## Tests
The following code runs the functions above for all possible inputs, so that you can check whether they work.
```
print('\nResults for the NOT gate')
for input in ['0','1']:
print(' Input',input,'gives output',NOT(input))
print('\nResults for the XOR gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',XOR(input1,input2))
print('\nResults for the AND gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',AND(input1,input2))
print('\nResults for the NAND gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',NAND(input1,input2))
print('\nResults for the OR gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',OR(input1,input2))
import qiskit
qiskit.__qiskit_version__
```
| github_jupyter |
# Beyond linear separation in classification
As we saw in the regression section, the linear classification model
expects the data to be linearly separable. When this assumption does not
hold, the model is not expressive enough to properly fit the data.
Therefore, we need to apply the same tricks as in regression: feature
augmentation (potentially using expert-knowledge) or using a
kernel-based method.
We will provide examples where we will use a kernel support vector machine
to perform classification on some toy-datasets where it is impossible to
find a perfect linear separation.
First, we redefine our plotting utility to show the decision boundary of a
classifier.
```
import numpy as np
import matplotlib.pyplot as plt
def plot_decision_function(fitted_classifier, range_features, ax=None):
"""Plot the boundary of the decision function of a classifier."""
from sklearn.preprocessing import LabelEncoder
feature_names = list(range_features.keys())
# create a grid to evaluate all possible samples
plot_step = 0.02
xx, yy = np.meshgrid(
np.arange(*range_features[feature_names[0]], plot_step),
np.arange(*range_features[feature_names[1]], plot_step),
)
# compute the associated prediction
Z = fitted_classifier.predict(np.c_[xx.ravel(), yy.ravel()])
Z = LabelEncoder().fit_transform(Z)
Z = Z.reshape(xx.shape)
# make the plot of the boundary and the data samples
if ax is None:
_, ax = plt.subplots()
ax.contourf(xx, yy, Z, alpha=0.4, cmap="RdBu")
return ax
```
We will generate a first dataset where the data are represented as two
interlaced half circle. This dataset is generated using the function
[`sklearn.datasets.make_moons`](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html).
```
import pandas as pd
from sklearn.datasets import make_moons
feature_names = ["Feature #0", "Features #1"]
target_name = "class"
X, y = make_moons(n_samples=100, noise=0.13, random_state=42)
# We store both the data and target in a dataframe to ease plotting
moons = pd.DataFrame(np.concatenate([X, y[:, np.newaxis]], axis=1),
columns=feature_names + [target_name])
data_moons, target_moons = moons[feature_names], moons[target_name]
range_features_moons = {"Feature #0": (-2, 2.5), "Feature #1": (-2, 2)}
```
Since the dataset contains only two features, we can make a scatter plot to
have a look at it.
```
import seaborn as sns
sns.scatterplot(data=moons, x=feature_names[0], y=feature_names[1],
hue=target_moons, palette=["tab:red", "tab:blue"])
_ = plt.title("Illustration of the moons dataset")
```
From the intuitions that we got by studying linear model, it should be
obvious that a linear classifier will not be able to find a perfect decision
function to separate the two classes.
Let's try to see what is the decision boundary of such a linear classifier.
We will create a predictive model by standardizing the dataset followed by
a linear support vector machine classifier.
```
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
linear_model = make_pipeline(StandardScaler(), SVC(kernel="linear"))
linear_model.fit(data_moons, target_moons)
```
<div class="admonition warning alert alert-danger">
<p class="first admonition-title" style="font-weight: bold;">Warning</p>
<p class="last">Be aware that we fit and will check the boundary decision of the classifier
on the same dataset without splitting the dataset into a training set and a
testing set. While this is a bad practice, we use it for the sake of
simplicity to depict the model behavior. Always use cross-validation when
you want to assess the statistical performance of a machine-learning model.</p>
</div>
Let's check the decision boundary of such a linear model on this dataset.
```
ax = sns.scatterplot(data=moons, x=feature_names[0], y=feature_names[1],
hue=target_moons, palette=["tab:red", "tab:blue"])
plot_decision_function(linear_model, range_features_moons, ax=ax)
_ = plt.title("Decision boundary of a linear model")
```
As expected, a linear decision boundary is not enough flexible to split the
two classes.
To push this example to the limit, we will create another dataset where
samples of a class will be surrounded by samples from the other class.
```
from sklearn.datasets import make_gaussian_quantiles
feature_names = ["Feature #0", "Features #1"]
target_name = "class"
X, y = make_gaussian_quantiles(
n_samples=100, n_features=2, n_classes=2, random_state=42)
gauss = pd.DataFrame(np.concatenate([X, y[:, np.newaxis]], axis=1),
columns=feature_names + [target_name])
data_gauss, target_gauss = gauss[feature_names], gauss[target_name]
range_features_gauss = {"Feature #0": (-4, 4), "Feature #1": (-4, 4)}
ax = sns.scatterplot(data=gauss, x=feature_names[0], y=feature_names[1],
hue=target_gauss, palette=["tab:red", "tab:blue"])
_ = plt.title("Illustration of the Gaussian quantiles dataset")
```
Here, this is even more obvious that a linear decision function is not
adapted. We can check what decision function, a linear support vector machine
will find.
```
linear_model.fit(data_gauss, target_gauss)
ax = sns.scatterplot(data=gauss, x=feature_names[0], y=feature_names[1],
hue=target_gauss, palette=["tab:red", "tab:blue"])
plot_decision_function(linear_model, range_features_gauss, ax=ax)
_ = plt.title("Decision boundary of a linear model")
```
As expected, a linear separation cannot be used to separate the classes
properly: the model will under-fit as it will make errors even on
the training set.
In the section about linear regression, we saw that we could use several
tricks to make a linear model more flexible by augmenting features or
using a kernel. Here, we will use the later solution by using a radial basis
function (RBF) kernel together with a support vector machine classifier.
We will repeat the two previous experiments and check the obtained decision
function.
```
kernel_model = make_pipeline(StandardScaler(), SVC(kernel="rbf", gamma=5))
kernel_model.fit(data_moons, target_moons)
ax = sns.scatterplot(data=moons, x=feature_names[0], y=feature_names[1],
hue=target_moons, palette=["tab:red", "tab:blue"])
plot_decision_function(kernel_model, range_features_moons, ax=ax)
_ = plt.title("Decision boundary with a model using an RBF kernel")
```
We see that the decision boundary is not anymore a straight line. Indeed,
an area is defined around the red samples and we could imagine that this
classifier should be able to generalize on unseen data.
Let's check the decision function on the second dataset.
```
kernel_model.fit(data_gauss, target_gauss)
ax = sns.scatterplot(data=gauss, x=feature_names[0], y=feature_names[1],
hue=target_gauss, palette=["tab:red", "tab:blue"])
plot_decision_function(kernel_model, range_features_gauss, ax=ax)
_ = plt.title("Decision boundary with a model using an RBF kernel")
```
We observe something similar than in the previous case. The decision function
is more flexible and does not underfit anymore.
Thus, kernel trick or feature expansion are the tricks to make a linear
classifier more expressive, exactly as we saw in regression.
Keep in mind that adding flexibility to a model can also risk increasing
overfitting by making the decision function to sensitive to individual
(possibly noisy) data points of the training set. Here we can observe that
the decision functions remain smooth enough to preserve good generalization.
If you are curious, you can try repeated the above experiment with
`gamma=100` and look at the decision functions.
| github_jupyter |
# Regressão Softmax com dados do MNIST
## Objetivo
O objetivo deste notebook é ilustrar o uso de praticamente a mesma rede desenvolvida para a classificação das flores Íris, porém agora com o problema de classificação de dígitos manuscritos utilizando o dataset MNIST.
As principais diferenças são:
- tipo do dado, agora imagem com muito atributos: 28 x 28 pixels
- número de amostras, muito maior, 60 mil
Neste exercício será possível a interpretação do significado dos parâmetros treinados
## Importação das bibliotecas
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import torch
from torch.autograd import Variable
import torchvision
from torchvision.datasets import MNIST
```
## Carregamento dos dados do MNIST
```
dataset_dir = 'data/datasets/MNIST/'
MNIST(dataset_dir, train=False, transform=None, target_transform=None, download=True)
x_train, y_train = torch.load(dataset_dir + 'processed/training.pt')
print("Amostras de treinamento:", x_train.size(0))
print("\nDimensões dos dados das imagens: ", x_train.size())
print("Valores mínimo e máximo dos pixels:", torch.min(x_train), torch.max(x_train))
print("Tipo dos dados das imagens: ", type(x_train))
print("Tipo das classes das imagens: ", type(y_train))
```
### Carregamento, normalização e seleção dos dados do MNIST
Neste exemplo utilizaremos apenas 1000 amostras de treinamento.
```
x_train = x_train.float()
x_train = x_train / 255.
if True:
n_samples_train = 1000
x_train = x_train[:n_samples_train]
y_train = y_train[:n_samples_train]
print("Amostras de treinamento:", x_train.size(0))
print("\nDimensões dos dados das imagens: ", x_train.size())
print("Valores mínimo e máximo dos pixels:", torch.min(x_train), torch.max(x_train))
print("Tipo dos dados das imagens: ", type(x_train))
print("Tipo das classes das imagens: ", type(y_train))
```
### Visualizando os dados
```
n_samples = 24
# cria um grid com as imagens
grid = torchvision.utils.make_grid(x_train[:n_samples].unsqueeze(1), pad_value=1.0, padding=1)
plt.figure(figsize=(15, 10))
plt.imshow(grid.numpy().transpose(1, 2, 0))
plt.axis('off')
```
### Visualizando uma imagem com o matplotlib
```
image = x_train[2]
target = y_train[2]
plt.imshow(image.numpy().reshape(28,28), cmap='gray')
print('class:', target)
```
## Modelo
```
model = torch.nn.Linear(28*28, 10) # 28*28 atributos de entrada e 10 neurônios na sáida
```
### Testando um predict com poucas amostras
## Treinamento
### Inicialização dos parâmetros
```
epochs = 100
learningRate = 0.5
# Utilizaremos CrossEntropyLoss como função de perda
criterion = torch.nn.CrossEntropyLoss()
# Gradiente descendente
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
```
### Visualização do grafo computacional da perda (loss)
```
y_pred = model(Variable(x_train.view(-1,28*28)))
loss = criterion(y_pred, Variable(y_train))
from lib.pytorch_visualize import make_dot
p = make_dot(loss, dict(model.named_parameters()))
p
```
### Laço de treinamento dos pesos
```
losses = []
for i in range(epochs):
# Transforma a entrada para uma dimensão
inputs = Variable(x_train.view(-1, 28 * 28))
# Predict da rede
outputs = model(inputs)
# calcula a perda
loss = criterion(outputs, Variable(y_train))
# zero, backpropagation, ajusta parâmetros pelo gradiente descendente
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.data[0])
print('Final loss:', loss.data[0])
```
### Visualizando gráfico de perda durante o treinamento
```
plt.plot(losses)
```
## Avaliação
### Acurácia tanto no conjunto de treinamento como no conjunto de testes
```
def predict(model, input_data):
outputs = model(Variable(input_data))
_, predicts = torch.max(outputs, 1)
return predicts.data
y_pred = predict(model, x_train.view(-1, 28*28))
accuracy = (y_pred.numpy() == y_train.numpy()).mean()
print('Accuracy:', accuracy)
```
### Matriz de confusão com dados de treinamento e teste
```
print('Matriz de confusão:')
pd.crosstab(y_pred.numpy(), y_train.numpy())
```
## Visualizando a matriz de pesos treinados
Observe que a matriz de peso treinado para cada classe mostra a importância dos pesos associados aos caracteres de cada classe.
```
weights = model.state_dict()['weight']
print('weights:', weights.shape)
bias = model.state_dict()['bias']
print('bias: ', bias.shape)
# Visualizando pesos da classe 3
plt.imshow(weights[8, :].numpy().reshape((28,28)),cmap = 'gray')
plt.show()
```
### Visualizando os pesos de todas as classes
```
# cria um grid com as imagens
grid = torchvision.utils.make_grid(weights.view(-1, 1, 28, 28), normalize=True, pad_value=1.0, padding=1, nrow=10)
plt.figure(figsize=(15, 10))
plt.imshow(grid.numpy().transpose(1, 2, 0))
plt.axis('off');
```
### Diagrama da regressão softmax com visualização dos pesos W
<img src="../figures/RegressaoSoftmaxArgmaxNMIST.png",width = 400>
# Atividades
## Exercícios
- 1) Na configuração da figura acima, mostre os valores de z0 até z9, os valores das probabilidades y_hat, após o softmax, quando a rede recebe como entrada a nona amostra que contém o manuscrito do dígito '4':
```
image = x_train[9]
target = y_train[9]
plt.imshow(image.numpy().reshape(28,28), cmap='gray')
print('class:', target)
```
- 2) Insira código no laço do treinamento para que no final de cada época,
seja impresso: o número da época e a perda e a acurácia
- 3) Insira código no laço do treinamento para visualização dos valores dos gradientes referentes à classe do dígito 4, no final de cada época.
## Perguntas
1. Qual é o shape da matriz de entrada na rede?
2. Qual é o shape da saída da rede?
3. Qual é o número total de parâmetros da rede, incluindo o bias?
# Aprendizados
| github_jupyter |
# Train a Simple Audio Recognition model for microcontroller use
This notebook demonstrates how to train a 20kb [Simple Audio Recognition](https://www.tensorflow.org/tutorials/sequences/audio_recognition) model for [TensorFlow Lite for Microcontrollers](https://tensorflow.org/lite/microcontrollers/overview). It will produce the same model used in the [micro_speech](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/micro/examples/micro_speech) example application.
The model is designed to be used with [Google Colaboratory](https://colab.research.google.com).
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/micro/examples/micro_speech/train_speech_model.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/micro/examples/micro_speech/train_speech_model.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
The notebook runs Python scripts to train and freeze the model, and uses the TensorFlow Lite converter to convert it for use with TensorFlow Lite for Microcontrollers.
**Training is much faster using GPU acceleration.** Before you proceed, ensure you are using a GPU runtime by going to **Runtime -> Change runtime type** and selecting **GPU**. Training 18,000 iterations will take 1.5-2 hours on a GPU runtime.
## Configure training
The following `os.environ` lines can be customized to set the words that will be trained for, and the steps and learning rate of the training. The default values will result in the same model that is used in the micro_speech example. Run the cell to set the configuration:
```
import os
# A comma-delimited list of the words you want to train for.
# The options are: yes,no,up,down,left,right,on,off,stop,go
# All other words will be used to train an "unknown" category.
os.environ["WANTED_WORDS"] = "yes,no"
# The number of steps and learning rates can be specified as comma-separated
# lists to define the rate at each stage. For example,
# TRAINING_STEPS=15000,3000 and LEARNING_RATE=0.001,0.0001
# will run 18,000 training loops in total, with a rate of 0.001 for the first
# 15,000, and 0.0001 for the final 3,000.
os.environ["TRAINING_STEPS"]="15000,3000"
os.environ["LEARNING_RATE"]="0.001,0.0001"
# Calculate the total number of steps, which is used to identify the checkpoint
# file name.
total_steps = sum(map(lambda string: int(string),
os.environ["TRAINING_STEPS"].split(",")))
os.environ["TOTAL_STEPS"] = str(total_steps)
# Print the configuration to confirm it
!echo "Training these words: ${WANTED_WORDS}"
!echo "Training steps in each stage: ${TRAINING_STEPS}"
!echo "Learning rate in each stage: ${LEARNING_RATE}"
!echo "Total number of training steps: ${TOTAL_STEPS}"
```
## Install dependencies
Next, we'll install a GPU build of TensorFlow, so we can use GPU acceleration for training.
```
# Replace Colab's default TensorFlow install with a more recent
# build that contains the operations that are needed for training
!pip uninstall -y tensorflow tensorflow_estimator tensorboard
!pip install -q tf-estimator-nightly==1.14.0.dev2019072901 tf-nightly-gpu==1.15.0.dev20190729
```
We'll also clone the TensorFlow repository, which contains the scripts that train and freeze the model.
```
# Clone the repository from GitHub
!git clone -q https://github.com/tensorflow/tensorflow
# Check out a commit that has been tested to work
# with the build of TensorFlow we're using
!git -c advice.detachedHead=false -C tensorflow checkout 17ce384df70
```
## Load TensorBoard
Now, set up TensorBoard so that we can graph our accuracy and loss as training proceeds.
```
# Delete any old logs from previous runs
!rm -rf /content/retrain_logs
# Load TensorBoard
%load_ext tensorboard
%tensorboard --logdir /content/retrain_logs
```
## Begin training
Next, run the following script to begin training. The script will first download the training data:
```
!python tensorflow/tensorflow/examples/speech_commands/train.py \
--model_architecture=tiny_conv --window_stride=20 --preprocess=micro \
--wanted_words=${WANTED_WORDS} --silence_percentage=25 --unknown_percentage=25 \
--quantize=1 --verbosity=WARN --how_many_training_steps=${TRAINING_STEPS} \
--learning_rate=${LEARNING_RATE} --summaries_dir=/content/retrain_logs \
--data_dir=/content/speech_dataset --train_dir=/content/speech_commands_train \
```
## Freeze the graph
Once training is complete, run the following cell to freeze the graph.
```
!python tensorflow/tensorflow/examples/speech_commands/freeze.py \
--model_architecture=tiny_conv --window_stride=20 --preprocess=micro \
--wanted_words=${WANTED_WORDS} --quantize=1 --output_file=/content/tiny_conv.pb \
--start_checkpoint=/content/speech_commands_train/tiny_conv.ckpt-${TOTAL_STEPS}
```
## Convert the model
Run this cell to use the TensorFlow Lite converter to convert the frozen graph into the TensorFlow Lite format, fully quantized for use with embedded devices.
```
!toco \
--graph_def_file=/content/tiny_conv.pb --output_file=/content/tiny_conv.tflite \
--input_shapes=1,49,40,1 --input_arrays=Reshape_2 --output_arrays='labels_softmax' \
--inference_type=QUANTIZED_UINT8 --mean_values=0 --std_dev_values=9.8077
```
The following cell will print the model size, which will be under 20 kilobytes.
```
import os
model_size = os.path.getsize("/content/tiny_conv.tflite")
print("Model is %d bytes" % model_size)
```
Finally, we use xxd to transform the model into a source file that can be included in a C++ project and loaded by TensorFlow Lite for Microcontrollers.
```
# Install xxd if it is not available
!apt-get -qq install xxd
# Save the file as a C source file
!xxd -i /content/tiny_conv.tflite > /content/tiny_conv.cc
# Print the source file
!cat /content/tiny_conv.cc
```
| github_jupyter |
En el mundo Qt tenemos una herramienta [RAD (Rapid Application Development)](https://es.wikipedia.org/wiki/Desarrollo_r%C3%A1pido_de_aplicaciones). Esta herramienta se llama Qt DesigneEste nuevo capítulo es el último en los que enumeramos los widgets disponibles dentro de Designer, en este caso le toca el turno a los *display widgets* o widgets que nos permiten mostrar información en distintos "formatos".**
Índice:
* [Instalación de lo que vamos a necesitar](https://pybonacci.org/2019/11/12/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-00-instalacion/).
* [Qt, versiones y diferencias](https://pybonacci.org/2019/11/21/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-01-qt-versiones-y-bindings/).
* [Hola, Mundo](https://pybonacci.org/2019/11/26/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-02-hola-mundo/).
* [Módulos en Qt](https://pybonacci.org/2019/12/02/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-03-modulos-qt/).
* [Añadimos icono a la ventana principal](https://pybonacci.org/2019/12/26/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-04-icono-de-la-ventana/).
* [Tipos de ventana en un GUI](https://pybonacci.org/2020/01/31/curso-de-creacion-de-guis-con-qt-capitulo-05-ventanas-principales-diferencias/).
* [Ventana inicial de carga o Splashscreen](https://pybonacci.org/2020/02/26/curso-de-creacion-de-guis-con-qt-capitulo-06-splash-screen/)
* [Menu principal. Introducción](https://pybonacci.org/2020/03/18/curso-de-creacion-de-guis-con-qt-capitulo-07-menu/).
* [Mejorando algunas cosas vistas](https://pybonacci.org/2020/03/26/curso-de-creacion-de-guis-con-qt-capitulo-08-mejorando-lo-visto/).
* [Gestión de eventos o Acción y reacción](https://pybonacci.org/2020/03/27/curso-de-creacion-de-guis-con-qt-capitulo-09-signals-y-slots/).
* [Introducción a Designer](https://pybonacci.org/2020/04/14/curso-de-creacion-de-guis-con-qt-capitulo-10-introduccion-a-designer/).
* [Los Widgets vistos a través de Designer: Primera parte](https://pybonacci.org/2020/05/01/curso-de-creacion-de-guis-con-qt-capitulo-11-widgets-en-designer-i/).
* [Los Widgets vistos a través de Designer: Segunda parte](https://pybonacci.org/2020/05/02/curso-de-creacion-de-guis-con-qt-capitulo-12:-widgets-en-designer-(ii)/).
* [Los Widgets vistos a través de Designer: Tercera parte](https://pybonacci.org/2020/05/03/curso-de-creacion-de-guis-con-qt-capitulo-13-widgets-en-designer-iii/).
* [Los Widgets vistos a través de Designer: Cuarta parte](https://pybonacci.org/2020/05/04/curso-de-creacion-de-guis-con-qt-capitulo-14-widgets-en-designer-iv/).
* [Los Widgets vistos a través de Designer: Quinta parte](https://pybonacci.org/2020/05/05/curso-de-creacion-de-guis-con-qt-capitulo-15-widgets-en-designer-v/).
* [Los Widgets vistos a través de Designer: Sexta parte](https://pybonacci.org/2020/05/06/curso-de-creacion-de-guis-con-qt-capitulo-16:-widgets-en-designer-(vi)/) (este capítulo).
* TBD… (lo actualizaré cuando tenga más claro los siguientes pasos).
[Los materiales para este capítulo los podéis descargar de [aquí](https://github.com/kikocorreoso/pyboqt/tree/chapter16)]
**[INSTALACIÓN] Si todavía no has pasado por el [inicio del curso, donde explico cómo poner a punto todo](https://pybonacci.org/2019/11/12/curso-de-creacion-de-guis-con-qt-capitulo-00:-instalacion/), ahora es un buen momento para hacerlo y después podrás seguir con esta nueva receta.**
En este último vídeo donde vemos los widgets que tenemos en Designer le damos un repaso a widgets que permiten mostrar información en distintas formas.
El vídeo está a continuación:
```
from IPython.display import Video
Video("https://libre.video/download/videos/9ee5e77e-5eac-4359-b75b-569060091a3b-360.mp4")
```
Transcripción del vídeo a continuación:
*Y ya solo nos queda una sección, la de los Widgets de exhibir cosas o de display. Tenemos, por ejemplo, las etiquetas que podemos usar en múltiples sitios. Luego tenemos el textbrowser que es como una etiqueta grande. Extiende al TextEdit que vimos anteriormente, en los widgets de input, pero es de solo lectura. Se puede usar para mostrar texto que el usuario no pueda editar. Tenemos un GraphicView que nos puede valer para meter, por ejemplo, gráficos de Matplotlib. Tenemos un CalendarWidget para seleccionar fechas. Podemos usar un LCD para enseñar números, similar al de una calculadora de mano. Podemos usar barras de progreso. Líneas horizontales o verticales que nos permitan separar cosas dentro de la ventana. Un Widget para meter gráficos OpenGL. El QQuickWidget no lo voy a comentar ahora, quizá en el futuro hagamos algo con esto pero a día de hoy no lo tengo todavía muy claro. Por último, tenemos el QWebEngineView que nos permite visualizar documentos web. Por ejemplo, le puedo pedir que me muestre una url y podemos ver el curso de creación de GUIs con Qt dentro del GUI con el que estamos trasteando.*
Y con todo esto creo que ya es suficiente. En el próximo capítulo más.
| github_jupyter |
```
import os, sys, glob, scipy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
```
## Plan
1. Describe the task
2. Make the simplest visualization you can think of that contains:
- the Dependent Variable, i.e. the behavior of the participants that you're trying to model/predict/explain/account for/etc
- the Independent Variable(s), i.e. the features of the trial that you think might influence behavior
- draw each trial as a point on this graph
3. Think of possible models that would generate similar values for the DV given the observed values for the IV
## 2. Make a visualization
##### Load some data
```
base_dir = os.path.realpath('')
data_dir = base_dir + '/Data'
data = pd.read_csv(data_dir + '/Study1_UG.csv')
data = data[['sub','trial','unfairness','choice']]
data['offer'] = 100 - data['unfairness']
data.head()
```
##### Make a simple plot
```
sub = 2
sub_data = data.query('sub == 2')
sub_data.head()
```
##### Problem 1. Plot each trial independently, use transparency to visualize overlap
##### Problem 2. Plot the average over trials with the same offer
## 3. Think of a model that can recreate this plot
###### Problem 3. Define the following models
- Model 1: always accept.
- Model 2: always reject.
- Model 3: act randomly.
- Model 4: maximize payoff ('greed').
- Model 5: minimize payoff ('inverse greed').
- Model 6: unfairness punisher (reject with a probability P proportional to the unfairness of the offer).
- Model 7: inequity aversion.
```
# Always accept
def model_1(offer):
return choice
# Always reject
def model_2(offer):
return choice
# Act random
def model_3(offer):
return choice
# Maximize payoff
def model_4(offer):
return choice
# Minimize payoff
def model_5(offer):
return choice
# Unfairness punisher
def model_6(offer):
return choice
# Inequity aversion
def model_7(offer):
return choice
```
## 4. Simulating task data
```
simulated_sub_data = sub_data[['trial','offer','choice']].copy()
simulated_sub_data['choice'] = np.nan
simulated_sub_data.head()
```
##### Problem 4. Simulate task data using a model
Use one of the models you have defined above to simulate choices for the simulated_sub_data dataframe.
So here we have a dataset – basically a list of trials that together constitute an experiment – with simulated task data! We've basically generated a pseudo-subject based on one of the models we defined. In the next steps, we will compare such simulated datasets to our actually observed subject data. The more similar a model's simulation is to observed task data, the better the model 'fits' the data.
## For next time
- Get Joey's data from GitHub
- Try to code models 5, 6, and 7
- Simulate data from each model
| github_jupyter |
<a href="https://colab.research.google.com/github/AnacletoLAB/grape/blob/main/tutorials/High_performance_graph_algorithms.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# High performance graph algorithms
A number of high performance algorithms have been implemented in Ensmallen, a considerable portion of which is an implementation of algorithms described in the literature by [David Bader](https://davidbader.net/), who we thank for his contribution to the field of graph algorithms.
See below for the algorithms available in Ensmallen.
Note that all of these algorithms are highly parallel implementations, and these benchmarks are being run on COLAB which typically provides virtual machines with a very small number of cores: on a machine with a reasonable number of cores they will execute much faster.
To install the GraPE library run:
```bash
pip install grape
```
To install exclusively the Ensmallen module, which may be useful when the TensorFlow dependency causes problems, do run:
```bash
pip install ensmallen
```
```
! pip install -q ensmallen
```
## Retrieving a graph to run the sampling on
In this tutorial we will run samples on one of the graph from the ones available from the automatic graph retrieval of Ensmallen, namely the [Homo Sapiens graph from STRING](https://string-db.org/cgi/organisms). If you want to load a graph from an edge list, just follow the examples provided from the [add reference to tutorial].
```
from ensmallen.datasets.string import HomoSapiens
```
Retrieving and loading the graph
```
graph = HomoSapiens()
```
We compute the graph report:
```
graph
```
Enable the speedups
```
graph.enable()
```
## Random Spanning arborescence
The spanning arborescence algorithm computes a set of edges, an [Arborescence](https://en.wikipedia.org/wiki/Arborescence_(graph_theory)), that is spanning, i.e cover all the nodes in the graph.
This is an implementation of [A fast, parallel spanning tree algorithm for symmetric multiprocessors
(SMPs)](https://davidbader.net/publication/2005-bc/2005-bc.pdf).
```
%%time
spanning_arborescence_edges = graph.spanning_arborescence()
```
## Connected components
The [connected components](https://en.wikipedia.org/wiki/Component_(graph_theory)) of a graph are the set of nodes connected one another by edges.
```
%%time
(
connected_component_ids,
number_of_connected_components,
minimum_component_size,
maximum_component_size
) = graph.connected_components()
```
## Diameter
The following is an implementation of [On computing the diameter of real-world undirected graphs](https://who.rocq.inria.fr/Laurent.Viennot/road/papers/ifub.pdf).
```
%%time
diameter = graph.get_diameter(ignore_infinity=True)
```
Note that most properties that boil down to a single value once computed are stored in a cache structure, so recomputing the diameter once it is done takes a significant smaller time.
```
%%time
diameter = graph.get_diameter(ignore_infinity=True)
```
## Clustering coefficient and triangles
This is an implementation of [Faster Clustering Coefficient Using Vertex Covers](https://davidbader.net/publication/2013-g-ba/2013-g-ba.pdf), proving the average clustering coefficient, the total number of triangles and the number of triangles per node.
```
%%time
graph.get_number_of_triangles()
%%time
graph.get_number_of_triangles_per_node()
%%time
graph.get_average_clustering_coefficient()
%%time
graph.get_clustering_coefficient_per_node()
```
| github_jupyter |
```
!pip install --upgrade tables
!pip install eli5
!pip install xgboost
import pandas as pd
import numpy as np
from sklearn.dummy import DummyRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
import xgboost as xgb
from sklearn.metrics import mean_absolute_error as mae
from sklearn.model_selection import cross_val_score, KFold
import eli5
from eli5.sklearn import PermutationImportance
cd "/content/drive/My Drive/Colab Notebooks/matrix/matrix_two/dw_matrix_car/"
df = pd.read_hdf('data/car.h5')
df.shape
#feat=dynamiczna nazwa poszczególnej kolumny
SUFFIX_CAT = '__cat'
for feat in df.columns:
if isinstance(df[feat][0],list):continue #jeśli wartości jesst listą to pomiń\
factorized_values=df[feat].factorize()[0]
if SUFFIX_CAT in feat:
df[feat]=factorized_values
else:
df[feat + SUFFIX_CAT] = factorized_values
cat_feats=[x for x in df.columns if SUFFIX_CAT in x]
cat_feats=[x for x in cat_feats if 'price' not in x]
len(cat_feats)
x = df[cat_feats].values
y=df['price_value'].values
model= DecisionTreeRegressor(max_depth=5)
scores = cross_val_score(model, x, y, cv=3, scoring='neg_mean_absolute_error')
np.mean(scores), np.std(scores)
def run_model(model, feats):
x = df[feats].values
y=df['price_value'].values
scores = cross_val_score(model, x, y, cv=3, scoring='neg_mean_absolute_error')
return np.mean(scores), np.std(scores)
run_model( DecisionTreeRegressor(max_depth=5), cat_feats)
```
## random forest
```
model= RandomForestRegressor(max_depth = 5, n_estimators=50, random_state=0 )
run_model(model, cat_feats)
```
##xgboost
```
xgb_param={
'max_depth': 5,
'n_estimators': 50,
'learning_rate': 0.1,
'seed': 0
}
model = xgb.XGBRegressor(**xgb_param)
run_model(model, cat_feats)
xgb_param={
'max_depth': 5,
'n_estimators': 50,
'learning_rate': 0.1,
'seed': 0
}
m = xgb.XGBRegressor(**xgb_param)
m.fit(x,y)
imp=PermutationImportance(m, random_state=0).fit(x,y)
eli5.show_weights(imp, feature_names=cat_feats)
feats=['param_napęd__cat',
'param_rok-produkcji__cat',
'param_stan__cat',
'param_skrzynia-biegów__cat',
'param_faktura-vat__cat',
'param_moc__cat',
'param_marka-pojazdu__cat',
'feature_kamera-cofania__cat',
'param_typ__cat',
'param_pojemność-skokowa__cat',
'seller_name__cat',
'feature_wspomaganie-kierownicy__cat',
'param_model-pojazdu__cat',
'param_wersja__cat',
'param_kod-silnika__cat',
'feature_system-start-stop__cat',
'feature_asystent-pasa-ruchu__cat',
'feature_czujniki-parkowania-przednie__cat',
'feature_łopatki-zmiany-biegów__cat',
'feature_regulowane-zawieszenie__cat']
len(feats)
xgb_param={
'max_depth': 5,
'n_estimators': 50,
'learning_rate': 0.1,
'seed': 0
}
model = xgb.XGBRegressor(**xgb_param)
run_model(model, feats)
df['param_rok-produkcji']=df['param_rok-produkcji'].map(lambda x: -1 if str(x) =='None' else int(x))
feats=['param_napęd__cat',
'param_rok-produkcji',
'param_stan__cat',
'param_skrzynia-biegów__cat',
'param_faktura-vat__cat',
'param_moc__cat',
'param_marka-pojazdu__cat',
'feature_kamera-cofania__cat',
'param_typ__cat',
'param_pojemność-skokowa__cat',
'seller_name__cat',
'feature_wspomaganie-kierownicy__cat',
'param_model-pojazdu__cat',
'param_wersja__cat',
'param_kod-silnika__cat',
'feature_system-start-stop__cat',
'feature_asystent-pasa-ruchu__cat',
'feature_czujniki-parkowania-przednie__cat',
'feature_łopatki-zmiany-biegów__cat',
'feature_regulowane-zawieszenie__cat']
xgb_param={
'max_depth': 5,
'n_estimators': 50,
'learning_rate': 0.1,
'seed': 0
}
model = xgb.XGBRegressor(**xgb_param)
run_model(model, feats)
df['param_moc']=df['param_moc'].map(lambda x: -1 if str(x) =='None' else int(x.split(' ')[0]))
df['param_rok-produkcji']=df['param_rok-produkcji'].map(lambda x: -1 if str(x) =='None' else int(x))
feats=['param_napęd__cat',
'param_rok-produkcji',
'param_stan__cat',
'param_skrzynia-biegów__cat',
'param_faktura-vat__cat',
'param_moc',
'param_marka-pojazdu__cat',
'feature_kamera-cofania__cat',
'param_typ__cat',
'param_pojemność-skokowa__cat',
'seller_name__cat',
'feature_wspomaganie-kierownicy__cat',
'param_model-pojazdu__cat',
'param_wersja__cat',
'param_kod-silnika__cat',
'feature_system-start-stop__cat',
'feature_asystent-pasa-ruchu__cat',
'feature_czujniki-parkowania-przednie__cat',
'feature_łopatki-zmiany-biegów__cat',
'feature_regulowane-zawieszenie__cat']
xgb_param={
'max_depth': 5,
'n_estimators': 50,
'learning_rate': 0.1,
'seed': 0
}
model = xgb.XGBRegressor(**xgb_param)
run_model(model, feats)
df['param_pojemność-skokowa']=df['param_pojemność-skokowa'].map(lambda x: -1 if str(x) =='None' else int(str(x).split('cm')[0].replace(' ', '')) )
feats=['param_napęd__cat',
'param_rok-produkcji',
'param_stan__cat',
'param_skrzynia-biegów__cat',
'param_faktura-vat__cat',
'param_moc',
'param_marka-pojazdu__cat',
'feature_kamera-cofania__cat',
'param_typ__cat',
'param_pojemność-skokowa',
'seller_name__cat',
'feature_wspomaganie-kierownicy__cat',
'param_model-pojazdu__cat',
'param_wersja__cat',
'param_kod-silnika__cat',
'feature_system-start-stop__cat',
'feature_asystent-pasa-ruchu__cat',
'feature_czujniki-parkowania-przednie__cat',
'feature_łopatki-zmiany-biegów__cat',
'feature_regulowane-zawieszenie__cat']
xgb_param={
'max_depth': 5,
'n_estimators': 50,
'learning_rate': 0.1,
'seed': 0
}
model = xgb.XGBRegressor(**xgb_param)
run_model(model, feats)
```
| github_jupyter |
# Power Law Transformation
Normally the quality of an image is improved by enhancing contrast and sharpness.
Power law transformations or piece-wise linear transformation functions require lot of user input. In the former case one has to choose the exponent
appearing in the transformation function, while in the latter case one has to choose the slopes
and ranges of the straight lines which form the transformation function.
The power-law transformation is usually defined as
s = cr^γ
where s and r are the gray levels of the pixels in the output and the input images, respectively and
c is a constant.
Maximum contrast stretching occurs by choosing the
value of γ for which the transformation function has the maximum slope at r = rmax.
That is, if m is the slope of the transformation function, then we should find the value of γ ,
which results in the maximum value of m at r = rmax.
Given the value of rmax, which corresponds to the peak in the histogram, we can determine the corresponding value of the exponent which would maximize the extent of the contrast
stretching.
```
from IPython.display import Image
PATH = "/Users/KIIT/Downloads/"
Image(filename = PATH + "powerlaw.png", width=400, height=400)
import cv2
import glob
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
files = glob.glob ("C:/DATA/gaussian_filtered_images/gaussian_filtered_images/Mild/*.png") #reading files from te directory
for myFile in files:
img = cv2.imread(myFile,1)
img = img.astype('float32')
img = img/255.0
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.pow(img,1.5) # Power law Trnasformation with γ=1.5
img = img*255.0
img = img.astype('uint8')
img = Image.fromarray(img)
img.save("C:/DATA1/gaussian_filtered_images/gaussian_filtered_images/Mild/"+str(i)+".png") #saving the transformed image to anther directory
i=i+1
plt.imshow(img)
files = glob.glob ("C:/DATA/gaussian_filtered_images/gaussian_filtered_images/Moderate/*.png")
for myFile in files:
img = cv2.imread(myFile,1)
img = img.astype('float32')
img = img/255.0
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.pow(img,1.5)
img = img*255.0
img = img.astype('uint8')
img = Image.fromarray(img)
img.save("C:/DATA1/gaussian_filtered_images/gaussian_filtered_images/Moderate/"+str(i)+".png")
i=i+1
files = glob.glob ("C:/DATA/gaussian_filtered_images/gaussian_filtered_images/No_DR/*.png")
for myFile in files:
img = cv2.imread(myFile,1)
img = img.astype('float32')
img = img/255.0
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.pow(img,1.5)
img = img*255.0
img = img.astype('uint8')
img = Image.fromarray(img)
img.save("C:/DATA1/gaussian_filtered_images/gaussian_filtered_images/No_DR/"+str(i)+".png")
i=i+1
files = glob.glob ("C:/DATA/gaussian_filtered_images/gaussian_filtered_images/Proliferate_DR/*.png")
for myFile in files:
img = cv2.imread(myFile,1)
img = img.astype('float32')
img = img/255.0
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.pow(img,1.5)
img = img*255.0
img = img.astype('uint8')
img = Image.fromarray(img)
img.save("C:/DATA1/gaussian_filtered_images/gaussian_filtered_images/Proliferate_DR/"+str(i)+".png")
i=i+1
files = glob.glob ("C:/DATA/gaussian_filtered_images/gaussian_filtered_images/Severe/*.png")
for myFile in files:
img = cv2.imread(myFile,1)
img = img.astype('float32')
img = img/255.0
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.pow(img,1.5)
img = img*255.0
img = img.astype('uint8')
img = Image.fromarray(img)
img.save("C:/DATA1/gaussian_filtered_images/gaussian_filtered_images/Severe/"+str(i)+".png")
i=i+1
```
| github_jupyter |
```
%matplotlib inline
import xarray as xr
import os
import pandas as pd
import numpy as np
import skdownscale
import dask
import dask.array as da
import dask.distributed as dd
import rhg_compute_tools.kubernetes as rhgk
from utils import _convert_lons, _remove_leap_days, _convert_ds_longitude
from regridding import apply_weights
import intake
import xesmf as xe
import warnings
warnings.filterwarnings("ignore")
# output directory
write_direc = '/gcs/rhg-data/climate/downscaled/workdir'
```
This notebook implements a scaling test for bias correction, using the BCSDTemperature model from `scikit-downscale`, with the daily BCSD bias correction method as implemented in the NASA-NEX dataset.
Datasets used include a CMIP6 model from a historical run (`GISS-E2-1-G` from NASA) and GMFD (obs). Historical/training period is taken as 1980-1982, and the future/predict period is 1990-1991.
GMFD is coarsened to the NASA `GISS-E2-1-G` grid for this bias correction test.
Note that the purpose of this notebook is intended to allow us to get a better estimate of timing for global daily bias correction. Future work will build on this notebook to:
- replace GMFD with ERA5
- combine this notebook with `SD_prototype.ipynb`, along with NASA-NEX data and a corresponding CMIP5 model, and over a limited domain, to test our implementation of BCSD against NASA-NEX for a limited domain. That notebook will be used as a prototype for our downscaling pipeline and can be modified to become a system test for the pipeline (1-3 gridcells for CI/CD, limited domain for science testing).
This notebook was also used as a resource and checkpoint for this workflow: https://github.com/jhamman/scikit-downscale/blob/ecahm2020/examples/2020ECAHM-scikit-downscale.ipynb
```
# client, cluster = rhgk.get_standard_cluster(extra_pip_packages="git+https://github.com/dgergel/xsd.git@feature/implement_daily_bcsd")
client, cluster = rhgk.get_standard_cluster(extra_pip_packages="git+https://github.com/jhamman/scikit-downscale.git")
cluster
cluster.scale(40)
'''a = da.ones((1000, 1000, 1000))
a.mean().compute()'''
from skdownscale.pointwise_models import PointWiseDownscaler, BcsdTemperature
train_slice = slice('1980', '1989') # train time range
holdout_slice = slice('1990', '2000') # prediction time range
# client.get_versions(check=True)
# use GMFD as standin for ERA-5
tmax_obs = xr.open_mfdataset(os.path.join('/gcs/rhg-data/climate/source_data/GMFD/tmax',
'tmax_0p25_daily_198*'), concat_dim='time', combine='nested',
parallel=True).squeeze(drop=True).rename({'latitude': 'lat', 'longitude': 'lon'})
'''tmax_obs = xr.open_dataset(os.path.join('/gcs/rhg-data/climate/source_data/GMFD/tmax',
'tmax_0p25_daily_1980-1980.nc')).rename({'latitude': 'lat', 'longitude': 'lon'})'''
# standardize longitudes
tmax_obs = _convert_ds_longitude(tmax_obs, lon_name='lon')
# remove leap days
tmax_obs = _remove_leap_days(tmax_obs)
obs_subset = tmax_obs.sel(time=train_slice)
```
get some CMIP6 data
```
# search the cmip6 catalog
col = intake.open_esm_datastore("https://storage.googleapis.com/cmip6/pangeo-cmip6.json")
cat = col.search(experiment_id=['historical', 'ssp585'], table_id='day', variable_id='tasmax',
grid_label='gn')
# cat['CMIP.NASA-GISS.GISS-E2-1-G.historical.day.gn']
# access the data and do some cleanup
ds_model = cat['CMIP.NASA-GISS.GISS-E2-1-G.historical.day.gn'].to_dask(
).isel(member_id=0).squeeze(drop=True).drop(['height', 'lat_bnds', 'lon_bnds', 'time_bnds',
'member_id'])
ds_model.lon.values[ds_model.lon.values > 180] -= 360
ds_model = ds_model.roll(lon=72, roll_coords=True)
```
regrid obs to model resolution
```
# first rechunk in space for xESMF
chunks = {'lat': len(obs_subset.lat), 'lon': len(obs_subset.lon), 'time': 100}
obs_subset = obs_subset.chunk(chunks)
%%time
obs_to_mod_weights = os.path.join(write_direc, 'bias_correction_bilinear_weights_new.nc')
regridder_obs_to_mod = xe.Regridder(obs_subset.isel(time=0, drop=True),
ds_model.isel(time=0, drop=True),
'bilinear',
filename=obs_to_mod_weights,
reuse_weights=True)
obs_subset_modres_lazy = xr.map_blocks(apply_weights, regridder_obs_to_mod,
args=[tmax_obs['tmax']])
obs_subset_modres = obs_subset_modres_lazy.compute()
```
### subset datasets to get ready for bias correcting
```
chunks = {'lat': 10, 'lon': 10, 'time': -1}
train_subset = ds_model['tasmax'].sel(time=train_slice)
train_subset['time'] = train_subset.indexes['time'].to_datetimeindex()
train_subset = train_subset.resample(time='1d').mean().load(scheduler='threads').chunk(chunks)
holdout_subset = ds_model['tasmax'].sel(time=holdout_slice)
holdout_subset['time'] = holdout_subset.indexes['time'].to_datetimeindex()
holdout_subset = holdout_subset.resample(time='1d').mean().load(scheduler='threads').chunk(chunks)
```
### fit BcsdTemperature models at each x/y point in domain using the `PointwiseDownscaler` with the `daily_nasa-nex` option
```
%%time
# model = PointWiseDownscaler(BcsdTemperature(return_anoms=False, time_grouper='daily_nasa-nex'))
model = PointWiseDownscaler(BcsdTemperature(return_anoms=False))
model = BcsdTemperature(return_anoms=False)
# remove leap days from model data
train_subset_noleap = _remove_leap_days(train_subset)
holdout_subset_noleap = _remove_leap_days(holdout_subset)
# chunk datasets
train_subset_noleap = train_subset_noleap.chunk(chunks)
holdout_subset_noleap = holdout_subset_noleap.chunk(chunks)
obs_subset_modres = obs_subset_modres.chunk(chunks)
%%time
model.fit(train_subset_noleap, obs_subset_modres)
model
display(model, model._models)
%%time
predicted = model.predict(holdout_subset_noleap).load()
predicted.isel(time=0).plot(vmin=250, vmax=325)
predicted.sel(lat=47, lon=-122, method='nearest').plot()
```
### save data
```
ds_predicted = predicted.to_dataset(name='tmax')
ds_new_attrs = {"file description": "daily bias correction test for 1980s, output from global bias correction scaling test",
"author": "Diana Gergel", "contact": "dgergel@rhg.com"}
ds_predicted.attrs.update(ds_new_attrs)
ds_predicted.to_netcdf(os.path.join(write_direc, 'global_bias_corrected_tenyears.nc'))
```
| github_jupyter |
# Jupyter Example 5 for HERMES: Neutrinos
```
from pyhermes import *
from pyhermes.units import PeV, TeV, GeV, mbarn, kpc, pc, deg, rad
import astropy.units as u
import numpy as np
import healpy
import matplotlib.pyplot as plt
```
HEMRES has available two cross-section modules for $pp \rightarrow \nu$:
* one built on top of cparamlib: Kamae et al. 2006
* one based on Kelner-Aharonian parametrization
```
kamae06 = interactions.Kamae06Neutrino()
kelahar = interactions.KelnerAharonianNeutrino()
E_neutrino_range = np.logspace(0,6,100)*GeV
E_proton_list = [10*GeV, 100*GeV, 1*TeV, 100*TeV, 1*PeV]
diff_sigma = lambda model, E_proton: [
E_neutrino*model.getDiffCrossSection(E_proton, E_neutrino)/mbarn
for E_neutrino in E_neutrino_range
]
diff_sigma_kamae06 = lambda E_proton: diff_sigma(kamae06, E_proton)
diff_sigma_kelahar = lambda E_proton: diff_sigma(kelahar, E_proton)
colors = ['tab:brown', 'tab:red', 'tab:green', 'tab:blue', 'tab:orange']
for E_proton, c in zip(E_proton_list, colors):
plt.loglog(E_neutrino_range/GeV, diff_sigma_kamae06(E_proton),
ls='-', color=c, label="{}".format(E_proton.toAstroPy().to('TeV').round(2)))
plt.loglog(E_neutrino_range/GeV, diff_sigma_kelahar(E_proton),
ls='--', color=c)
plt.ylim(top=1e3, bottom=1e-2)
plt.title("Kamae06 (solid) and K&A (dashed) for a list of $E_p$")
plt.xlabel(r"$E_\nu$ / GeV")
plt.ylabel(r"$E_\nu\, \mathrm{d}\sigma_{pp \rightarrow \nu} / \mathrm{d} E_\nu$ [mbarn]")
_ = plt.legend(loc="upper right", frameon=False)
def integrate_template(integrator, nside):
integrator.setupCacheTable(60, 60, 12)
sun_pos = Vector3QLength(8.0*kpc, 0*pc, 0*pc)
integrator.setSunPosition(sun_pos)
mask_edges = ([5*deg, 0*deg], [-5*deg, 180*deg])
mask = RectangularWindow(*mask_edges)
skymap_range = GammaSkymapRange(nside, 0.05*TeV, 1e4*TeV, 20)
skymap_range.setIntegrator(integrator)
skymap_range.setMask(mask)
skymap_range.compute()
return skymap_range
def integrate_neutrino(cosmicrays, gas, crosssection):
nside = 256
integrator = PiZeroIntegrator(cosmicrays, gas, crosssection)
return integrate_template(integrator, nside)
neutral_gas_HI = neutralgas.RingModel(neutralgas.RingType.HI)
proton = cosmicrays.Dragon2D(Proton)
skymap_range_neutrino_HI_kamae06 = integrate_neutrino(proton, neutral_gas_HI, kamae06)
skymap_range_neutrino_HI_kelahar = integrate_neutrino(proton, neutral_gas_HI, kelahar)
#use_units = skymap_range_HI[0].getUnits() # default units for GammaSkymap (GeV^-1 m^-2 s^-1 sr^-1)
use_units = "GeV^-1 cm^-2 s^-1 sr^-1" # override default
skymap_units = u.Quantity(1, use_units)
base_units = skymap_units.unit.si.scale
def calc_mean_flux(skymap_range):
energies = np.array([float(s.getEnergy()/GeV) for s in skymap_range])
fluxes = np.array([s.getMean() for s in skymap_range]) / base_units
return energies, fluxes
def plot_spectrum(skymap_range, label, style):
energies, fluxes = calc_mean_flux(skymap_range)
plt.plot(energies, fluxes*energies**2, style, label=label)
def plot_total_spectrum(list_of_skymap_range, label, style):
fluxes = QDifferentialIntensity(0)
for skymap_range in list_of_skymap_range:
energies, fluxes_i = calc_mean_flux(skymap_range)
fluxes = fluxes + fluxes_i
plt.plot(energies, fluxes*energies**2, style, label=label)
fig, ax = plt.subplots()
plot_spectrum(skymap_range_neutrino_HI_kamae06, r'$\nu $ @ p + HI (Kamae06)', '-')
plot_spectrum(skymap_range_neutrino_HI_kelahar, r'$\nu $ @ p + HI (K&A)', '--')
plt.title("Neutrinos from diffuse emission (Fornieri20, Remy18)\n $|b| < 5^\degree$, $0^\degree \leq l \leq 180^\degree$")
plt.legend(loc="lower left")
plt.xlabel(r"$E_\nu$ / GeV")
plt.ylabel(r"$E_\nu\, \mathrm{d}\Phi_\gamma / \mathrm{d} E_\gamma$ / " + (skymap_units*u.GeV**2).unit.to_string(format='latex_inline'))
ax.tick_params(which='minor', direction='in', axis='both', bottom=True, top=True, left=True, right=True, length=3)
ax.tick_params(which='major', direction='in', axis='both', bottom=True, top=True, left=True, right=True, length=5)
plt.xscale("log")
plt.yscale("log")
plt.ylim(10**(-9), 10**(-6))
plt.xlim(10**(2), 10**(6))
#plt.savefig("img/neutrinos-from-diffuse-emission-spectrum-180.pdf", dpi=150)
```
| github_jupyter |
# Regression Week 1: Simple Linear Regression
In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will:
* Use Turi Create SArray and SFrame functions to compute important summary statistics
* Write a function to compute the Simple Linear Regression weights using the closed form solution
* Write a function to make predictions of the output given the input feature
* Turn the regression around to predict the input given the output
* Compare two different models for predicting house prices
In this notebook you will be provided with some already complete code as well as some code that you should complete yourself in order to answer quiz questions. The code we provide to complte is optional and is there to assist you with solving the problems but feel free to ignore the helper code and write your own.
# Fire up Turi Create
```
import turicreate as tc
```
# Load house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
```
sales = tc.SFrame('home_data.sframe/')
sales.head(5)
```
# Split data into training and testing
We use seed=0 so that everyone running this notebook gets the same results. In practice, you may set a random seed (or let Turi Create pick a random seed for you).
```
train_data,test_data = sales.random_split(0.8, seed=0)
```
# Useful SFrame summary functions
In order to make use of the closed form solution as well as take advantage of turi create's built in functions we will review some important ones. In particular:
* Computing the sum of an SArray
* Computing the arithmetic average (mean) of an SArray
* multiplying SArrays by constants
* multiplying SArrays by other SArrays
```
# Let's compute the mean of the House Prices in King County in 2 different ways.
prices = sales['price'] # extract the price column of the sales SFrame -- this is now an SArray
# recall that the arithmetic average (the mean) is the sum of the prices divided by the total number of houses:
sum_prices = prices.sum()
num_houses = len(prices) # when prices is an SArray len() returns its length
avg_price_1 = sum_prices/num_houses
avg_price_2 = prices.mean() # if you just want the average, the .mean() function
print(f'average price via method 1: {avg_price_1:.2f}')
print(f'average price via method 2: {avg_price_2:.2f}')
```
As we see we get the same answer both ways
```
# if we want to multiply every price by 0.5 it's a simple as:
half_prices = 0.5 * prices
# Let's compute the sum of squares of price. We can multiply two SArrays of the same length elementwise also with *
prices_squared = prices * prices
sum_prices_squared = prices_squared.sum() # price_squared is an SArray of the squares and we want to add them up.
print(f'the sum of price squared is: {sum_prices_squared}')
```
Aside: The python notation x.xxe+yy means x.xx \* 10^(yy). e.g 100 = 10^2 = 1*10^2 = 1e2
# Build a generic simple linear regression function
Armed with these SArray functions we can use the closed form solution found from lecture to compute the slope and intercept for a simple linear regression on observations stored as SArrays: input_feature, output.
Complete the following function (or write your own) to compute the simple linear regression slope and intercept:
```
def simple_linear_regression(input_feature, output):
# compute the sum of input_feature and output
sum_input = input_feature.sum()
sum_output = output.sum()
# compute the product of the output and the input_feature and its sum
prod_input_output = input_feature * output
sum_prod_input_output = prod_input_output.sum()
# compute the squared value of the input_feature and its sum
squared_input_feature = input_feature * input_feature
sum_squared_input_feature = squared_input_feature.sum()
# use the formula for the slope
slope = (sum_prod_input_output - (sum_input * sum_output) / len(output)) \
/ (sum_squared_input_feature - (sum_input * sum_input) / len(output))
# use the formula for the intercept
intercept = sum_output / len(output) - slope * sum_input / len(output)
return (intercept, slope)
```
We can test that our function works by passing it something where we know the answer. In particular we can generate a feature and then put the output exactly on a line: output = 1 + 1\*input_feature then we know both our slope and intercept should be 1
```
test_feature = tc.SArray(range(5))
test_output = tc.SArray(1 + 1 * test_feature)
test_intercept, test_slope = simple_linear_regression(test_feature, test_output)
print(f'Intercept: {test_intercept}')
print(f'Slope: {test_slope}')
```
Now that we know it works let's build a regression model for predicting price based on sqft_living. Rembember that we train on train_data!
```
sqft_intercept, sqft_slope = simple_linear_regression(train_data['sqft_living'], train_data['price'])
print(f'Intercept: {sqft_intercept}')
print(f'Slope: {sqft_slope}')
```
# Predicting Values
Now that we have the model parameters: intercept & slope we can make predictions. Using SArrays it's easy to multiply an SArray by a constant and add a constant value. Complete the following function to return the predicted output given the input_feature, slope and intercept:
```
def get_regression_predictions(input_feature, intercept, slope):
# calculate the predicted values:
predicted_values = slope * input_feature + intercept
return predicted_values
```
Now that we can calculate a prediction given the slope and intercept let's make a prediction. Use (or alter) the following to find out the estimated price for a house with 2650 squarefeet according to the squarefeet model we estiamted above.
**Quiz Question: Using your Slope and Intercept from (4), What is the predicted price for a house with 2650 sqft?**
```
my_house_sqft = 2650
estimated_price = get_regression_predictions(my_house_sqft, sqft_intercept, sqft_slope)
print(f'The estimated price for a house with {my_house_sqft} squarefeet is ${estimated_price:.2f}')
```
# Residual Sum of Squares
Now that we have a model and can make predictions let's evaluate our model using Residual Sum of Squares (RSS). Recall that RSS is the sum of the squares of the residuals and the residuals is just a fancy word for the difference between the predicted output and the true output.
Complete the following (or write your own) function to compute the RSS of a simple linear regression model given the input_feature, output, intercept and slope:
```
def get_residual_sum_of_squares(input_feature, output, intercept, slope):
# First get the predictions
pred_output = input_feature * slope + intercept
# then compute the residuals (since we are squaring it doesn't matter which order you subtract)
residuals = output - pred_output
# square the residuals and add them up
square_residuals = residuals * residuals
RSS = square_residuals.sum()
return(RSS)
```
Let's test our get_residual_sum_of_squares function by applying it to the test model where the data lie exactly on a line. Since they lie exactly on a line the residual sum of squares should be zero!
```
print(get_residual_sum_of_squares(test_feature, test_output, test_intercept, test_slope)) # should be 0.0
```
Now use your function to calculate the RSS on training data from the squarefeet model calculated above.
**Quiz Question: According to this function and the slope and intercept from the squarefeet model What is the RSS for the simple linear regression using squarefeet to predict prices on TRAINING data?**
```
rss_prices_on_sqft = get_residual_sum_of_squares(train_data['sqft_living'], train_data['price'],
sqft_intercept, sqft_slope)
print(f'The RSS of predicting Prices based on Square Feet is : {rss_prices_on_sqft:e}')
```
# Predict the squarefeet given price
What if we want to predict the squarefoot given the price? Since we have an equation y = a + b\*x we can solve the function for x. So that if we have the intercept (a) and the slope (b) and the price (y) we can solve for the estimated squarefeet (x).
Complete the following function to compute the inverse regression estimate, i.e. predict the input_feature given the output.
```
def inverse_regression_predictions(output, intercept, slope):
# solve output = intercept + slope*input_feature for input_feature. Use this equation to compute the inverse predictions:
estimated_feature = (output - intercept) / slope
return estimated_feature
```
Now that we have a function to compute the squarefeet given the price from our simple regression model let's see how big we might expect a house that costs $800,000 to be.
**Quiz Question: According to this function and the regression slope and intercept from (3) what is the estimated square-feet for a house costing $800,000?**
```
my_house_price = 800000
estimated_squarefeet = inverse_regression_predictions(my_house_price, sqft_intercept, sqft_slope)
print(f'The estimated squarefeet for a house worth ${my_house_price} is {estimated_squarefeet:.2f}')
```
# New Model: estimate prices from bedrooms
We have made one model for predicting house prices using squarefeet, but there are many other features in the sales SFrame.
Use your simple linear regression function to estimate the regression parameters from predicting Prices based on number of bedrooms. Use the training data!
```
# Estimate the slope and intercept for predicting 'price' based on 'bedrooms'
sqft_intercept_bed, sqft_slope_bed = simple_linear_regression(train_data['bedrooms'], train_data['price'])
print(f'Intercept: {sqft_intercept}')
print(f'Slope: {sqft_slope}')
```
# Test your Linear Regression Algorithm
Now we have two models for predicting the price of a house. How do we know which one is better? Calculate the RSS on the TEST data (remember this data wasn't involved in learning the model). Compute the RSS from predicting prices using bedrooms and from predicting prices using squarefeet.
**Quiz Question: Which model (square feet or bedrooms) has lowest RSS on TEST data? Think about why this might be the case.**
```
# Compute RSS when using bedrooms on TEST data:
rss_prices_on_bed_test = get_residual_sum_of_squares(test_data['bedrooms'], test_data['price'],
sqft_intercept, sqft_slope)
print(f'The RSS of predicting Prices based on Bedrooms is : {rss_prices_on_bed_test:e}')
# Compute RSS when using squarefeet on TEST data:
rss_prices_on_sqft_test = get_residual_sum_of_squares(test_data['sqft_living'], test_data['price'],
sqft_intercept, sqft_slope)
print(f'The RSS of predicting Prices based on Square Feet is : {rss_prices_on_sqft_test:e}')
```
| github_jupyter |
```
from opentrons import simulate
from opentrons.drivers.rpi_drivers import gpio
import time
import math
ctx = simulate.get_protocol_api('2.1')
# Metadata
metadata = {
'protocolName': 'S3 Station C Version 1',
'author': 'Nick <protocols@opentrons.com>, Sara <smonzon@isciii.es>, Miguel <mjuliam@isciii.es>',
'source': 'Custom Protocol Request',
'apiLevel': '2.1'
}
# Parameters to adapt the protocol
NUM_SAMPLES = 96
MM_LABWARE = 'opentrons aluminum block'
PCR_LABWARE = 'opentrons aluminum nest plate'
ELUTION_LABWARE = 'opentrons aluminum biorad plate'
MMTUBE_LABWARE = '2ml tubes'
PREPARE_MASTERMIX = True
MM_TYPE = 'MM1'
TRANSFER_MASTERMIX = False
TRANSFER_SAMPLES = False
# Calculated variables
if MM_TYPE == 'mm3':
VOLUME_MMIX = 15
else:
VOLUME_MMIX = 20
# Constants
MM_LW_DICT = {
'opentrons plastic block': 'opentrons_24_tuberack_generic_2ml_screwcap',
'opentrons aluminum block': 'opentrons_24_aluminumblock_generic_2ml_screwcap',
'covidwarriors aluminum block': 'covidwarriors_aluminumblock_24_screwcap_2000ul'
}
PCR_LW_DICT = {
'opentrons aluminum biorad plate': 'opentrons_96_aluminumblock_biorad_wellplate_200ul',
'opentrons aluminum nest plate': 'opentrons_96_aluminumblock_nest_wellplate_100ul',
'opentrons aluminum strip short': 'opentrons_aluminumblock_96_pcrstrips_100ul',
'covidwarriors aluminum biorad plate': 'covidwarriors_aluminumblock_96_bioradwellplate_200ul',
'covidwarriors aluminum biorad strip short': 'covidwarriors_aluminumblock_96_bioradwellplate_pcrstrips_100ul'
}
EL_LW_DICT = {
# tubes
'opentrons plastic 2ml tubes': 'opentrons_24_tuberack_generic_2ml_screwcap',
'opentrons plastic 1.5ml tubes': 'opentrons_24_tuberack_nest_1.5ml_screwcap',
'opentrons aluminum 2ml tubes': 'opentrons_24_aluminumblock_generic_2ml_screwcap',
'opentrons aluminum 1.5ml tubes': 'opentrons_24_aluminumblock_nest_1.5ml_screwcap',
'covidwarriors aluminum 2ml tubes': 'covidwarriors_aluminumblock_24_screwcap_2000ul',
'covidwarriors aluminum 1.5ml tubes': 'covidwarriors_aluminumblock_24_screwcap_2000ul',
# PCR plate
'opentrons aluminum biorad plate': 'opentrons_96_aluminumblock_biorad_wellplate_200ul',
'opentrons aluminum nest plate': 'opentrons_96_aluminumblock_nest_wellplate_100ul',
'covidwarriors aluminum biorad plate': 'covidwarriors_aluminumblock_96_bioradwellplate_200ul',
# Strips
#'large strips': 'opentrons_96_aluminumblock_generic_pcr_strip_200ul',
#'short strips': 'opentrons_96_aluminumblock_generic_pcr_strip_200ul',
'opentrons aluminum strip alpha': 'opentrons_aluminumblock_96_pcrstripsalpha_200ul',
'opentrons aluminum strip short': 'opentrons_aluminumblock_96_pcrstrips_100ul',
'covidwarriors aluminum biorad strip alpha': 'covidwarriors_aluminumblock_96_bioradwellplate_pcrstripsalpha_200ul',
'covidwarriors aluminum biorad strip short': 'covidwarriors_aluminumblock_96_bioradwellplate_pcrstrips_100ul'
}
MMTUBE_LW_DICT = {
# Radius of each possible tube
'2ml tubes': 4
}
# Function definitions
def check_door():
return gpio.read_window_switches()
def confirm_door_is_closed(ctx):
#Check if door is opened
if check_door() == False:
#Set light color to red and pause
gpio.set_button_light(1,0,0)
ctx.pause(f"Please, close the door")
time.sleep(3)
confirm_door_is_closed(ctx)
else:
#Set light color to green
gpio.set_button_light(0,1,0)
def finish_run():
#Set light color to blue
gpio.set_button_light(0,0,1)
def get_source_dest_coordinates(ELUTION_LABWARE,source_racks, pcr_plate):
if 'strip' in ELUTION_LABWARE:
sources = [
tube
for i, rack in enumerate(source_racks)
for col in [
rack.columns()[c] if i < 2 else rack.columns()[c+1]
for c in [0, 5, 10]
]
for tube in col
][:NUM_SAMPLES]
dests = pcr_plate.wells()[:NUM_SAMPLES]
elif 'plate' in ELUTION_LABWARE:
sources = source_racks.wells()[:NUM_SAMPLES]
dests = pcr_plate.wells()[:NUM_SAMPLES]
else:
sources = [
tube
for rack in source_racks for tube in rack.wells()][:NUM_SAMPLES]
dests = [
well
for v_block in range(2)
for h_block in range(2)
for col in pcr_plate.columns()[6*v_block:6*(v_block+1)]
for well in col[4*h_block:4*(h_block+1)]][:NUM_SAMPLES]
return sources, dests
def get_mm_hight(volume):
# depending on the volume in tube, get mm fluid hight
hight = volume // (3.14 * 3.14 * MMTUBE_LW_DICT[MMTUBE_LABWARE])
hight -= 10
if hight < 5:
return 1
else:
return hight
def homogenize_mm(mm_tube, p300, times=5):
# homogenize mastermix tube a given number of times
p300.pick_up_tip()
volume_hight = get_mm_hight(VOLUME_MMIX)
#p300.mix(5, 200, mm_tube.bottom(5))
for i in range(times):
for j in range(5):
# depending on the number of samples, start at a different hight and move as it aspires
aspirate_hight = volume_hight-(3*j)
if aspirate_hight < 5:
p300.aspirate(40, mm_tube.bottom(1))
else:
p300.aspirate(40, mm_tube.bottom(aspirate_hight))
# empty pipete
p300.dispense(200, mm_tube.bottom(volume_hight))
# clow out before dropping tip
p300.blow_out(mm_tube.top(-2))
p300.drop_tip()
def prepare_mastermix(MM_TYPE, mm_rack, p300, p20):
# setup mastermix coordinates
""" mastermix component maps """
mm1 = {
tube: vol
for tube, vol in zip(
[well for col in mm_rack.columns()[2:5] for well in col][:10],
[2.85, 12.5, 0.4, 1, 1, 0.25, 0.25, 0.5, 0.25, 1]
)
}
mm2 = {
tube: vol
for tube, vol in zip(
[mm_rack.wells_by_name()[well] for well in ['A3', 'C5', 'D5']],
[10, 4, 1]
)
}
mm3 = {
tube: vol
for tube, vol in zip(
[mm_rack.wells_by_name()[well] for well in ['A6', 'B6']],
[13, 2]
)
}
mm_dict = {'MM1': mm1, 'MM2': mm2, 'MM3': mm3}
# create mastermix
mm_tube = mm_rack.wells()[0]
for tube, vol in mm_dict[MM_TYPE].items():
mm_vol = vol*(NUM_SAMPLES+5)
disp_loc = mm_tube.top(-10)
pip = p300 if mm_vol > 20 else p20
pip.pick_up_tip()
#pip.transfer(mm_vol, tube.bottom(0.5), disp_loc, air_gap=2, touch_tip=True, new_tip='never')
air_gap_vol = 5
num_transfers = math.ceil(mm_vol/(200-air_gap_vol))
for i in range(num_transfers):
if i == 0:
transfer_vol = mm_vol % (200-air_gap_vol)
else:
transfer_vol = (200-air_gap_vol)
pip.transfer(transfer_vol, tube.bottom(0.5), disp_loc, air_gap=air_gap_vol, new_tip='never')
pip.blow_out(disp_loc)
pip.aspirate(5, mm_tube.top(2))
pip.drop_tip()
# homogenize mastermix
homogenize_mm(mm_tube, p300)
return mm_tube
def transfer_mastermix(mm_tube, dests, VOLUME_MMIX, p300, p20):
max_trans_per_asp = 8 #230//(VOLUME_MMIX+5)
split_ind = [ind for ind in range(0, NUM_SAMPLES, max_trans_per_asp)]
dest_sets = [dests[split_ind[i]:split_ind[i+1]]
for i in range(len(split_ind)-1)] + [dests[split_ind[-1]:]]
pip = p300 if VOLUME_MMIX >= 20 else p20
pip.pick_up_tip()
# get initial fluid hight to avoid overflowing mm when aspiring
mm_volume = VOLUME_MMIX * NUM_SAMPLES
volume_hight = get_mm_hight(mm_volume)
for set in dest_sets:
# check hight and if it is low enought, aim for the bottom
if volume_hight < 5:
disp_loc = mm_tube.bottom(1)
else:
disp_loc = mm_tube.bottom(volume_hight)
# reclaculate volume hight
mm_volume -= VOLUME_MMIX * max_trans_per_asp
volume_hight = get_mm_hight(mm_volume)
pip.aspirate(4, disp_loc)
pip.distribute(VOLUME_MMIX, disp_loc, [d.bottom(2) for d in set],
air_gap=1, disposal_volume=0, new_tip='never')
pip.blow_out(disp_loc)
pip.drop_tip()
def transfer_samples(ELUTION_LABWARE, sources, dests, p20):
# hight for aspiration has to be different depending if you ar useing tubes or wells
if 'strip' in ELUTION_LABWARE or 'plate' in ELUTION_LABWARE:
hight = 1.5
else:
hight = 1
# transfer
for s, d in zip(sources, dests):
p20.pick_up_tip()
p20.transfer(7, s.bottom(hight), d.bottom(2), air_gap=2, new_tip='never')
#p20.mix(1, 10, d.bottom(2))
#p20.blow_out(d.top(-2))
p20.aspirate(1, d.top(-2))
p20.drop_tip()
# define tips
tips20 = [
ctx.load_labware('opentrons_96_filtertiprack_20ul', slot)
for slot in ['6', '9', '8', '7']
]
tips300 = [ctx.load_labware('opentrons_96_filtertiprack_200ul', '3')]
# define pipettes
p20 = ctx.load_instrument('p20_single_gen2', 'right', tip_racks=tips20)
p300 = ctx.load_instrument('p300_single_gen2', 'left', tip_racks=tips300)
# tempdeck module
tempdeck = ctx.load_module('tempdeck', '10')
#tempdeck.set_temperature(4)
# check mastermix labware type
if MM_LABWARE not in MM_LW_DICT:
raise Exception('Invalid MM_LABWARE. Must be one of the \
following:\nopentrons plastic block\nopentrons aluminum block\ncovidwarriors aluminum block')
# load mastermix labware
mm_rack = ctx.load_labware(
MM_LW_DICT[MM_LABWARE], '11',
MM_LABWARE)
# check pcr plate
if PCR_LABWARE not in PCR_LW_DICT:
raise Exception('Invalid PCR_LABWARE. Must be one of the \
following:\nopentrons aluminum biorad plate\nopentrons aluminum nest plate\nopentrons aluminum strip short\ncovidwarriors aluminum biorad plate\ncovidwarriors aluminum biorad strip short')
# load pcr plate
pcr_plate = tempdeck.load_labware(
PCR_LW_DICT[PCR_LABWARE], 'PCR plate')
# check source (elution) labware type
if ELUTION_LABWARE not in EL_LW_DICT:
raise Exception('Invalid ELUTION_LABWARE. Must be one of the \
following:\nopentrons plastic 2ml tubes\nopentrons plastic 1.5ml tubes\nopentrons aluminum 2ml tubes\nopentrons aluminum 1.5ml tubes\ncovidwarriors aluminum 2ml tubes\ncovidwarriors aluminum 1.5ml tubes\nopentrons aluminum biorad plate\nopentrons aluminum nest plate\ncovidwarriors aluminum biorad plate\nopentrons aluminum strip alpha\nopentrons aluminum strip short\ncovidwarriors aluminum biorad strip alpha\ncovidwarriors aluminum biorad strip short')
# load elution labware
if 'plate' in ELUTION_LABWARE:
source_racks = ctx.load_labware(
EL_LW_DICT[ELUTION_LABWARE], '1',
'RNA elution labware')
else:
source_racks = [
ctx.load_labware(EL_LW_DICT[ELUTION_LABWARE], slot,
'RNA elution labware ' + str(i+1))
for i, slot in enumerate(['4', '1', '5', '2'])
]
# setup sample sources and destinations
sources, dests = get_source_dest_coordinates(ELUTION_LABWARE, source_racks, pcr_plate)
def prepare_mastermix(MM_TYPE, mm_rack, p300, p20):
# setup mastermix coordinates
""" mastermix component maps """
mm1 = {
tube: vol
for tube, vol in zip(
[well for col in mm_rack.columns()[2:5] for well in col][:10],
[2.85, 12.5, 0.4, 1, 1, 0.25, 0.25, 0.5, 0.25, 1]
)
}
mm2 = {
tube: vol
for tube, vol in zip(
[mm_rack.wells_by_name()[well] for well in ['A3', 'C5', 'D5']],
[10, 4, 1]
)
}
mm3 = {
tube: vol
for tube, vol in zip(
[mm_rack.wells_by_name()[well] for well in ['A6', 'B6']],
[13, 2]
)
}
mm_dict = {'MM1': mm1, 'MM2': mm2, 'MM3': mm3}
# create mastermix
mm_tube = mm_rack.wells()[0]
mm_tube_vol = 0
for tube, vol in mm_dict[MM_TYPE].items():
mm_vol = vol*(NUM_SAMPLES+5)
#disp_loc = mm_tube.top(-10)
disp_loc = mm_tube.bottom(5) if mm_vol < 50 else mm_tube.top(-5)
pip = p300 if mm_vol > 20 else p20
#pip.pick_up_tip()
#pip.transfer(mm_vol, tube.bottom(0.5), disp_loc, air_gap=2, touch_tip=True, new_tip='never')
air_gap_vol = 5
num_transfers = math.ceil(mm_vol/(200-air_gap_vol))
#num_transfers = int(mm_vol//(200-air_gap_vol))
print(tube)
print("mmvol:" + str(mm_vol) )
mm_tube_vol = mm_tube_vol + mm_vol
print("Num transfers:" + str(num_transfers))
for i in range(num_transfers):
if(i == 0 ):
transfer_vol = mm_vol % (200-air_gap_vol)
else:
transfer_vol = 200-air_gap_vol
print("Transfer vol:" + str(transfer_vol))
#pip.transfer(transfer_vol, tube.bottom(0.5), disp_loc, air_gap=air_gap_vol, new_tip='never')
#pip.blow_out(disp_loc)
#pip.aspirate(5, mm_tube.top(2))
#pip.drop_tip()
print("Total mm vol:" + str(mm_tube_vol))
#p300.pick_up_tip()
#p300.mix(5, 200, mm_tube.bottom(5))
for i in range(5):
for j in range(5):
disp_loc = -10-(3*i)
#p300.aspirate(40, mm_tube.top(disp_loc))
#p300.dispense(200, mm_tube.top(-22))
#p300.drop_tip()
return mm_tube
mm_tube = prepare_mastermix(MM_TYPE, mm_rack, p300, p20)
def homogenize_mm(mm_tube, p300, times=5):
# homogenize mastermix tube a given number of times
#p300.pick_up_tip()
volume_hight = get_mm_hight(VOLUME_MMIX)
for i in range(times):
for j in range(5):
# depending on the number of samples, start at a different hight and move as it aspires
aspirate_hight = volume_hight-(3*j)
if aspirate_hight < 5:
print("if < 5 aspirate_hight:" + str(aspirate_hight))
#p300.aspirate(40, mm_tube.bottom(1))
else:
print("else aspirate_hight:" + str(aspirate_hight))
#p300.aspirate(40, mm_tube.bottom(aspirate_hight))
# empty pipete
#p300.dispense(200, mm_tube.bottom(volume_hight))
# clow out before dropping tip
#p300.blow_out(mm_tube.top(-2))
#p300.drop_tip()
homogenize_mm(mm_tube, p300)
split_ind = [ind for ind in range(0, 24, 3)]
dest_sets = [dests[split_ind[i]:split_ind[i+1]]
for i in range(len(split_ind)-1)] + [dests[split_ind[-1]:]]
print(range(len(split_ind)-1))
print(split_ind[-1])
print(split_ind)
```
| github_jupyter |
# Project 2 - Forecasting Service Metrics
Authors: Tatiana Barrios, Anisha Anandkrishnan
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf
import os
import seaborn as sn
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn import preprocessing
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.feature_selection import SelectFromModel
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.linear_model import LinearRegression
from sklearn.multioutput import MultiOutputRegressor
from pandas import concat
import seaborn as sns
import scipy.stats as st
from scipy.fft import fft, ifft
from statsmodels.tsa.ar_model import AutoReg
from statsmodels.tsa.seasonal import DecomposeResult
%matplotlib inline
#NMAE function
def nmae_get(y, y_hat):
y_av = np.mean(y)
y_sum = np.sum(np.abs(y - y_hat))
return y_sum/(len(y)*y_av)
#NMAE for h=0:::10
def nmaes_array(df_test, df_pre, h):
nmaes = []
for i in range(0, h+1):
y_predict_i = df_pre.iloc[:, i]
y_test_o = df_test.iloc[:, i].to_numpy()
nmaes.append(nmae_get(y_test_o, y_predict_i))
return nmaes
def future_columns(df, h):
nv = df.shape[1]
original_names = df.columns
col, names = list(), list()
for i in range(0, h+1):
col.append(df.shift(-i))
if i == 0:
names += [('%s(t)' % (original_names[j])) for j in range(nv)]
else:
names += [('%s(t+%d)' % (original_names[j], i)) for j in range(nv)]
concated_ = concat(col, axis=1)
concated_.columns = names
#This might bring errors, but i dont know if its better to drop them or to fill them at this point
concated_.fillna(0, inplace=True)
return concated_
```
# Task III - Time series analysis
1. In this task, we apply traditional univariate time-series analysis methods. This means we only consider the target values y(t) of the trace and do not consider the input values x(t)
2. Outliers elimination. Before applying any method, we remove outliers if there are any. Use one of the methods from project 1 (Advanced) to eliminate the outliers.
```
Y = pd.read_csv('Y.csv')
#Y.index = pd.to_datetime(Y['TimeStamp'])
Y_dropped = Y.drop(labels=["Unnamed: 0", "WritesAvg"], axis=1, inplace=False)
Y_dropped1 = Y.drop(labels=["Unnamed: 0", "TimeStamp", "WritesAvg"], axis=1, inplace=False)
Y_preprocessed = pd.DataFrame()
Y_tmp = preprocessing.StandardScaler().fit_transform(Y_dropped1)
for i, n in enumerate(Y_dropped1):
Y_preprocessed[n] = Y_tmp[:, i]
Y_preprocessed.head()
Y_dropped.head()
print(Y_dropped.shape)
print(Y_preprocessed.shape)
remove = []
for i in Y_preprocessed:
for j in range(len(Y_preprocessed[i])):
if j not in remove and abs(Y_preprocessed[i][j]) > 3.5:
remove.append(j)
Y_clean = Y_dropped.drop(index=remove, axis=0, inplace=False)
print("Number of dropped samples: ", (len(remove)))
%store Y_clean
Y_clean = Y_clean.reset_index()
Y_clean = Y_clean.drop(Y_clean.columns[0], axis=1)
Y_clean.head()
reads = Y_clean['ReadsAvg']
fig, ax1 = plt.subplots(figsize = (10,6), dpi = 100)
mn_point = min(reads)
mx_point = max(reads)
bins = np.arange(mn_point, mx_point + 1, 1)
dens_vals = ax1.hist(reads, density=True, bins=bins, label='Hist')
mn_point, mx_point = plt.xlim()
plt.xlim(mn_point, mx_point)
Y_clean.head()
features_file = 'FedCSIS_X.csv'
targets_file = 'FedCSIS_Y.csv'
directory = 'FedCSIS'
fn1 = os.path.join(directory, features_file)
fn2 = os.path.join(directory, targets_file)
Xfed = pd.read_csv(fn1)
Yfed = pd.read_csv(fn2)
Xfed.info()
Yfed.info()
Yfed.head()
Xfed = Xfed.drop(Xfed.columns[0], axis=1)
Yfed = Yfed.drop(Yfed.columns[0], axis=1)
Yfed.head()
hostdata = Yfed['host1619_/']
#Time series of this plot
fig_, linep_ = plt.subplots(figsize = (10,6), dpi = 100)
linep_ = sn.lineplot(data=hostdata, color='green')
linep_.set(xlabel='Time index', ylabel='host1619')
linep_.set_title("Time series of FedCSIS data")
fig_.savefig('timesDT1.png', dpi=300, bbox_inches='tight')
fig, ax1 = plt.subplots(figsize = (10,6), dpi = 100)
mn_point = min(hostdata)
mx_point = max(hostdata)
bins = np.arange(mn_point, mx_point + 1, 0.1)
dens_vals = ax1.hist(hostdata, density=True, bins=bins, label='Hist')
mn_point, mx_point = plt.xlim()
plt.xlim(mn_point, mx_point)
#Kernel density estimation
kde = st.gaussian_kde(hostdata)
kde_x = np.linspace(mn_point, mx_point, 500)
ax1.plot(kde_x, kde.pdf(kde_x), color='orange', label='Density', linewidth=3.0)
plt.legend(loc="upper right")
plt.xlabel('host1619')
plt.ylabel('Density')
plt.title('Density and histogram for target in FedCSIS data')
fig.savefig('densitytargetfcsis.png', dpi=300, bbox_inches='tight')
Xfed_preprocessed = pd.DataFrame()
Xfed_tmp = preprocessing.StandardScaler().fit_transform(Xfed)
for i, n in enumerate(Xfed):
Xfed_preprocessed[n] = Xfed_tmp[:, i]
Xfed.describe(percentiles=[.25, .95])
#converting Y_dropped to make it of the same form as X_preprocessed
Yfed_new = pd.DataFrame()
Yfed_tmp=Yfed.to_numpy()
for i, n in enumerate(Yfed):
Yfed_new[n] = Yfed_tmp[:, i]
# outlier rejection
remove = []
for i in Xfed_preprocessed:
for j in range(len(Xfed_preprocessed[i])):
if j not in remove and abs(Xfed_preprocessed[i][j]) > 3.8:
remove.append(j)
Xfed_clean = Xfed_preprocessed.drop(labels=remove, axis=0, inplace=False)
Yfed_clean = Yfed_new.drop(labels=remove, axis=0, inplace=False)
print("Number of dropped samples: ", (len(remove)))
%store Xfed_clean
%store Yfed_clean
Xfed_clean.describe(percentiles=[.25, .95])
hostdata_cln = Yfed_clean['host1619_/']
fedcsis_everything = Xfed_clean.join(hostdata_cln)
gen_corr_mat = fedcsis_everything.corr()
print(gen_corr_mat)
#Heatmap of correlation matrix
params = {'legend.fontsize': 'x-large',
'figure.figsize': (12, 12),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
plt.rcParams.update(params)
heatmaplt = sn.heatmap(gen_corr_mat, cmap="YlGnBu")
heatmaplt.set_title('Correlation matrix of FedCSIS data')
plt.show()
fig = heatmaplt.get_figure()
fig.savefig('corrmat_fedcsis.png', dpi=300, bbox_inches='tight')
```
3. The auto-correlation function (ACF) computes the correlation of observations in a time series with respect to lag values. Compute the values of this function for the KTH trace and the FedCSIS trace. For each trace, plot the ACF values (correlogram) in two ways.The first plot shows the lag values in the interval l = 0; :::; 100, the second plot shows in the interval l = 0; :::; 4000. The x-axis of the plots shows the lag values and the y-axis shows the correlation coefficients (Pearson correlation) with values between -1 and 1 for negative and positive correlation, respectively.
```
Y_clean_ = Y_clean.drop(labels=["TimeStamp"], axis=1, inplace=False)
# For the KTH trace (KV_periodic)
fig, plotss = plt.subplots(figsize = (10,6), dpi = 100)
plot_acf(x=Y_clean_, lags=100, ax=plotss)
plotss.set(title="ACF for KV data trace until lag=100")
plotss.set(xlabel='lag', ylabel='Coefficients')
fig.savefig('kv_acf100.png', dpi=300, bbox_inches='tight')
fig, plotss = plt.subplots(figsize = (10,6), dpi = 100)
plot_acf(x=Y_clean_, lags=4000, ax=plotss)
plotss.set(title="ACF for KV data trace until lag=4000")
plotss.set(xlabel='lag', ylabel='Coefficients')
import statsmodels.api as sm
acf, ci = sm.tsa.acf(Y_clean_, nlags=3000, alpha=0.05)
plt.plot(acf)
#period
period_index = np.where(acf == max(acf[500:3000]))
print("Period is: ", period_index)
fig, plotss = plt.subplots(figsize = (10,6), dpi = 100)
plot_acf(x=Y_clean_, lags=2570, ax=plotss)
plotss.set(title="ACF for KV data trace until lag=4000")
plotss.set(xlabel='lag', ylabel='Coefficients')
fig.savefig('kv_acf4000.png', dpi=300, bbox_inches='tight')
# For the FedCSIS trace
fig, plotss = plt.subplots(figsize = (10,6), dpi = 100)
plot_acf(x=Yfed_clean, lags=100, ax=plotss)
plotss.set(title="ACF for FedCSIS data trace until lag=100")
plotss.set(xlabel='lag', ylabel='Coefficients')
fig.savefig('fed_acf100.png', dpi=300, bbox_inches='tight')
Yfed_clean.shape
fig, plotss = plt.subplots(figsize = (10,6), dpi = 100)
plot_acf(x=Yfed_clean, lags=1866, ax=plotss)
plotss.set(title="ACF for FedCSIS data trace until lag=1866")
plotss.set(xlabel='lag', ylabel='Coefficients')
fig.savefig('fed_acf4000.png', dpi=300, bbox_inches='tight')
```
# Task IV - Time series forecasting
1. Fit an Autoregression (AR) model to the KTH time series. Perform forecasting using the AR model, which formulates the next step in the sequence as a linear function of the observations at previous time steps. The method is suitable for time series without trend and seasonal components. Evaluate the method for the AR model parameter p = 1; :::; 10.
```
Y_clean.head()
# This data is seasonal, so we want to remove the seasonality before implementing AR or MA
# Before removing seasonality, we need to find out the period, for that we use fft
#Time series of this plot (for finding the period)
fig_, linep_ = plt.subplots(figsize = (10,6), dpi = 100)
linep_ = sn.lineplot(data=Y_clean, x=Y_clean.index, y="ReadsAvg", color='green')
linep_.set(xlabel='Time index', ylabel='ReadsAvg (ms)')
linep_.set_title("Time series of reads data (clean)")
#Period is around index 2661 (according to the acf). Let's use Seasonal Adjustment with Modeling (because it allows us to have a trial and error method)
# I tried with periods around 2400, it seems like the best fit is 2570 roughly
period = 2661
X = [i%period for i in range(0, len(reads))]
degree = 5
coef = np.polyfit(X, reads, degree)
print('Coefficients: %s' % coef)
#Splitting train and test
#MAKE SURE YOU RUN THIS BEFORE THE MA THING
Y_train, Y_test = train_test_split(Y_clean_, test_size=0.3, shuffle = False)
print(Y_train.shape,"(70% of the samples in training set)")
Y_train = Y_train.sort_index(axis = 0)
Y_test = Y_test.sort_index(axis = 0)
curve = list()
for i in range(len(X)):
value = coef[-1]
for d in range(degree):
value += X[i]**(degree-d) * coef[d]
curve.append(value)
# plot curve over original data
fig_, linep_ = plt.subplots(figsize = (10,6), dpi = 100)
linep_ = sn.lineplot(data=reads, color='blue')
plt.plot(curve, color='red', linewidth=3)
linep_.set(xlabel='Time index', ylabel='ReadsAvg (ms)', title="Seasonality curve")
fig_.savefig('seasonality.png', dpi=300, bbox_inches='tight')
#Removing seasonality
diff = list()
for i in range(len(reads)):
read = reads[i] - curve[i]
diff.append(read)
plt.plot(diff)
plt.show()
Y_clean_ws = pd.DataFrame(diff, columns =['ReadsAvg'], dtype = float)
# Seasonal Adjustment with Differencing (it makes the first period unavailable for modeling)
diff_ = list()
for i in range(period, len(reads)):
value = reads[i] - reads[i - period]
diff_.append(value)
fig_, linep_ = plt.subplots(figsize = (10,6), dpi = 100)
plt.plot(diff_)
plt.show()
plt.plot(Y_test)
Y_new_test = future_columns(Y_test, 10)
h = 10
# train autoregression
model = AutoReg(train, lags=29)
model_fit = model.fit()
print('Coefficients: %s' % model_fit.params)
# make predictions
predictions = model_fit.predict(start=len(train), end=len(train)+len(test)-1, dynamic=False)
for i in range(len(predictions)):
print('predicted=%f, expected=%f' % (predictions[i], test[i]))
rmse = sqrt(mean_squared_error(test, predictions))
print('Test RMSE: %.3f' % rmse)
# plot results
pyplot.plot(test)
pyplot.plot(predictions, color='red')
pyplot.show()
#p=1, h=10 using rolling forecast (AR model)
history = Y_train.values
test = Y_test.values
predictions = list()
for t in range(len(test)):
model_fit = AutoReg(history, lags=1).fit()
output = model_fit.forecast(steps=11)
predictions.append(output)
obs = test[t]
history = np.append(history, obs)
yin = Y_new_test.index
ycol =Y_new_test.columns
Y_pred = pd.DataFrame(predictions, columns = ycol, index=yin)
Y_pred.head()
nmaes_l1 = nmaes_array(Y_new_test, Y_pred, h)
d = {'nmaes_l1': nmaes_l1}
nmaes_df = pd.DataFrame(data=d)
nmaes_df
#p=2 onwards, h=10 using rolling forecast
for p in range(2,11):
history = Y_train.values
test = Y_test.values
predictions = list()
for t in range(len(test)):
model_fit = AutoReg(history, lags=p).fit()
output = model_fit.forecast(steps=h+1)
predictions.append(output)
obs = test[t]
history = np.append(history, obs)
Y_pred_ = pd.DataFrame(predictions, columns = ycol, index=yin)
nme = nmaes_array(Y_new_test, Y_pred_, h)
nmaes_df['nmaes_l'+str(p)] = nme
print(p)
nmaes_df
nmaes_df.to_excel("ARnmae.xlsx")
fig, linep_ = plt.subplots(figsize = (10,6), dpi = 100)
linep_ = sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l1", label="q=1", linewidth =1)
sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l2", label="q=2", linewidth =1.2)
sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l3", label="q=3", linewidth =1.4)
sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l4", label="q=4", linewidth =1.6)
sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l5", label="q=5", linewidth =1.8)
sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l6", label="q=6", linewidth =2)
sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l7", label="q=7", linewidth =2.2)
sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l8", label="q=8", linewidth =2.4)
sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l9", label="q=9", linewidth =2.6)
sns.lineplot(data=nmaes_df, x=nmaes_df.index, y="nmaes_l10", label="q=10", linewidth =2.8)
linep_.set(title="NMAE vs horizon value for AR model")
linep_.set(xlabel='h', ylabel='NMAE')
fig.savefig('ARnmae.png', dpi=300, bbox_inches='tight')
```
2. Fit a Moving Average (MA) model to the KTH time series. Perform forecasting using the MA model, which formulates the next step in the sequence as a linear function of the residual errors from a meanprocess at previous time steps. Note that MA is different from calculating the moving average of a time series. The method is suitable for time series without trend and seasonal components. Evaluate the method for the model parameter q = 1; :::; 10.
```
# Equation form X = miu + Zt + beta1()
from statsmodels.tsa.arima.model import ARIMA
#Splitting train and test
#MAKE SURE YOU RUN THIS BEFORE THE MA THING
Y_train, Y_test = train_test_split(Y_clean_, test_size=0.007, shuffle = False)
print(Y_train.shape,"(100 samples in testing set)")
Y_train = Y_train.sort_index(axis = 0)
Y_test = Y_test.sort_index(axis = 0)
Y_test.shape
import multiprocessing as mp
print("Number of processors: ", mp.cpu_count())
#q=1, h=10 using rolling forecast (MA model) #takes like an hour to run :c
history = Y_train.values
test = Y_test.values
predictions = list()
for t in range(len(test)):
model_fit = ARIMA(history, order=(0,0,1), trend='c').fit()
output = model_fit.forecast(steps=11)
predictions.append(output)
obs = test[t]
history = np.append(history, obs)
print(t)
Y_new_test = future_columns(Y_test, 10)
h = 10
yin = Y_new_test.index
ycol =Y_new_test.columns
#Y_pred = pd.DataFrame(predictions, columns = ycol, index=yin)
nmaes_l1 = [0.022795, 0.036474, 0.046999, 0.057806, 0.068842, 0.079894, 0.091058, 0.102502, 0.114425, 0.126540, 0.139031]
#nmaes_l1 = nmaes_array(Y_new_test, Y_pred, h)
d = {'nmaes_q1': nmaes_l1}
nmaes_df_MA = pd.DataFrame(data=d)
nmaes_df_MA
#q=2 onwards, h=10 using rolling forecast
for q in range(2,11):
history = Y_train.values
test = Y_test.values
predictions = list()
for t in range(len(test)):
model_fit = ARIMA(history, order=(0,0,q), trend='c').fit()
output = model_fit.forecast(steps=11)
predictions.append(output)
obs = test[t]
history = np.append(history, obs)
Y_pred_ = pd.DataFrame(predictions, columns = ycol, index=yin)
nme = nmaes_array(Y_new_test, Y_pred_, h)
print(q)
print("NMAE: ", nme)
nmaes_df_MA['nmaes_l'+str(q)] = nme
nmaes_MA.to_excel("nmaesMAAA.xlsx")
fig, linep_ = plt.subplots(figsize = (10,6), dpi = 100)
linep_ = sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q1", label="q=1", linewidth =2.4)
sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q2", label="q=2", linewidth =2.2)
sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q3", label="q=3", linewidth =2.0)
sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q4", label="q=4", linewidth =1.8)
sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q5", label="q=5", linewidth =1.6)
sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q6", label="q=6", linewidth =1.4)
sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q7", label="q=7", linewidth =1.2)
sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q8", label="q=8", linewidth =1)
sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q9", label="q=9", linewidth =4.2)
#sns.lineplot(data=nmaes_MA, x=nmaes_MA.index, y="nmaes_q10", label="q=10", linewidth =4.6)
linep_.set(yscale="log")
linep_.set(title="NMAE vs horizon value for MA model")
linep_.set(xlabel='h', ylabel='NMAE')
```
| github_jupyter |
# Facial Keypoint Detection
This project will be all about defining and training a convolutional neural network to perform facial keypoint detection, and using computer vision techniques to transform images of faces. The first step in any challenge like this will be to load and visualize the data you'll be working with.
Let's take a look at some examples of images and corresponding facial keypoints.
<img src='images/key_pts_example.png' width=50% height=50%/>
Facial keypoints (also called facial landmarks) are the small magenta dots shown on each of the faces in the image above. In each training and test image, there is a single face and **68 keypoints, with coordinates (x, y), for that face**. These keypoints mark important areas of the face: the eyes, corners of the mouth, the nose, etc. These keypoints are relevant for a variety of tasks, such as face filters, emotion recognition, pose recognition, and so on. Here they are, numbered, and you can see that specific ranges of points match different portions of the face.
<img src='images/landmarks_numbered.jpg' width=30% height=30%/>
---
## Load and Visualize Data
The first step in working with any dataset is to become familiar with your data; you'll need to load in the images of faces and their keypoints and visualize them! This set of image data has been extracted from the [YouTube Faces Dataset](https://www.cs.tau.ac.il/~wolf/ytfaces/), which includes videos of people in YouTube videos. These videos have been fed through some processing steps and turned into sets of image frames containing one face and the associated keypoints.
#### Training and Testing Data
This facial keypoints dataset consists of 5770 color images. All of these images are separated into either a training or a test set of data.
* 3462 of these images are training images, for you to use as you create a model to predict keypoints.
* 2308 are test images, which will be used to test the accuracy of your model.
The information about the images and keypoints in this dataset are summarized in CSV files, which we can read in using `pandas`. Let's read the training CSV and get the annotations in an (N, 2) array where N is the number of keypoints and 2 is the dimension of the keypoint coordinates (x, y).
---
First, before we do anything, we have to load in our image data. This data is stored in a zip file and in the below cell, we access it by it's URL and unzip the data in a `/data/` directory that is separate from the workspace home directory.
```
# -- DO NOT CHANGE THIS CELL -- #
!mkdir /data
!wget -P /data/ https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5aea1b91_train-test-data/train-test-data.zip
!unzip -n /data/train-test-data.zip -d /data
# import the required libraries
import glob
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
```
Then, let's load in our training data and display some stats about that dat ato make sure it's been loaded in correctly!
```
key_pts_frame = pd.read_csv('/data/training_frames_keypoints.csv')
n = 0
image_name = key_pts_frame.iloc[n, 0]
key_pts = key_pts_frame.iloc[n, 1:].as_matrix()
key_pts = key_pts.astype('float').reshape(-1, 2)
print('Image name: ', image_name)
print('Landmarks shape: ', key_pts.shape)
print('First 4 key pts: {}'.format(key_pts[:4]))
# print out some stats about the data
print('Number of images: ', key_pts_frame.shape[0])
```
## Look at some images
Below, is a function `show_keypoints` that takes in an image and keypoints and displays them. As you look at this data, **note that these images are not all of the same size**, and neither are the faces! To eventually train a neural network on these images, we'll need to standardize their shape.
```
def show_keypoints(image, key_pts):
"""Show image with keypoints"""
plt.imshow(image)
plt.scatter(key_pts[:, 0], key_pts[:, 1], s=20, marker='x', c='orange')
# Display a few different types of images by changing the index n
# select an image by index in our data frame
n = 84
image_name = key_pts_frame.iloc[n, 0]
key_pts = key_pts_frame.iloc[n, 1:].as_matrix()
key_pts = key_pts.astype('float').reshape(-1, 2)
plt.figure(figsize=(5, 5))
show_keypoints(mpimg.imread(os.path.join('/data/training/', image_name)), key_pts)
plt.show()
```
## Dataset class and Transformations
To prepare our data for training, we'll be using PyTorch's Dataset class. Much of this this code is a modified version of what can be found in the [PyTorch data loading tutorial](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html).
#### Dataset class
``torch.utils.data.Dataset`` is an abstract class representing a
dataset. This class will allow us to load batches of image/keypoint data, and uniformly apply transformations to our data, such as rescaling and normalizing images for training a neural network.
Your custom dataset should inherit ``Dataset`` and override the following
methods:
- ``__len__`` so that ``len(dataset)`` returns the size of the dataset.
- ``__getitem__`` to support the indexing such that ``dataset[i]`` can
be used to get the i-th sample of image/keypoint data.
Let's create a dataset class for our face keypoints dataset. We will
read the CSV file in ``__init__`` but leave the reading of images to
``__getitem__``. This is memory efficient because all the images are not
stored in the memory at once but read as required.
A sample of our dataset will be a dictionary
``{'image': image, 'keypoints': key_pts}``. Our dataset will take an
optional argument ``transform`` so that any required processing can be
applied on the sample. We will see the usefulness of ``transform`` in the
next section.
```
from torch.utils.data import Dataset, DataLoader
class FacialKeypointsDataset(Dataset):
"""Face Landmarks dataset."""
def __init__(self, csv_file, root_dir, transform=None):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.key_pts_frame = pd.read_csv(csv_file)
self.root_dir = root_dir
self.transform = transform
def __len__(self):
return len(self.key_pts_frame)
def __getitem__(self, idx):
image_name = os.path.join(self.root_dir,
self.key_pts_frame.iloc[idx, 0])
image = mpimg.imread(image_name)
# if image has an alpha color channel, get rid of it
if(image.shape[2] == 4):
image = image[:,:,0:3]
key_pts = self.key_pts_frame.iloc[idx, 1:].as_matrix()
key_pts = key_pts.astype('float').reshape(-1, 2)
sample = {'image': image, 'keypoints': key_pts}
if self.transform:
sample = self.transform(sample)
return sample
```
Now that we've defined this class, let's instantiate the dataset and display some images.
```
# Construct the dataset
face_dataset = FacialKeypointsDataset(csv_file='/data/training_frames_keypoints.csv',
root_dir='/data/training/')
# print some stats about the dataset
print('Length of dataset: ', len(face_dataset))
# Display a few of the images from the dataset
num_to_display = 5
for i in range(num_to_display):
# define the size of images
fig = plt.figure(figsize=(20,10))
# randomly select a sample
rand_i = np.random.randint(0, len(face_dataset))
sample = face_dataset[rand_i]
# print the shape of the image and keypoints
print(i, sample['image'].shape, sample['keypoints'].shape)
ax = plt.subplot(1, num_to_display, i + 1)
ax.set_title('Sample #{}'.format(i))
# Using the same display function, defined earlier
show_keypoints(sample['image'], sample['keypoints'])
```
## Transforms
Now, the images above are not of the same size, and neural networks often expect images that are standardized; a fixed size, with a normalized range for color ranges and coordinates, and (for PyTorch) converted from numpy lists and arrays to Tensors.
Therefore, we will need to write some pre-processing code.
Let's create four transforms:
- ``Normalize``: to convert a color image to grayscale values with a range of [0,1] and normalize the keypoints to be in a range of about [-1, 1]
- ``Rescale``: to rescale an image to a desired size.
- ``RandomCrop``: to crop an image randomly.
- ``ToTensor``: to convert numpy images to torch images.
We will write them as callable classes instead of simple functions so
that parameters of the transform need not be passed everytime it's
called. For this, we just need to implement ``__call__`` method and
(if we require parameters to be passed in), the ``__init__`` method.
We can then use a transform like this:
tx = Transform(params)
transformed_sample = tx(sample)
Observe below how these transforms are generally applied to both the image and its keypoints.
```
import torch
from torchvision import transforms, utils
# tranforms
class Normalize(object):
"""Convert a color image to grayscale and normalize the color range to [0,1]."""
def __call__(self, sample):
image, key_pts = sample['image'], sample['keypoints']
image_copy = np.copy(image)
key_pts_copy = np.copy(key_pts)
# convert image to grayscale
image_copy = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# scale color range from [0, 255] to [0, 1]
image_copy= image_copy/255.0
# scale keypoints to be centered around 0 with a range of [-1, 1]
# mean = 100, sqrt = 50, so, pts should be (pts - 100)/50
key_pts_copy = (key_pts_copy - 100)/50.0
return {'image': image_copy, 'keypoints': key_pts_copy}
class Rescale(object):
"""Rescale the image in a sample to a given size.
Args:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ratio the same.
"""
def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
self.output_size = output_size
def __call__(self, sample):
image, key_pts = sample['image'], sample['keypoints']
h, w = image.shape[:2]
if isinstance(self.output_size, int):
if h > w:
new_h, new_w = self.output_size * h / w, self.output_size
else:
new_h, new_w = self.output_size, self.output_size * w / h
else:
new_h, new_w = self.output_size
new_h, new_w = int(new_h), int(new_w)
img = cv2.resize(image, (new_w, new_h))
# scale the pts, too
key_pts = key_pts * [new_w / w, new_h / h]
return {'image': img, 'keypoints': key_pts}
class RandomCrop(object):
"""Crop randomly the image in a sample.
Args:
output_size (tuple or int): Desired output size. If int, square crop
is made.
"""
def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
assert len(output_size) == 2
self.output_size = output_size
def __call__(self, sample):
image, key_pts = sample['image'], sample['keypoints']
h, w = image.shape[:2]
new_h, new_w = self.output_size
top = np.random.randint(0, h - new_h)
left = np.random.randint(0, w - new_w)
image = image[top: top + new_h,
left: left + new_w]
key_pts = key_pts - [left, top]
return {'image': image, 'keypoints': key_pts}
class ToTensor(object):
"""Convert ndarrays in sample to Tensors."""
def __call__(self, sample):
image, key_pts = sample['image'], sample['keypoints']
# if image has no grayscale color channel, add one
if(len(image.shape) == 2):
# add that third color dim
image = image.reshape(image.shape[0], image.shape[1], 1)
# swap color axis because
# numpy image: H x W x C
# torch image: C X H X W
image = image.transpose((2, 0, 1))
return {'image': torch.from_numpy(image),
'keypoints': torch.from_numpy(key_pts)}
```
## Test out the transforms
Let's test these transforms out to make sure they behave as expected. As you look at each transform, note that, in this case, **order does matter**. For example, you cannot crop a image using a value smaller than the original image (and the orginal images vary in size!), but, if you first rescale the original image, you can then crop it to any size smaller than the rescaled size.
```
# test out some of these transforms
rescale = Rescale(100)
crop = RandomCrop(50)
composed = transforms.Compose([Rescale(250),
RandomCrop(224)])
# apply the transforms to a sample image
test_num = 500
sample = face_dataset[test_num]
fig = plt.figure()
for i, tx in enumerate([rescale, crop, composed]):
transformed_sample = tx(sample)
ax = plt.subplot(1, 3, i + 1)
plt.tight_layout()
ax.set_title(type(tx).__name__)
show_keypoints(transformed_sample['image'], transformed_sample['keypoints'])
plt.show()
```
## Create the transformed dataset
Apply the transforms in order to get grayscale images of the same shape. Verify that your transform works by printing out the shape of the resulting data (printing out a few examples should show you a consistent tensor size).
```
# define the data tranform
# order matters! i.e. rescaling should come before a smaller crop
data_transform = transforms.Compose([Rescale(250),
RandomCrop(224),
Normalize(),
ToTensor()])
# create the transformed dataset
transformed_dataset = FacialKeypointsDataset(csv_file='/data/training_frames_keypoints.csv',
root_dir='/data/training/',
transform=data_transform)
transformed_dataset[3]['image'].shape
# print some stats about the transformed data
print('Number of images: ', len(transformed_dataset))
# make sure the sample tensors are the expected size
for i in range(5):
sample = transformed_dataset[i]
print(i, sample['image'].size(), sample['keypoints'].size())
```
## Data Iteration and Batching
Right now, we are iterating over this data using a ``for`` loop, but we are missing out on a lot of PyTorch's dataset capabilities, specifically the abilities to:
- Batch the data
- Shuffle the data
- Load the data in parallel using ``multiprocessing`` workers.
``torch.utils.data.DataLoader`` is an iterator which provides all these
features, and we'll see this in use in the *next* notebook, Notebook 2, when we load data in batches to train a neural network!
---
## Ready to Train!
Now that you've seen how to load and transform our data, you're ready to build a neural network to train on this data.
In the next notebook, you'll be tasked with creating a CNN for facial keypoint detection.
| github_jupyter |
# 04 Spark essentials
```
# Make it Python2 & Python3 compatible
from __future__ import print_function
import sys
if sys.version[0] == 3:
xrange = range
```
## Spark context
The notebook deployment includes Spark automatically within each Python notebook kernel. This means that, upon kernel instantiation, there is an [SparkContext](http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.SparkContext) object called `sc` immediatelly available in the Notebook, as in a PySpark shell. Let's take a look at it:
```
?sc
```
We can inspect some of the SparkContext properties:
```
# Spark version we are using
print( sc.version )
# Name of the application we are running
print(sc.appName)
sc.appName
# Some configuration variables
print( sc.defaultParallelism )
print( sc.defaultMinPartitions )
# Username running all Spark processes
# --> Note this is a method, not a property
print( sc.sparkUser() )
```
# Spark configuration
```
# Print out the SparkContext configuration
print( sc._conf.toDebugString() )
# Another way to get similar information
from pyspark import SparkConf, SparkContext
SparkConf().getAll()
```
## Spark execution modes
We can also take a look at the Spark configuration this kernel is running under, by using the above configuration data:
```
print( sc._conf.toDebugString() )
```
... this includes the execution mode for Spark. The default mode is *local*, i.e. all Spark processes run locally in the launched Virtual Machine. This is fine for developing and testing with small datasets.
But to run Spark applications on bigger datasets, they must be executed in a remote cluster. This deployment comes with configuration modes for that, which require:
* network adjustments to make the VM "visible" from the cluster: the virtual machine must be started in _bridged_ mode (the default *Vagrantfile* already contains code for doingso, but it must be uncommented)
* configuring the addresses for the cluster. This is done within the VM by using the `spark-notebook` script, such as
sudo service spark-notebook set-addr <master-ip> <namenode-ip> <historyserver-ip>
* activating the desired mode, by executing
sudo service spark-notebook set-mode (local | standalone | yarn)
These operations can also be performed outside the VM by telling vagrant to relay them, e.g.
vagrant ssh -c "sudo service spark-notebook set-mode local"
## A trivial test
Let's do a trivial operation that creates an RDD and executes an action on it. So that we can test that the kernel is capable of launching executors
```
from operator import add
l = sc.range(10000)
print( l.reduce(add) )
```
| github_jupyter |
# Setup
##Import libraries
```
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import random
random.seed(123)
import time
import os
from google.colab import drive
drive.mount('/content/drive')
```
##Check CUDA version
```
use_cuda = True
if use_cuda and torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
device
```
##Visualisation functions
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Function to show an image tensor
def show(X):
if X.dim() == 3 and X.size(2) == 3:
plt.imshow(X.numpy())
#plt.show()
elif X.dim() == 2:
plt.imshow( X.numpy() , cmap='gray' )
#plt.show()
else:
print('WRONG TENSOR SIZE')
def show_saliency(X):
if X.dim() == 3 and X.size(2) == 3:
plt.imshow(X.numpy())
plt.show()
elif X.dim() == 2:
plt.imshow( X.numpy() , cmap='viridis' )
plt.show()
else:
print('WRONG TENSOR SIZE')
```
##Download dataset
```
transform = transforms.Compose([transforms.ToTensor(),
transforms.Lambda(lambda x: x.squeeze()), # Squeeze the data to remove the redundant channel dimension
])
trainset = torchvision.datasets.FashionMNIST(root='./data_FashionMNIST',
train=True,
download=True,
transform=transform
)
testset = torchvision.datasets.FashionMNIST(root='./data_FashionMNIST',
train=False,
download=True,
transform=transform
)
classes = (
'T-shirt/top',
'Trouser',
'Pullover',
'Dress',
'Coat',
'Sandal',
'Shirt',
'Sneaker',
'Bag',
'Ankle boot',
)
```
#Data preprocessing
##Augment the data
```
train_hflip = transforms.functional.hflip(trainset.data)
train_brightness = [transforms.functional.adjust_brightness(x, brightness_factor=random.choice([0.5, 0.75, 1.25, 1.5])) for x in trainset.data]
train_brightness = torch.stack(train_brightness)
train_blur = transforms.functional.gaussian_blur(trainset.data, kernel_size=3)
train_rotate = [transforms.functional.rotate(torch.unsqueeze(x, dim=0), angle=random.randrange(30,330,5)).squeeze() for x in trainset.data]
train_rotate = torch.stack(train_rotate)
```
##Visualise the augmented data
```
show(trainset.data[0])
show(train_hflip[0])
show(train_blur[0])
show(train_brightness[0])
show(train_rotate[0])
```
##Split training data into train and validation data
```
trainset.data = torch.cat((trainset.data, train_hflip, train_brightness, train_blur, train_rotate),dim=0)
trainset.targets = torch.cat((trainset.targets, trainset.targets, trainset.targets, trainset.targets, trainset.targets))
trainset
from sklearn.model_selection import train_test_split
targets = trainset.targets
train_idx, val_idx= train_test_split(np.arange(len(targets)),test_size=0.2,shuffle=True, stratify=targets, random_state=123)
train_sampler = torch.utils.data.SubsetRandomSampler(train_idx)
val_sampler = torch.utils.data.SubsetRandomSampler(val_idx)
batch_size=128
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, sampler=train_sampler)
valloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, sampler=val_sampler)
testloader = torch.utils.data.DataLoader(testset,
batch_size=batch_size,
shuffle=True,
drop_last=True
)
```
#Model architecture
##Create the model
```
class Net(nn.Module):
def __init__(self, kernel_size, pool_function, nfilters_conv1, nfilters_conv2):
super(Net, self).__init__()
self.nfilters_conv2 = nfilters_conv2
# CL1: 1 x 28 x 28 (grayscale) --> nfilters_conv1 x 28 x 28
self.conv1 = nn.Conv2d(1, nfilters_conv1, kernel_size=kernel_size, padding=kernel_size//2)
# MP1: nfilters_conv1 x 28 x 28 --> nfilters_conv1 x 14 x 14
self.pool1 = pool_function(2,2)
# CL2: nfilters_conv1 x 14 x 14 --> nfilters_conv2 x 14 x 14
self.conv2 = nn.Conv2d(nfilters_conv1, nfilters_conv2, kernel_size=kernel_size, padding=kernel_size//2)
# MP2: nfilters_conv2 x 14 x 14 --> nfilters_conv2 x 7 x 7
self.pool2 = pool_function(2,2)
# LL1: nfilters_conv2 x 7 x 7 --> 100
self.linear1 = nn.Linear((nfilters_conv2*7*7), 100)
# LL2: 100 --> 10
self.linear2 = nn.Linear(100,10)
def forward(self, x):
x = x.unsqueeze(1)
# CL1:
x = self.conv1(x)
x = F.relu(x)
# MP1:
x = self.pool1(x)
# CL2:
x = self.conv2(x)
x = F.relu(x)
# MP2:
x = self.pool2(x)
# LL1:
x = x.view(-1, self.nfilters_conv2*7*7)
x = self.linear1(x)
x = F.relu(x)
# LL2:
x = self.linear2(x)
return x
# best results from hyperparameter tuning
kernel_size= 5
pool_function = nn.AvgPool2d
nfilters_conv1 = 128
nfilters_conv2 = 128
model_aug = Net(kernel_size=kernel_size,pool_function=pool_function,nfilters_conv1=nfilters_conv1,nfilters_conv2=nfilters_conv2).to(device)
criterion = nn.CrossEntropyLoss()
my_lr=0.01
optimizer=torch.optim.Adam(model_aug.parameters(), lr=my_lr) # change here
print(model_aug)
```
# Attack!
##Import libraries
```
!pip install advertorch
from advertorch.attacks import PGDAttack
```
##Create adversary
```
# prepare your pytorch model as "model"
# prepare a batch of data and label as "cln_data" and "true_label"
# prepare attack instance
adversary = PGDAttack(
model_aug, loss_fn=nn.CrossEntropyLoss(), eps=0.3,
nb_iter=10, eps_iter=0.01, rand_init=True, clip_min=0.0, clip_max=1.0,
targeted=False)
plot_valloss = []
```
##Train the model
```
start=time.time()
min_loss = 20 #initial loss to be overwritten
epochs_no_improve = 0
patience = 20 # high patience to overcome local minima
for epoch in range(1,200):
model_aug.train()
for i, (x_batch, y_batch) in enumerate(trainloader):
x_batch, y_batch = x_batch.to(device), y_batch.to(device) # Move the data to the device that is used
optimizer.zero_grad() # Set all currenly stored gradients to zero
y_pred = model_aug(x_batch)
loss = criterion(y_pred, y_batch)
loss.backward()
optimizer.step()
# Compute relevant metrics
y_pred_max = torch.argmax(y_pred, dim=1) # Get the labels with highest output probability
correct = torch.sum(torch.eq(y_pred_max, y_batch)).item() # Count how many are equal to the true labels
elapsed = time.time() - start # Keep track of how much time has elapsed
# Show progress every 50 batches
if not i % 100:
print(f'epoch: {epoch}, time: {elapsed:.3f}s, loss: {loss.item():.3f}, train accuracy: {correct / batch_size:.3f}')
model_aug.eval()
val_loss = 0
counter = 0
for i, (x_batch, y_batch) in enumerate(valloader):
counter += 1
x_batch, y_batch = x_batch.to(device), y_batch.to(device) # Move the data to the device that is used
y_pred = model_aug(x_batch)
val_loss += criterion(y_pred, y_batch).item()
val_loss = val_loss/counter
print(f'epoch: {epoch}, validation loss: {val_loss}')
plot_valloss.append([val_loss, epoch])
# save the model
if val_loss < min_loss:
torch.save(model_aug, "/content/drive/MyDrive/Deep Learning/Project/model_aug.pckl")
epochs_no_improve = 0
min_loss = val_loss
else:
epochs_no_improve += 1
if epochs_no_improve == patience:
print("Early Stopping!")
break
```
##Show validation loss
```
import pandas as pd
df_plot = pd.DataFrame(data = plot_valloss, columns=['Validation Loss', 'Epoch'])
df_plot.head()
import plotly.express as px
fig = px.line(df_plot, x="Epoch", y="Validation Loss", title='Validation Loss DA')
fig.show()
df_plot.to_csv("/content/drive/MyDrive/Deep Learning/Project/DA_valloss.csv", index=False)
```
# Testing
##Test model on clean data
```
model_aug_inf = torch.load("/content/drive/MyDrive/Deep Learning/Project/model_aug.pckl")
correct_total = 0
for i, (x_batch, y_batch) in enumerate(testloader):
x_batch, y_batch = x_batch.to(device), y_batch.to(device) # Move the data to the device that is used
y_pred = model_aug_inf(x_batch)
y_pred_max = torch.argmax(y_pred, dim=1)
correct_total += torch.sum(torch.eq(y_pred_max, y_batch)).item()
print(f'Accuracy on the test set: {correct_total / len(testset):.3f}')
accuracy = correct_total / len(testset)
z = 1.96 #for 95% CI
n = len(testset)
interval = z * np.sqrt( (accuracy * (1 - accuracy)) / n)
interval
```
## Test model on perturbed data
```
import pandas as pd
import seaborn as sn
from advertorch.utils import predict_from_logits
correct_total = 0
all_preds = []
y_true = []
for i, (x_batch, y_batch) in enumerate(testloader):
x_batch, y_batch = x_batch.to(device), y_batch.to(device) # Move the data to the device that is used
y_true.extend(y_batch)
adv = adversary.perturb(x_batch, y_batch)
y_adv_pred = predict_from_logits(model_aug_inf(adv))
all_preds.extend(y_adv_pred)
correct_total += torch.sum(torch.eq(y_adv_pred, y_batch)).item()
print(f'Accuracy on the test set: {correct_total / len(testset):.3f}')
accuracy = correct_total / len(testset)
z = 1.96 #for 95% CI
n = len(all_preds)
interval = z * np.sqrt( (accuracy * (1 - accuracy)) / n)
interval
```
## Visualise results
```
y_true_int = [int(x.cpu()) for x in y_true]
y_pred_int = [int(x.cpu()) for x in all_preds]
data = {'y_Actual': y_true_int,
'y_Predicted': y_pred_int
}
cm_df = pd.DataFrame(data, columns=['y_Actual', 'y_Predicted'])
cm_df.head()
confusion_matrix = pd.crosstab(cm_df['y_Actual'], cm_df['y_Predicted'], rownames=['Actual'], colnames=['Predicted'])
print(confusion_matrix)
sn.heatmap(confusion_matrix, annot=False)
plt.show()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/open-mmlab/mmsegmentation/blob/master/demo/MMSegmentation_Tutorial.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# MMSegmentation Tutorial
Welcome to MMSegmentation!
In this tutorial, we demo
* How to do inference with MMSeg trained weight
* How to train on your own dataset and visualize the results.
## Install MMSegmentation
This step may take several minutes.
We use PyTorch 1.6 and CUDA 10.1 for this tutorial. You may install other versions by change the version number in pip install command.
```
# Check nvcc version
!nvcc -V
# Check GCC version
!gcc --version
# Install PyTorch
!conda install pytorch=1.6.0 torchvision cudatoolkit=10.1 -c pytorch
# Install MMCV
!pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu101/torch1.6/index.html
!rm -rf mmsegmentation
!git clone https://github.com/open-mmlab/mmsegmentation.git
%cd mmsegmentation
!pip install -e .
# Check Pytorch installation
import torch, torchvision
print(torch.__version__, torch.cuda.is_available())
# Check MMSegmentation installation
import mmseg
print(mmseg.__version__)
```
## Run Inference with MMSeg trained weight
```
!mkdir checkpoints
!wget https://download.openmmlab.com/mmsegmentation/v0.5/pspnet/pspnet_r50-d8_512x1024_40k_cityscapes/pspnet_r50-d8_512x1024_40k_cityscapes_20200605_003338-2966598c.pth -P checkpoints
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
from mmseg.core.evaluation import get_palette
config_file = '../configs/pspnet/pspnet_r50-d8_512x1024_40k_cityscapes.py'
checkpoint_file = '../checkpoints/pspnet_r50-d8_512x1024_40k_cityscapes_20200605_003338-2966598c.pth'
# build the model from a config file and a checkpoint file
model = init_segmentor(config_file, checkpoint_file, device='cuda:0')
# test a single image
img = './demo.png'
result = inference_segmentor(model, img)
# show the results
show_result_pyplot(model, img, result, get_palette('cityscapes'))
```
## Train a semantic segmentation model on a new dataset
To train on a customized dataset, the following steps are necessary.
1. Add a new dataset class.
2. Create a config file accordingly.
3. Perform training and evaluation.
### Add a new dataset
Datasets in MMSegmentation require image and semantic segmentation maps to be placed in folders with the same prefix. To support a new dataset, we may need to modify the original file structure.
In this tutorial, we give an example of converting the dataset. You may refer to [docs](https://github.com/open-mmlab/mmsegmentation/docs/en/tutorials/new_dataset.md) for details about dataset reorganization.
We use [Stanford Background Dataset](http://dags.stanford.edu/projects/scenedataset.html) as an example. The dataset contains 715 images chosen from existing public datasets [LabelMe](http://labelme.csail.mit.edu), [MSRC](http://research.microsoft.com/en-us/projects/objectclassrecognition), [PASCAL VOC](http://pascallin.ecs.soton.ac.uk/challenges/VOC) and [Geometric Context](http://www.cs.illinois.edu/homes/dhoiem/). Images from these datasets are mainly outdoor scenes, each containing approximately 320-by-240 pixels.
In this tutorial, we use the region annotations as labels. There are 8 classes in total, i.e. sky, tree, road, grass, water, building, mountain, and foreground object.
```
# download and unzip
!wget http://dags.stanford.edu/data/iccv09Data.tar.gz -O stanford_background.tar.gz
!tar xf stanford_background.tar.gz
# Let's take a look at the dataset
import mmcv
import matplotlib.pyplot as plt
img = mmcv.imread('iccv09Data/images/6000124.jpg')
plt.figure(figsize=(8, 6))
plt.imshow(mmcv.bgr2rgb(img))
plt.show()
```
We need to convert the annotation into semantic map format as an image.
```
import os.path as osp
import numpy as np
from PIL import Image
# convert dataset annotation to semantic segmentation map
data_root = 'iccv09Data'
img_dir = 'images'
ann_dir = 'labels'
# define class and plaette for better visualization
classes = ('sky', 'tree', 'road', 'grass', 'water', 'bldg', 'mntn', 'fg obj')
palette = [[128, 128, 128], [129, 127, 38], [120, 69, 125], [53, 125, 34],
[0, 11, 123], [118, 20, 12], [122, 81, 25], [241, 134, 51]]
for file in mmcv.scandir(osp.join(data_root, ann_dir), suffix='.regions.txt'):
seg_map = np.loadtxt(osp.join(data_root, ann_dir, file)).astype(np.uint8)
seg_img = Image.fromarray(seg_map).convert('P')
seg_img.putpalette(np.array(palette, dtype=np.uint8))
seg_img.save(osp.join(data_root, ann_dir, file.replace('.regions.txt',
'.png')))
# Let's take a look at the segmentation map we got
import matplotlib.patches as mpatches
img = Image.open('iccv09Data/labels/6000124.png')
plt.figure(figsize=(8, 6))
im = plt.imshow(np.array(img.convert('RGB')))
# create a patch (proxy artist) for every color
patches = [mpatches.Patch(color=np.array(palette[i])/255.,
label=classes[i]) for i in range(8)]
# put those patched as legend-handles into the legend
plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,
fontsize='large')
plt.show()
# split train/val set randomly
split_dir = 'splits'
mmcv.mkdir_or_exist(osp.join(data_root, split_dir))
filename_list = [osp.splitext(filename)[0] for filename in mmcv.scandir(
osp.join(data_root, ann_dir), suffix='.png')]
with open(osp.join(data_root, split_dir, 'train.txt'), 'w') as f:
# select first 4/5 as train set
train_length = int(len(filename_list)*4/5)
f.writelines(line + '\n' for line in filename_list[:train_length])
with open(osp.join(data_root, split_dir, 'val.txt'), 'w') as f:
# select last 1/5 as train set
f.writelines(line + '\n' for line in filename_list[train_length:])
```
After downloading the data, we need to implement `load_annotations` function in the new dataset class `StanfordBackgroundDataset`.
```
from mmseg.datasets.builder import DATASETS
from mmseg.datasets.custom import CustomDataset
@DATASETS.register_module()
class StanfordBackgroundDataset(CustomDataset):
CLASSES = classes
PALETTE = palette
def __init__(self, split, **kwargs):
super().__init__(img_suffix='.jpg', seg_map_suffix='.png',
split=split, **kwargs)
assert osp.exists(self.img_dir) and self.split is not None
```
### Create a config file
In the next step, we need to modify the config for the training. To accelerate the process, we finetune the model from trained weights.
```
from mmcv import Config
cfg = Config.fromfile('../configs/pspnet/pspnet_r50-d8_512x1024_40k_cityscapes.py')
```
Since the given config is used to train PSPNet on the cityscapes dataset, we need to modify it accordingly for our new dataset.
```
from mmseg.apis import set_random_seed
# Since we use only one GPU, BN is used instead of SyncBN
cfg.norm_cfg = dict(type='BN', requires_grad=True)
cfg.model.backbone.norm_cfg = cfg.norm_cfg
cfg.model.decode_head.norm_cfg = cfg.norm_cfg
cfg.model.auxiliary_head.norm_cfg = cfg.norm_cfg
# modify num classes of the model in decode/auxiliary head
cfg.model.decode_head.num_classes = 8
cfg.model.auxiliary_head.num_classes = 8
# Modify dataset type and path
cfg.dataset_type = 'StanfordBackgroundDataset'
cfg.data_root = data_root
cfg.data.samples_per_gpu = 8
cfg.data.workers_per_gpu=8
cfg.img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
cfg.crop_size = (256, 256)
cfg.train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations'),
dict(type='Resize', img_scale=(320, 240), ratio_range=(0.5, 2.0)),
dict(type='RandomCrop', crop_size=cfg.crop_size, cat_max_ratio=0.75),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='PhotoMetricDistortion'),
dict(type='Normalize', **cfg.img_norm_cfg),
dict(type='Pad', size=cfg.crop_size, pad_val=0, seg_pad_val=255),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_semantic_seg']),
]
cfg.test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(320, 240),
# img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75],
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **cfg.img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
cfg.data.train.type = cfg.dataset_type
cfg.data.train.data_root = cfg.data_root
cfg.data.train.img_dir = img_dir
cfg.data.train.ann_dir = ann_dir
cfg.data.train.pipeline = cfg.train_pipeline
cfg.data.train.split = 'splits/train.txt'
cfg.data.val.type = cfg.dataset_type
cfg.data.val.data_root = cfg.data_root
cfg.data.val.img_dir = img_dir
cfg.data.val.ann_dir = ann_dir
cfg.data.val.pipeline = cfg.test_pipeline
cfg.data.val.split = 'splits/val.txt'
cfg.data.test.type = cfg.dataset_type
cfg.data.test.data_root = cfg.data_root
cfg.data.test.img_dir = img_dir
cfg.data.test.ann_dir = ann_dir
cfg.data.test.pipeline = cfg.test_pipeline
cfg.data.test.split = 'splits/val.txt'
# We can still use the pre-trained Mask RCNN model though we do not need to
# use the mask branch
cfg.load_from = 'checkpoints/pspnet_r50-d8_512x1024_40k_cityscapes_20200605_003338-2966598c.pth'
# Set up working dir to save files and logs.
cfg.work_dir = './work_dirs/tutorial'
cfg.runner.max_iters = 200
cfg.log_config.interval = 10
cfg.evaluation.interval = 200
cfg.checkpoint_config.interval = 200
# Set seed to facitate reproducing the result
cfg.seed = 0
set_random_seed(0, deterministic=False)
cfg.gpu_ids = range(1)
# Let's have a look at the final config used for training
print(f'Config:\n{cfg.pretty_text}')
```
### Train and Evaluation
```
from mmseg.datasets import build_dataset
from mmseg.models import build_segmentor
from mmseg.apis import train_segmentor
# Build the dataset
datasets = [build_dataset(cfg.data.train)]
# Build the detector
model = build_segmentor(
cfg.model, train_cfg=cfg.get('train_cfg'), test_cfg=cfg.get('test_cfg'))
# Add an attribute for visualization convenience
model.CLASSES = datasets[0].CLASSES
# Create work_dir
mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
train_segmentor(model, datasets, cfg, distributed=False, validate=True,
meta=dict())
```
Inference with trained model
```
img = mmcv.imread('iccv09Data/images/6000124.jpg')
model.cfg = cfg
result = inference_segmentor(model, img)
plt.figure(figsize=(8, 6))
show_result_pyplot(model, img, result, palette)
```
| github_jupyter |
- 参考 [天秀!GitHub 硬核项目:动漫生成器让照片秒变手绘日漫风!!!](https://mp.weixin.qq.com/s?__biz=MzAxOTcxNTIwNQ==&mid=310435176&idx=1&sn=9d3f5916ae5126c4e3233b26595e02cb&chksm=0cb6b8823bc13194bb38ce5eabe344e59a6881f1ae6a4ac0aa183874ec71c2586b73ce3c0f96#rd)
以下下步骤中 [ ] 表示非必须
- **[查看分配到的GPU型号]**
```
!nvidia-smi
```
- **1. 安装运行环境**
```
!pip3 install tensorflow-gpu==1.13.1
!pip3 install opencv-python
!pip3 install tqdm
!pip3 install numpy
!pip3 install argparse
```
- **[检查是否安装成功]**
```
!pip3 show tensorflow-gpu
!pip3 show opencv-python
!pip3 show tqdm
!pip3 show numpy
!pip3 show argparse
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
```
- **2. 下载AnimeGAN源码**
```
%cd /content
!git clone https://github.com/TachibanaYoshino/AnimeGAN
```
- **3. 添加(or上传)并执行预训练模型下载脚本 download_staffs.sh**
```
%cd /content/AnimeGAN
!echo -e 'URL=https://github.com/TachibanaYoshino/AnimeGAN/releases/download/Haoyao-style_V1.0/Haoyao-style.zip\nZIP_FILE=./checkpoint/Haoyao-style.zip\nTARGET_DIR=./checkpoint/saved_model\n\nmkdir -p ./checkpoint\nwget -N $URL -O $ZIP_FILE\nmkdir -p $TARGET_DIR\nunzip $ZIP_FILE -d $TARGET_DIR\nrm $ZIP_FILE\n\nDatesetURL=https://github.com/TachibanaYoshino/AnimeGAN/releases/download/dataset-1/dataset.zip\nZIP_FILE=./dataset.zip\nTARGET_DIR=./dataset\n\nrm -rf dataset\nwget -N $DatesetURL -O $ZIP_FILE\nunzip $ZIP_FILE -d $TARGET_DIR\nrm $ZIP_FILE\n\nVGG_FILE=./vgg19_weight/vgg19.npy\nwget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate \0047https://docs.google.com/uc?export=download&id=1U5HCRpZWAbDVLipNoF8t0ZHpwCRX7kdF\0047 -O- | sed -rn \0047s/.*confirm=([0-9A-Za-z_]+).*/\01341\0134n/p\0047)&id=1U5HCRpZWAbDVLipNoF8t0ZHpwCRX7kdF" -O $VGG_FILE && rm -rf /tmp/cookies.txt' > download_staffs.sh
!bash download_staffs.sh
```
- **4. [训练模型(非常耗时, 可以跳过这一步)]**
```
!python main.py --phase train --dataset Hayao --epoch 101 --init_epoch 1
```
- **5. 添加(or上传)视频处理脚本 video.py**
```
!echo -e 'import\0040argparse\nimport\0040cv2\nimport\0040os\nimport\0040re\nimport\0040shutil\n\nfg_video_path\0040=\0040\0047/content/AnimeGAN/video/input_video.mp4\0047\nEXTRACT_FREQUENCY\0040=\00401\n\ndef\0040extract(video_path,\0040image_path,\0040index=EXTRACT_FREQUENCY):\n\0040\0040\0040\0040try:\n\0040\0040\0040\0040\0040\0040\0040\0040shutil.rmtree(image_path)\n\0040\0040\0040\0040except\0040OSError:\n\0040\0040\0040\0040\0040\0040\0040\0040pass\n\0040\0040\0040\0040os.mkdir(image_path)\n\0040\0040\0040\0040video\0040=\0040cv2.VideoCapture()\n\0040\0040\0040\0040if\0040not\0040video.open(video_path):\n\0040\0040\0040\0040\0040\0040\0040\0040print("can\0040not\0040open\0040the\0040video")\n\0040\0040\0040\0040\0040\0040\0040\0040exit(1)\n\0040\0040\0040\0040count\0040=\00401\n\0040\0040\0040\0040while\0040True:\n\0040\0040\0040\0040\0040\0040\0040\0040_,\0040frame\0040=\0040video.read()\n\0040\0040\0040\0040\0040\0040\0040\0040if\0040frame\0040is\0040None:\n\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040break\n\0040\0040\0040\0040\0040\0040\0040\0040if\0040count\0040%\0040EXTRACT_FREQUENCY\0040==\00400:\n\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040save_path\0040=\0040"{}/{:>04d}.jpg".format(image_path,\0040index)\n\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040cv2.imwrite(save_path,\0040frame)\n\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040\0040index\0040+=\00401\n\0040\0040\0040\0040\0040\0040\0040\0040count\0040+=\00401\n\0040\0040\0040\0040video.release()\n\0040\0040\0040\0040print("Totally\0040save\0040{:d}\0040pics".format(index\0040-\00401))\n\ndef\0040is_frame(path):\n\0040\0040\0040\0040res\0040=\0040re.match(r\0047\0134d{4}\0134.jpg$\0047,\0040path)\n\0040\0040\0040\0040return\0040True\0040if\0040res\0040!=\0040None\0040else\0040False\n\ndef\0040filter_frame(array):\n\0040\0040\0040\0040res\0040=\0040[]\n\0040\0040\0040\0040for\0040item\0040in\0040filter(is_frame,\0040array):\n\0040\0040\0040\0040\0040\0040\0040\0040res.append(item)\n\0040\0040\0040\0040res.sort(reverse=False)\n\0040\0040\0040\0040return\0040res\n\ndef\0040combine(image_path,\0040output_path):\n\0040\0040\0040\0040cap\0040=\0040cv2.VideoCapture(fg_video_path)\n\0040\0040\0040\0040fgs\0040=\0040int(cap.get(cv2.CAP_PROP_FPS))\0040\n\0040\0040\0040\0040fgs\0040=\0040fgs\0040if\0040fgs\0040>\00400\0040else\004025\n\0040\0040\0040\0040pictrue_in_filelist\0040=\0040filter_frame(os.listdir(image_path))\n\0040\0040\0040\0040print(pictrue_in_filelist)\n\0040\0040\0040\0040name\0040=\0040image_path\0040+\0040"/"\0040+\0040pictrue_in_filelist[0]\n\0040\0040\0040\0040img\0040=\0040cv2.imread(name)\n\0040\0040\0040\0040h,\0040w,\0040c\0040=\0040img.shape\n\0040\0040\0040\0040size\0040=\0040(w,\0040h)\n\0040\0040\0040\0040print(f\0047size:\0040{size},\0040fgs:\0040{fgs}\0047)\n\n\0040\0040\0040\0040fourcc\0040=\0040cv2.VideoWriter_fourcc(*\0047XVID\0047)\n\0040\0040\0040\0040out_video\0040=\0040output_path\0040+\0040\0047.mp4\0047\n\0040\0040\0040\0040video_writer\0040=\0040cv2.VideoWriter(out_video,\0040fourcc,\0040fgs,\0040size)\n\n\0040\0040\0040\0040for\0040i\0040in\0040range(len(pictrue_in_filelist)):\n\0040\0040\0040\0040\0040\0040\0040\0040pictrue_in_filename\0040=\0040image_path\0040+\0040"/"\0040+\0040pictrue_in_filelist[i]\n\0040\0040\0040\0040\0040\0040\0040\0040img12\0040=\0040cv2.imread(pictrue_in_filename)\n\0040\0040\0040\0040\0040\0040\0040\0040video_writer.write(img12)\n\0040\0040\0040\0040video_writer.release()\n\0040\0040\0040\0040#print("删除合成的图片数据集")\n\0040\0040\0040\0040#shutil.rmtree(fg_in_bg)\n\0040\0040\0040\0040return\0040out_video\n\ndef\0040parse_args():\n\0040\0040\0040\0040desc\0040=\0040"video\0040util"\n\0040\0040\0040\0040parser\0040=\0040argparse.ArgumentParser(description=desc)\n\0040\0040\0040\0040parser.add_argument(\0047--type\0047,\0040type=str,\0040default=\0047extract\0047,\0040help=\0047specify\0040which\0040action\0040to\0040take\0047)\n\0040\0040\0040\0040parser.add_argument(\0047--video_path\0047,\0040type=str,\0040default=\0047/content/AnimeGAN/video/input_video.mp4\0047,\0040help=\0047input\0040video\0040path\0047)\n\0040\0040\0040\0040parser.add_argument(\0047--image_path\0047,\0040type=str,\0040default=\0047/content/AnimeGAN/video/input_video\0047,\0040help=\0047output\0040images\0040path\0047)\n\0040\0040\0040\0040parser.add_argument(\0047--output_path\0047,\0040type=str,\0040default=\0047/content/AnimeGAN/video/output_video.mp4\0047,\0040help=\0047output\0040video\0040path\0047)\n\0040\0040\0040\0040"""checking\0040arguments"""\n\0040\0040\0040\0040return\0040parser.parse_args()\n\nif\0040__name__\0040==\0040"__main__":\n\0040\0040\0040\0040args\0040=\0040parse_args()\n\0040\0040\0040\0040if\0040args.type\0040==\0040\0047extract\0047:\n\0040\0040\0040\0040\0040\0040\0040\0040extract(args.video_path,\0040args.image_path)\n\0040\0040\0040\0040\0040\0040\0040\0040print(f\0047extract\0040video\0040{args.video_path}\0040into\0040images\0040{args.image_path}\0047)\n\0040\0040\0040\0040elif\0040args.type\0040==\0040\0047combine\0047:\n\0040\0040\0040\0040\0040\0040\0040\0040combine(args.image_path,\0040args.output_path)\n\0040\0040\0040\0040\0040\0040\0040\0040print(f\0047combine\0040images\0040from\0040{args.image_path}\0040into\0040{args.output_path}\0047)\n\0040\0040\0040\0040else:\n\0040\0040\0040\0040\0040\0040\0040\0040print(f\0047Error:\0040you\0040must\0040specify\0040the\0040argument\0040of\0040type,\0040extract\0040or\0040combine\0047)' > video.py
```
- **6. 上传视频**
```
%mkdir video
print('Upload video in this dir: /content/AnimeGAN/video')
```
- **7. 视频分解为序列帧图片**
```
!python video.py --type extract --video_path /content/AnimeGAN/video/input_video.mp4 --image_path /content/AnimeGAN/video/input_video
```
- **8. 序列帧图片动漫化**
```
!python test.py --checkpoint_dir checkpoint/saved_model --test_dir video/input_video --style_name H
```
- **9. 序列帧合成视频**
```
!python video.py --type combine --image_path /content/AnimeGAN/results/H --output_path /content/AnimeGAN/video/output_video.mp4
```
| github_jupyter |
```
import pickle
import numpy as np
import mplhep
import awkward
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import uproot
import boost_histogram as bh
physics_process = "qcd"
data_baseline = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.0/out.pkl", "rb")))
data_mlpf = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.13/out.pkl", "rb")))
fi1 = uproot.open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.0/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root")
fi2 = uproot.open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.13/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root")
physics_process = "ttbar"
data_mlpf = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.13/out.pkl", "rb")))
data_baseline = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.0/out.pkl", "rb")))
fi1 = uproot.open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.0/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root")
fi2 = uproot.open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.13/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root")
# physics_process = "singlepi"
# data_mlpf = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_11_3_0_pre2/11688.0_mlpf/out.pkl", "rb")))
# data_baseline = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_11_3_0_pre2/11688.0_baseline/out.pkl", "rb")))
def cms_label(x0=0.12, x1=0.23, x2=0.67, y=0.90):
plt.figtext(x0, y,'CMS',fontweight='bold', wrap=True, horizontalalignment='left', fontsize=12)
plt.figtext(x1, y,'Simulation Preliminary', style='italic', wrap=True, horizontalalignment='left', fontsize=10)
plt.figtext(x2, y,'Run 3 (14 TeV)', wrap=True, horizontalalignment='left', fontsize=10)
physics_process_str = {
"ttbar": "$\mathrm{t}\overline{\mathrm{t}}$ events",
"singlepi": "single $\pi^{\pm}$ events",
"qcd": "QCD",
}
def sample_label(ax, x=0.03, y=0.98, additional_text="", physics_process=physics_process):
plt.text(x, y,
physics_process_str[physics_process]+additional_text,
va="top", ha="left", size=10, transform=ax.transAxes)
plt.figure(figsize=(5, 5))
ax = plt.axes()
bins = np.linspace(0, 500, 61)
plt.hist(awkward.flatten(data_baseline["ak4PFJetsCHS"]["pt"]), bins=bins, histtype="step", lw=2, label="PF");
plt.hist(awkward.flatten(data_mlpf["ak4PFJetsCHS"]["pt"]), bins=bins, histtype="step", lw=2, label="MLPF");
plt.yscale("log")
plt.ylim(top=1e5)
cms_label()
sample_label(ax, x=0.02)
plt.xlabel("ak4PFJetsCHS $p_T$ [GeV]")
plt.ylabel("Number of jets")
plt.legend(loc="best")
plt.savefig("ak4jet_pt_{}.pdf".format(physics_process), bbox_inches="tight")
plt.figure(figsize=(5, 5))
bins = np.linspace(0, 2500, 61)
plt.hist(awkward.flatten(data_baseline["ak4PFJetsCHS"]["energy"]), bins=bins, histtype="step", lw=2, label="PF");
plt.hist(awkward.flatten(data_mlpf["ak4PFJetsCHS"]["energy"]), bins=bins, histtype="step", lw=2, label="MLPF");
plt.yscale("log")
plt.ylim(top=1e5)
cms_label()
sample_label(ax, x=0.02)
plt.xlabel("ak4PFJetsCHS $E$ [GeV]")
plt.ylabel("Number of jets")
plt.legend(loc="best")
plt.savefig("ak4jet_energy_{}.pdf".format(physics_process), bbox_inches="tight")
plt.figure(figsize=(5, 5))
bins = np.linspace(-6, 6, 101)
plt.hist(awkward.flatten(data_baseline["ak4PFJetsCHS"]["eta"]), bins=bins, histtype="step", lw=2, label="PF");
plt.hist(awkward.flatten(data_mlpf["ak4PFJetsCHS"]["eta"]), bins=bins, histtype="step", lw=2, label="MLPF");
#plt.yscale("log")
cms_label()
sample_label(ax)
plt.ylim(top=2000)
plt.xlabel("ak4PFJetsCHS $\eta$")
plt.ylabel("Number of jets")
plt.legend(loc="best")
plt.savefig("ak4jet_eta_{}.pdf".format(physics_process), bbox_inches="tight")
color_map = {
1: "red",
2: "blue",
11: "orange",
22: "cyan",
13: "purple",
130: "green",
211: "black"
}
particle_labels = {
1: "HFEM",
2: "HFHAD",
11: "$e^\pm$",
22: "$\gamma$",
13: "$\mu$",
130: "neutral hadron",
211: "charged hadron"
}
def draw_event(iev):
pt_0 = data_mlpf["particleFlow"]["pt"][iev]
energy_0 = data_mlpf["particleFlow"]["energy"][iev]
eta_0 = data_mlpf["particleFlow"]["eta"][iev]
phi_0 = data_mlpf["particleFlow"]["phi"][iev]
pdgid_0 = np.abs(data_mlpf["particleFlow"]["pdgId"][iev])
pt_1 = data_baseline["particleFlow"]["pt"][iev]
energy_1 = data_baseline["particleFlow"]["energy"][iev]
eta_1 = data_baseline["particleFlow"]["eta"][iev]
phi_1 = data_baseline["particleFlow"]["phi"][iev]
pdgid_1 = np.abs(data_baseline["particleFlow"]["pdgId"][iev])
plt.figure(figsize=(5, 5))
ax = plt.axes()
plt.scatter(eta_0, phi_0, marker=".", s=energy_0, c=[color_map[p] for p in pdgid_0], alpha=0.6)
pids = [211,130,1,2,22,11,13]
for p in pids:
plt.plot([], [], color=color_map[p], lw=0, marker="o", label=particle_labels[p])
plt.legend(loc=8, frameon=False, ncol=3, fontsize=8)
cms_label()
sample_label(ax)
plt.xlim(-6,6)
plt.ylim(-5,4)
plt.xlabel("PFCandidate $\eta$")
plt.ylabel("PFCandidate $\phi$")
plt.title("MLPF (trained on PF), CMSSW-ONNX inference", y=1.05)
plt.savefig("event_mlpf_{}_iev{}.pdf".format(physics_process, iev), bbox_inches="tight")
plt.savefig("event_mlpf_{}_iev{}.png".format(physics_process, iev), bbox_inches="tight", dpi=300)
plt.figure(figsize=(5, 5))
ax = plt.axes()
plt.scatter(eta_1, phi_1, marker=".", s=energy_1, c=[color_map[p] for p in pdgid_1], alpha=0.6)
# plt.scatter(
# data_baseline["ak4PFJetsCHS"]["eta"][iev],
# data_baseline["ak4PFJetsCHS"]["phi"][iev],
# s=data_baseline["ak4PFJetsCHS"]["energy"][iev], color="gray", alpha=0.3
# )
cms_label()
sample_label(ax)
plt.xlim(-6,6)
plt.ylim(-5,4)
plt.xlabel("PFCandidate $\eta$")
plt.ylabel("PFCandidate $\phi$")
plt.title("Standard PF, CMSSW", y=1.05)
pids = [211,130,1,2,22,11,13]
for p in pids:
plt.plot([], [], color=color_map[p], lw=0, marker="o", label=particle_labels[p])
plt.legend(loc=8, frameon=False, ncol=3, fontsize=8)
plt.savefig("event_pf_{}_iev{}.pdf".format(physics_process, iev), bbox_inches="tight")
plt.savefig("event_pf_{}_iev{}.png".format(physics_process, iev), bbox_inches="tight", dpi=300)
draw_event(0)
draw_event(1)
draw_event(2)
def plot_dqm(key, title, rebin=None):
h1 = fi1.get(key).to_boost()
h2 = fi2.get(key).to_boost()
fig, (ax1, ax2) = plt.subplots(2, 1)
plt.sca(ax1)
if rebin:
h1 = h1[bh.rebin(rebin)]
h2 = h2[bh.rebin(rebin)]
mplhep.histplot(h1, yerr=0, label="PF");
mplhep.histplot(h2, yerr=0, label="MLPF");
plt.legend(frameon=False)
plt.ylabel("Number of particles / bin")
sample_label(ax=ax1, additional_text=", "+title, physics_process=physics_process)
plt.sca(ax2)
ratio_hist = h2/h1
vals_y = ratio_hist.values()
vals_y[np.isnan(vals_y)] = 0
plt.plot(ratio_hist.axes[0].centers, vals_y, color="gray", lw=0, marker=".")
plt.ylim(0,2)
plt.axhline(1.0, color="black", ls="--")
plt.ylabel("MLPF / PF")
return ax1, ax2
#plt.xscale("log")
#plt.yscale("log")
log10_pt = "$\log_{10}[p_T/\mathrm{GeV}]$"
eta = "$\eta$"
dqm_plots_ptcl = [
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/chargedHadron/chargedHadronLog10Pt",
"ch.had.", log10_pt, "ch_had_logpt"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/chargedHadron/chargedHadronEta",
"ch.had.", eta, "ch_had_eta"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/neutralHadron/neutralHadronLog10Pt",
"n.had.", log10_pt, "n_had_logpt"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/neutralHadron/neutralHadronPtLow",
"n.had.", "$p_T$ [GeV]", "n_had_ptlow"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/neutralHadron/neutralHadronPtMid",
"n.had.", "$p_T$ [GeV]", "n_had_ptmid"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/neutralHadron/neutralHadronEta",
"n.had.", eta, "n_had_eta"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/HF_hadron/HF_hadronLog10Pt",
"HFHAD", log10_pt, "hfhad_logpt"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/HF_hadron/HF_hadronEta",
"HFHAD", eta, "hfhad_eta"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/HF_EM_particle/HF_EM_particleLog10Pt",
"HFEM", log10_pt, "hfem_logpt"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/HF_EM_particle/HF_EM_particleEta",
"HFEM", eta, "hfem_eta"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/photon/photonLog10Pt",
"photon", log10_pt, "photon_logpt"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/photon/photonEta",
"photon", eta, "photon_eta"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/electron/electronLog10Pt",
"electron", log10_pt, "electron_logpt"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/electron/electronEta",
"electron", eta, "electron_eta"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/muon/muonLog10Pt",
"muon", log10_pt, "muon_logpt"),
("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/muon/muonEta",
"muon", eta, "muon_eta"),
]
dqm_plots_jetres = [
("DQMData/Run 1/ParticleFlow/Run summary/PFJetValidation/CompWithGenJet/mean_delta_et_Over_et_VS_et_",
"jets", "gen-jet $E_t$", "$\Delta E_t / E_t$"),
]
for key, title, xlabel, plot_label in dqm_plots_ptcl:
rh = plot_dqm(key, title)
plt.xlabel(xlabel)
cms_label()
plt.savefig("dqm_{}_{}.pdf".format(plot_label, physics_process), bbox_inches="tight")
plt.savefig("dqm_{}_{}.png".format(plot_label, physics_process), bbox_inches="tight", dpi=300)
ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/Jet/Cleanedak4PFJetsCHS/Pt", "ak4PFCHS jets")
ax2.set_xlabel("jet $p_t$ [GeV]")
ax1.set_ylabel("number of jets / bin")
#plt.xscale("log")
#plt.ylim(bottom=1, top=1e4)
ax1.set_yscale("log")
ax1.set_ylim(bottom=1, top=1e5)
#ax2.set_ylim(0,5)
cms_label()
plt.savefig("dqm_jet_pt_{}.pdf".format(physics_process), bbox_inches="tight")
plt.savefig("dqm_jet_pt_{}.png".format(physics_process), bbox_inches="tight", dpi=300)
ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/Jet/CleanedslimmedJetsPuppi/Pt", "ak4PFPuppi jets")
ax2.set_xlabel("jet $p_t$ [GeV]")
ax1.set_ylabel("number of jets / bin")
#plt.xscale("log")
#plt.ylim(bottom=1, top=1e4)
ax1.set_yscale("log")
ax1.set_ylim(bottom=1, top=1e5)
#ax2.set_ylim(0,5)
cms_label()
plt.savefig("dqm_jet_pt_puppi_{}.pdf".format(physics_process), bbox_inches="tight")
plt.savefig("dqm_jet_pt_puppi_{}.png".format(physics_process), bbox_inches="tight", dpi=300)
ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/Jet/Cleanedak4PFJetsCHS/Eta", "ak4PFCHS jets")
ax2.set_xlabel("jet $\eta$")
ax1.set_ylabel("number of jets / bin")
#plt.xscale("log")
#plt.ylim(bottom=1, top=1e4)
#ax1.set_yscale("log")
ax1.set_ylim(bottom=0, top=1e3)
#ax2.set_ylim(0,5)
cms_label()
plt.savefig("dqm_jet_eta_{}.pdf".format(physics_process), bbox_inches="tight")
plt.savefig("dqm_jet_eta_{}.png".format(physics_process), bbox_inches="tight", dpi=300)
ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/Jet/CleanedslimmedJetsPuppi/Eta", "ak4PFPuppi jets")
ax2.set_xlabel("jet $\eta$")
ax1.set_ylabel("number of jets / bin")
#plt.xscale("log")
#plt.ylim(bottom=1, top=1e4)
#ax1.set_yscale("log")
#ax1.set_ylim(bottom=0, top=20)
#ax2.set_ylim(0,5)
cms_label()
plt.savefig("dqm_jet_eta_puppi_{}.pdf".format(physics_process), bbox_inches="tight")
plt.savefig("dqm_jet_eta_puppi_{}.png".format(physics_process), bbox_inches="tight", dpi=300)
# plot_dqm("DQMData/Run 1/ParticleFlow/Run summary/PFJetValidation/CompWithGenJet/mean_delta_et_Over_et_VS_et_", "AK4 PF jets")
# plt.xlabel("gen-jet $E_t$ [GeV]")
# plt.ylabel("profiled $\mu(\Delta E_t / E_t$)")
# plt.xscale("log")
# plt.ylim(0,3)
# cms_label()
# plt.savefig("dqm_jet_mean_delta_et_Over_et_VS_et.pdf", bbox_inches="tight")
# plot_dqm("DQMData/Run 1/ParticleFlow/Run summary/PFJetValidation/CompWithGenJet/sigma_delta_et_Over_et_VS_et_", "AK4 PF jets")
# plt.xlabel("gen-jet $E_t$ [GeV]")
# plt.ylabel("profiled $\sigma(\Delta E_t / E_t)$")
# plt.xscale("log")
# plt.ylim(0,10)
# cms_label()
# plt.savefig("dqm_jet_sigma_delta_et_Over_et_VS_et.pdf", bbox_inches="tight")
ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/METValidation/pfMet/MET", "PFMET", rebin=1)
ax2.set_xlabel("$\sum E_t$ [GeV]")
ax1.set_ylabel("number of events / bin")
#ax1.set_xscale("log")
ax1.set_ylim(bottom=1, top=1000)
ax1.set_yscale("log")
plt.savefig("dqm_met_sumet_{}.pdf".format(physics_process), bbox_inches="tight")
plt.savefig("dqm_met_sumet_{}.png".format(physics_process), bbox_inches="tight", dpi=300)
# plot_dqm("DQMData/Run 1/ParticleFlow/Run summary/PFMETValidation/CompWithGenMET/profileRMS_delta_et_Over_et_VS_et_", "PFMET")
# plt.xlabel("gen-MET $E_t$ [GeV]")
# plt.ylabel("profiled RMS $\Delta E_t / E_t$")
# plt.xscale("log")
# plt.ylim(0,3)
# cms_label()
# plt.savefig("dqm_met_profileRMS_delta_et_Over_et_VS_et.pdf", bbox_inches="tight")
# plot_dqm("DQMData/Run 1/ParticleFlow/Run summary/PFMETValidation/CompWithGenMET/profile_delta_et_VS_et_", "PFMET")
# plt.xlabel("gen-MET $E_t$ [GeV]")
# plt.ylabel("profiled $\Delta E_t$ [GeV]")
# plt.xscale("log")
# plt.ylim(0, 80)
# cms_label()
# plt.savefig("dqm_met_delta_et_VS_et.pdf", bbox_inches="tight")
timing_output = """
Nelem=1600 mean_time=5.92 ms stddev_time=5.03 ms mem_used=1018 MB
Nelem=1920 mean_time=6.57 ms stddev_time=1.01 ms mem_used=1110 MB
Nelem=2240 mean_time=6.92 ms stddev_time=0.81 ms mem_used=1127 MB
Nelem=2560 mean_time=7.37 ms stddev_time=0.66 ms mem_used=1136 MB
Nelem=2880 mean_time=8.17 ms stddev_time=0.56 ms mem_used=1123 MB
Nelem=3200 mean_time=8.88 ms stddev_time=1.09 ms mem_used=1121 MB
Nelem=3520 mean_time=9.51 ms stddev_time=0.65 ms mem_used=1121 MB
Nelem=3840 mean_time=10.48 ms stddev_time=0.93 ms mem_used=1255 MB
Nelem=4160 mean_time=11.05 ms stddev_time=0.87 ms mem_used=1255 MB
Nelem=4480 mean_time=12.07 ms stddev_time=0.81 ms mem_used=1230 MB
Nelem=4800 mean_time=12.92 ms stddev_time=0.89 ms mem_used=1230 MB
Nelem=5120 mean_time=13.44 ms stddev_time=0.75 ms mem_used=1230 MB
Nelem=5440 mean_time=14.07 ms stddev_time=0.78 ms mem_used=1230 MB
Nelem=5760 mean_time=15.00 ms stddev_time=0.84 ms mem_used=1230 MB
Nelem=6080 mean_time=15.74 ms stddev_time=1.05 ms mem_used=1230 MB
Nelem=6400 mean_time=16.32 ms stddev_time=1.30 ms mem_used=1230 MB
Nelem=6720 mean_time=17.24 ms stddev_time=0.99 ms mem_used=1230 MB
Nelem=7040 mean_time=17.74 ms stddev_time=0.85 ms mem_used=1230 MB
Nelem=7360 mean_time=18.59 ms stddev_time=1.04 ms mem_used=1230 MB
Nelem=7680 mean_time=19.33 ms stddev_time=0.93 ms mem_used=1499 MB
Nelem=8000 mean_time=20.00 ms stddev_time=1.06 ms mem_used=1499 MB
Nelem=8320 mean_time=20.55 ms stddev_time=1.13 ms mem_used=1499 MB
Nelem=8640 mean_time=21.10 ms stddev_time=0.90 ms mem_used=1499 MB
Nelem=8960 mean_time=22.88 ms stddev_time=1.24 ms mem_used=1499 MB
Nelem=9280 mean_time=23.44 ms stddev_time=1.14 ms mem_used=1499 MB
Nelem=9600 mean_time=23.93 ms stddev_time=1.04 ms mem_used=1499 MB
Nelem=9920 mean_time=24.75 ms stddev_time=0.91 ms mem_used=1499 MB
Nelem=10240 mean_time=25.47 ms stddev_time=1.33 ms mem_used=1499 MB
Nelem=10560 mean_time=26.29 ms stddev_time=1.33 ms mem_used=1499 MB
Nelem=10880 mean_time=26.72 ms stddev_time=1.18 ms mem_used=1490 MB
Nelem=11200 mean_time=29.50 ms stddev_time=2.60 ms mem_used=1502 MB
Nelem=11520 mean_time=28.50 ms stddev_time=0.91 ms mem_used=1491 MB
Nelem=11840 mean_time=29.11 ms stddev_time=1.14 ms mem_used=1491 MB
Nelem=12160 mean_time=30.01 ms stddev_time=1.15 ms mem_used=1499 MB
Nelem=12480 mean_time=30.55 ms stddev_time=0.94 ms mem_used=1499 MB
Nelem=12800 mean_time=31.31 ms stddev_time=1.08 ms mem_used=1499 MB
Nelem=13120 mean_time=32.61 ms stddev_time=1.19 ms mem_used=1499 MB
Nelem=13440 mean_time=33.37 ms stddev_time=1.01 ms mem_used=1499 MB
Nelem=13760 mean_time=34.13 ms stddev_time=1.18 ms mem_used=1499 MB
Nelem=14080 mean_time=34.73 ms stddev_time=1.40 ms mem_used=1499 MB
Nelem=14400 mean_time=35.79 ms stddev_time=1.70 ms mem_used=2036 MB
Nelem=14720 mean_time=36.68 ms stddev_time=1.37 ms mem_used=2036 MB
Nelem=15040 mean_time=37.17 ms stddev_time=0.97 ms mem_used=2036 MB
Nelem=15360 mean_time=38.73 ms stddev_time=1.19 ms mem_used=2036 MB
Nelem=15680 mean_time=39.80 ms stddev_time=1.04 ms mem_used=2036 MB
Nelem=16000 mean_time=40.87 ms stddev_time=1.46 ms mem_used=1996 MB
Nelem=16320 mean_time=41.89 ms stddev_time=1.01 ms mem_used=1996 MB
Nelem=16640 mean_time=43.36 ms stddev_time=1.08 ms mem_used=1996 MB
Nelem=16960 mean_time=44.87 ms stddev_time=1.35 ms mem_used=1996 MB
Nelem=17280 mean_time=46.04 ms stddev_time=0.96 ms mem_used=1996 MB
Nelem=17600 mean_time=47.96 ms stddev_time=1.47 ms mem_used=1996 MB
Nelem=17920 mean_time=49.01 ms stddev_time=1.35 ms mem_used=1996 MB
Nelem=18240 mean_time=50.04 ms stddev_time=1.34 ms mem_used=1956 MB
Nelem=18560 mean_time=51.34 ms stddev_time=1.49 ms mem_used=1956 MB
Nelem=18880 mean_time=52.16 ms stddev_time=1.20 ms mem_used=1956 MB
Nelem=19200 mean_time=53.19 ms stddev_time=1.20 ms mem_used=1956 MB
Nelem=19520 mean_time=54.03 ms stddev_time=0.96 ms mem_used=1956 MB
Nelem=19840 mean_time=55.68 ms stddev_time=1.05 ms mem_used=1956 MB
Nelem=20160 mean_time=56.88 ms stddev_time=1.12 ms mem_used=1956 MB
Nelem=20480 mean_time=57.49 ms stddev_time=1.50 ms mem_used=1956 MB
Nelem=20800 mean_time=60.40 ms stddev_time=3.51 ms mem_used=1959 MB
Nelem=21120 mean_time=61.30 ms stddev_time=3.90 ms mem_used=1959 MB
Nelem=21440 mean_time=60.74 ms stddev_time=1.05 ms mem_used=1948 MB
Nelem=21760 mean_time=61.66 ms stddev_time=1.29 ms mem_used=1948 MB
Nelem=22080 mean_time=63.35 ms stddev_time=1.11 ms mem_used=1948 MB
Nelem=22400 mean_time=64.70 ms stddev_time=1.16 ms mem_used=1948 MB
Nelem=22720 mean_time=65.63 ms stddev_time=0.95 ms mem_used=1948 MB
Nelem=23040 mean_time=67.09 ms stddev_time=1.02 ms mem_used=1948 MB
Nelem=23360 mean_time=68.40 ms stddev_time=1.15 ms mem_used=1948 MB
Nelem=23680 mean_time=69.76 ms stddev_time=0.88 ms mem_used=1948 MB
Nelem=24000 mean_time=71.55 ms stddev_time=0.94 ms mem_used=1948 MB
Nelem=24320 mean_time=73.04 ms stddev_time=1.46 ms mem_used=1948 MB
Nelem=24640 mean_time=74.53 ms stddev_time=1.28 ms mem_used=1948 MB
Nelem=24960 mean_time=76.03 ms stddev_time=1.07 ms mem_used=1948 MB
Nelem=25280 mean_time=77.59 ms stddev_time=0.88 ms mem_used=1948 MB
"""
time_x = []
time_y = []
time_y_err = []
gpu_mem_use = []
for line in timing_output.split("\n"):
if len(line)>0:
spl = line.split()
time_x.append(int(spl[0].split("=")[1]))
time_y.append(float(spl[1].split("=")[1]))
time_y_err.append(float(spl[3].split("=")[1]))
gpu_mem_use.append(float(spl[5].split("=")[1]))
import glob
nelem = []
for fi in glob.glob("../data/TTbar_14TeV_TuneCUETP8M1_cfi/raw/*.pkl"):
d = pickle.load(open(fi, "rb"))
for elem in d:
X = elem["Xelem"][(elem["Xelem"]["typ"]!=2)&(elem["Xelem"]["typ"]!=3)]
nelem.append(X.shape[0])
plt.figure(figsize=(5,5))
ax = plt.axes()
plt.hist(nelem, bins=np.linspace(2000,6000,100));
plt.ylabel("Number of events / bin")
plt.xlabel("PFElements per event")
cms_label()
sample_label(ax, physics_process="ttbar")
plt.figure(figsize=(10, 3))
plt.errorbar(time_x, time_y, yerr=time_y_err, marker=".", label="MLPF")
plt.axvline(np.mean(nelem)-np.std(nelem), color="black", ls="--", lw=1.0, label=r"$t\bar{t}$+PU Run 3")
plt.axvline(np.mean(nelem)+np.std(nelem), color="black", ls="--", lw=1.0)
#plt.xticks(time_x, time_x);
plt.xlim(0,30000)
plt.ylim(0,100)
plt.ylabel("Average runtime per event [ms]")
plt.xlabel("PFElements per event")
plt.legend(frameon=False)
cms_label(x1=0.17, x2=0.8)
plt.savefig("runtime_scaling.pdf", bbox_inches="tight")
plt.savefig("runtime_scaling.png", bbox_inches="tight", dpi=300)
plt.figure(figsize=(10, 3))
plt.plot(time_x, gpu_mem_use, marker=".", label="MLPF")
plt.axvline(np.mean(nelem)-np.std(nelem), color="black", ls="--", lw=1.0, label=r"$t\bar{t}$+PU Run 3")
plt.axvline(np.mean(nelem)+np.std(nelem), color="black", ls="--", lw=1.0)
#plt.xticks(time_x, time_x);
plt.xlim(0,30000)
plt.ylim(0,3000)
plt.ylabel("Maximum GPU memory used [MB]")
plt.xlabel("PFElements per event")
plt.legend(frameon=False, loc=4)
cms_label(x1=0.17, x2=0.8)
plt.savefig("memory_scaling.pdf", bbox_inches="tight")
plt.savefig("memory_scaling.png", bbox_inches="tight", dpi=300)
```
| github_jupyter |
```
import pandas as pd
import pyspark.sql.functions as F
from datetime import datetime
from pyspark.sql.types import *
from pyspark import StorageLevel
import numpy as np
pd.set_option("display.max_rows", 1000)
pd.set_option("display.max_columns", 1000)
pd.set_option("mode.chained_assignment", None)
from pyspark.ml import Pipeline
from pyspark.ml.classification import GBTClassifier
from pyspark.ml.feature import IndexToString, StringIndexer, VectorIndexer
# from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.ml.feature import OneHotEncoderEstimator, StringIndexer, VectorAssembler
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
from pyspark.sql import Row
from pyspark.ml.linalg import Vectors
# !pip install scikit-plot
import sklearn
import scikitplot as skplt
from sklearn.metrics import classification_report, confusion_matrix, precision_score
```
<hr />
<hr />
<hr />
```
result_schema = StructType([
StructField('experiment_filter', StringType(), True),
StructField('undersampling_method', StringType(), True),
StructField('undersampling_column', StringType(), True),
StructField('filename', StringType(), True),
StructField('experiment_id', StringType(), True),
StructField('n_covid', IntegerType(), True),
StructField('n_not_covid', IntegerType(), True),
StructField('model_name', StringType(), True),
StructField('model_seed', StringType(), True),
StructField('model_maxIter', IntegerType(), True),
StructField('model_maxDepth', IntegerType(), True),
StructField('model_maxBins', IntegerType(), True),
StructField('model_minInstancesPerNode', IntegerType(), True),
StructField('model_minInfoGain', FloatType(), True),
StructField('model_featureSubsetStrategy', StringType(), True),
StructField('model_n_estimators', IntegerType(), True),
StructField('model_learning_rate', FloatType(), True),
StructField('model_impurity', StringType(), True),
StructField('model_AUC_ROC', StringType(), True),
StructField('model_AUC_PR', StringType(), True),
StructField('model_covid_precision', StringType(), True),
StructField('model_covid_recall', StringType(), True),
StructField('model_covid_f1', StringType(), True),
StructField('model_not_covid_precision', StringType(), True),
StructField('model_not_covid_recall', StringType(), True),
StructField('model_not_covid_f1', StringType(), True),
StructField('model_avg_precision', StringType(), True),
StructField('model_avg_recall', StringType(), True),
StructField('model_avg_f1', StringType(), True),
StructField('model_avg_acc', StringType(), True),
StructField('model_TP', StringType(), True),
StructField('model_TN', StringType(), True),
StructField('model_FN', StringType(), True),
StructField('model_FP', StringType(), True),
StructField('model_time_exec', StringType(), True),
StructField('model_col_set', StringType(), True)
])
```
<hr />
<hr />
<hr />
```
# undersamp_col = ['03-STRSAMP-AG', '04-STRSAMP-EW']
# dfs = ['ds-1', 'ds-2', 'ds-3']
# cols_sets = ['cols_set_1', 'cols_set_2', 'cols_set_3']
undersamp_col = ['03-STRSAMP-AG']
dfs = ['ds-3']
cols_sets = ['cols_set_3']
# lists of params
model_maxIter = [20, 50, 100]
model_maxDepth = [3, 5, 7]
model_maxBins = [32, 64]
# model_learningRate = [0.01, 0.1, 0.5]
# model_loss = ['logLoss', 'leastSquaresError', 'leastAbsoluteError']
list_of_param_dicts = []
for maxIter in model_maxIter:
for maxDepth in model_maxDepth:
for maxBins in model_maxBins:
params_dict = {}
params_dict['maxIter'] = maxIter
params_dict['maxDepth'] = maxDepth
params_dict['maxBins'] = maxBins
list_of_param_dicts.append(params_dict)
print("There is {} set of params.".format(len(list_of_param_dicts)))
# list_of_param_dicts
prefix = 'gs://ai-covid19-datalake/trusted/experiment_map/'
```
<hr />
<hr />
<hr />
```
# filename = 'gs://ai-covid19-datalake/trusted/experiment_map/03-STRSAMP-AG/ds-1/cols_set_1/experiment0.parquet'
# df = spark.read.parquet(filename)
# df.limit(2).toPandas()
# params_dict = {'maxIter': 100,
# 'maxDepth': 3,
# 'maxBins': 32,
# 'learningRate': 0.5,
# 'loss': 'leastAbsoluteError'}
# cols = 'cols_set_1'
# experiment_filter = 'ds-1'
# undersampling_method = '03-STRSAMP-AG',
# experiment_id = 0
# run_gbt(df, params_dict, cols, filename, experiment_filter, undersampling_method, experiment_id)
```
<hr />
<hr />
<hr />
```
def run_gbt(exp_df, params_dict, cols, filename, experiment_filter,
undersampling_method, experiment_id):
import time
start_time = time.time()
n_covid = exp_df.filter(F.col('CLASSI_FIN') == 1.0).count()
n_not_covid = exp_df.filter(F.col('CLASSI_FIN') == 0.0).count()
id_cols = ['NU_NOTIFIC', 'CLASSI_FIN']
labelIndexer = StringIndexer(inputCol="CLASSI_FIN", outputCol="indexedLabel").fit(exp_df)
input_cols = [x for x in exp_df.columns if x not in id_cols]
assembler = VectorAssembler(inputCols = input_cols, outputCol= 'features')
exp_df = assembler.transform(exp_df)
# Automatically identify categorical features, and index them.
# Set maxCategories so features with > 4 distinct values are treated as continuous.
featureIndexer = VectorIndexer(inputCol="features", outputCol="indexedFeatures", maxCategories=30).fit(exp_df)
# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = exp_df.randomSplit([0.7, 0.3])
trainingData = trainingData.persist(StorageLevel.MEMORY_ONLY)
testData = testData.persist(StorageLevel.MEMORY_ONLY)
# Train a RandomForest model.
gbt = GBTClassifier(labelCol = "indexedLabel", featuresCol = "indexedFeatures",
maxIter = params_dict['maxIter'],
maxDepth = params_dict['maxDepth'],
maxBins = params_dict['maxBins'])
# Convert indexed labels back to original labels.
labelConverter = IndexToString(inputCol="prediction", outputCol="predictedLabel",
labels=labelIndexer.labels)
# Chain indexers and forest in a Pipeline
pipeline = Pipeline(stages=[labelIndexer, featureIndexer, gbt, labelConverter])
# Train model. This also runs the indexers.
model = pipeline.fit(trainingData)
# Make predictions.
predictions = model.transform(testData)
pred = predictions.select(['CLASSI_FIN', 'predictedLabel'])\
.withColumn('predictedLabel', F.col('predictedLabel').cast('double'))\
.withColumn('predictedLabel', F.when(F.col('predictedLabel') == 1.0, 'covid').otherwise('n-covid'))\
.withColumn('CLASSI_FIN', F.when(F.col('CLASSI_FIN') == 1.0, 'covid').otherwise('n-covid'))\
.toPandas()
y_true = pred['CLASSI_FIN'].tolist()
y_pred = pred['predictedLabel'].tolist()
report = classification_report(y_true, y_pred, output_dict=True)
evaluator_ROC = BinaryClassificationEvaluator(labelCol="indexedLabel", rawPredictionCol="prediction", metricName="areaUnderROC")
accuracy_ROC = evaluator_ROC.evaluate(predictions)
evaluator_PR = BinaryClassificationEvaluator(labelCol="indexedLabel", rawPredictionCol="prediction", metricName="areaUnderPR")
accuracy_PR = evaluator_PR.evaluate(predictions)
conf_matrix = confusion_matrix(y_true, y_pred)
result_dict = {}
result_dict['experiment_filter'] = experiment_filter
result_dict['undersampling_method'] = undersampling_method
result_dict['filename'] = filename
result_dict['experiment_id'] = experiment_id
result_dict['n_covid'] = n_covid
result_dict['n_not_covid'] = n_not_covid
result_dict['model_name'] = 'GBT'
result_dict['params'] = params_dict
result_dict['model_AUC_ROC'] = accuracy_ROC
result_dict['model_AUC_PR'] = accuracy_PR
result_dict['model_covid_precision'] = report['covid']['precision']
result_dict['model_covid_recall'] = report['covid']['recall']
result_dict['model_covid_f1'] = report['covid']['f1-score']
result_dict['model_not_covid_precision'] = report['n-covid']['precision']
result_dict['model_not_covid_recall'] = report['n-covid']['recall']
result_dict['model_not_covid_f1'] = report['n-covid']['f1-score']
result_dict['model_avg_precision'] = report['macro avg']['precision']
result_dict['model_avg_recall'] = report['macro avg']['recall']
result_dict['model_avg_f1'] = report['macro avg']['f1-score']
result_dict['model_avg_acc'] = report['accuracy']
result_dict['model_TP'] = conf_matrix[0][0]
result_dict['model_TN'] = conf_matrix[1][1]
result_dict['model_FN'] = conf_matrix[0][1]
result_dict['model_FP'] = conf_matrix[1][0]
result_dict['model_time_exec'] = time.time() - start_time
result_dict['model_col_set'] = cols
return result_dict
```
<hr />
<hr />
<hr />
# Running GBT on 10 samples for each experiment
### 3x col sets -> ['cols_set_1', 'cols_set_2', 'cols_set_3']
### 3x model_maxIter -> [100, 200, 300]
### 3x model_maxDepth -> [5, 10, 15]
### 3x model_maxBins -> [16, 32, 64]
Total: 10 * 3 * 3 * 3 * 3 = 810
```
experiments = []
```
### Datasets: strat_samp_lab_agegrp
```
for uc in undersamp_col:
for ds in dfs:
for col_set in cols_sets:
for params_dict in list_of_param_dicts:
for id_exp in range(50):
filename = prefix + uc + '/' + ds + '/' + col_set + '/' + 'experiment' + str(id_exp) + '.parquet'
exp_dataframe = spark.read.parquet(filename)
# if 'SG_UF_NOT' in exp_dataframe.columns:
# exp_dataframe = exp_dataframe.withColumn('SG_UF_NOT', F.col('SG_UF_NOT').cast('float'))
print('read {}'.format(filename))
undersampling_method = uc
experiment_filter = ds
experiment_id = id_exp
try:
model = run_gbt(exp_dataframe, params_dict, col_set, filename, experiment_filter, undersampling_method, experiment_id)
experiments.append(model)
print("Parameters ==> {}\n Results: \n AUC_PR: {} \n Precision: {} \n Time: {}".format(str(params_dict), str(model['model_AUC_PR']), str(model['model_avg_precision']), str(model['model_time_exec'])))
print('=========================== \n')
except:
print('=========== W A R N I N G =========== \n')
print('Something wrong with the exp: {}, {}, {}'.format(filename, params_dict, col_set))
```
<hr />
<hr />
<hr />
```
for i in range(len(experiments)):
for d in list(experiments[i].keys()):
experiments[i][d] = str(experiments[i][d])
# experiments
cols = ['experiment_filter', 'undersampling_method', 'filename', 'experiment_id', 'n_covid', 'n_not_covid', 'model_name', 'params', 'model_AUC_ROC', 'model_AUC_PR', 'model_covid_precision', 'model_covid_recall', 'model_covid_f1', 'model_not_covid_precision', 'model_not_covid_recall', 'model_not_covid_f1', 'model_avg_precision', 'model_avg_recall', 'model_avg_f1', 'model_avg_acc', 'model_TP', 'model_TN', 'model_FN', 'model_FP', 'model_time_exec', 'model_col_set']
intermed_results = spark.createDataFrame(data=experiments).select(cols)
intermed_results.toPandas()
intermed_results.write.parquet('gs://ai-covid19-datalake/trusted/intermed_results/STRSAMP/GBT_experiments-AG-ds3-cs3.parquet', mode='overwrite')
print('finished')
intermed_results.show()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/cdosrunwild/glide-text2im/blob/main/Copy_of_Disco_Diffusion_v4_1_%5Bw_Video_Inits%2C_Recovery_%26_DDIM_Sharpen%5D.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Disco Diffusion v4.1 - Now with Video Inits, Recovery, DDIM Sharpen and improved UI
In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model
For issues, message [@Somnai_dreams](https://twitter.com/Somnai_dreams) or Somnai#6855
Credits & Changelog ⬇️
Original notebook by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses either OpenAI's 256x256 unconditional ImageNet or Katherine Crowson's fine-tuned 512x512 diffusion model (https://github.com/openai/guided-diffusion), together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images.
Modified by Daniel Russell (https://github.com/russelldc, https://twitter.com/danielrussruss) to include (hopefully) optimal params for quick generations in 15-100 timesteps rather than 1000, as well as more robust augmentations.
Further improvements from Dango233 and nsheppard helped improve the quality of diffusion in general, and especially so for shorter runs like this notebook aims to achieve.
Vark added code to load in multiple Clip models at once, which all prompts are evaluated against, which may greatly improve accuracy.
The latest zoom, pan, rotation, and keyframes features were taken from Chigozie Nri's VQGAN Zoom Notebook (https://github.com/chigozienri, https://twitter.com/chigozienri)
Advanced DangoCutn Cutout method is also from Dango223.
--
I, Somnai (https://twitter.com/Somnai_dreams), have added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below.
```
# @title Licensed under the MIT License
# Copyright (c) 2021 Katherine Crowson
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#@title <- View Changelog
skip_for_run_all = True #@param {type: 'boolean'}
if skip_for_run_all == False:
print(
'''
v1 Update: Oct 29th 2021
QoL improvements added by Somnai (@somnai_dreams), including user friendly UI, settings+prompt saving and improved google drive folder organization.
v1.1 Update: Nov 13th 2021
Now includes sizing options, intermediate saves and fixed image prompts and perlin inits. unexposed batch option since it doesn't work
v2 Update: Nov 22nd 2021
Initial addition of Katherine Crowson's Secondary Model Method (https://colab.research.google.com/drive/1mpkrhOjoyzPeSWy2r7T8EYRaU7amYOOi#scrollTo=X5gODNAMEUCR)
Noticed settings were saving with the wrong name so corrected it. Let me know if you preferred the old scheme.
v3 Update: Dec 24th 2021
Implemented Dango's advanced cutout method
Added SLIP models, thanks to NeuralDivergent
Fixed issue with NaNs resulting in black images, with massive help and testing from @Softology
Perlin now changes properly within batches (not sure where this perlin_regen code came from originally, but thank you)
v4 Update: Jan 2021
Implemented Diffusion Zooming
Added Chigozie keyframing
Made a bunch of edits to processes
v4.1 Update: Jan 14th 2021
Added video input mode
Added license that somehow went missing
Added improved prompt keyframing, fixed image_prompts and multiple prompts
Improved UI
Significant under the hood cleanup and improvement
Refined defaults for each mode
Added latent-diffusion SuperRes for sharpening
Added resume run mode
'''
)
from google.colab import drive
drive.mount('/content/drive')
```
#Tutorial
**Diffusion settings**
---
This section is outdated as of v2
Setting | Description | Default
--- | --- | ---
**Your vision:**
`text_prompts` | A description of what you'd like the machine to generate. Think of it like writing the caption below your image on a website. | N/A
`image_prompts` | Think of these images more as a description of their contents. | N/A
**Image quality:**
`clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000
`tv_scale` | Controls the smoothness of the final output. | 150
`range_scale` | Controls how far out of range RGB values are allowed to be. | 150
`sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0
`cutn` | Controls how many crops to take from the image. | 16
`cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts | 2
**Init settings:**
`init_image` | URL or local path | None
`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0
`skip_steps Controls the starting point along the diffusion timesteps | 0
`perlin_init` | Option to start with random perlin noise | False
`perlin_mode` | ('gray', 'color') | 'mixed'
**Advanced:**
`skip_augs` |Controls whether to skip torchvision augmentations | False
`randomize_class` |Controls whether the imagenet class is randomly changed each iteration | True
`clip_denoised` |Determines whether CLIP discriminates a noisy or denoised image | False
`clamp_grad` |Experimental: Using adaptive clip grad in the cond_fn | True
`seed` | Choose a random seed and print it at end of run for reproduction | random_seed
`fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False
`rand_mag` |Controls the magnitude of the random noise | 0.1
`eta` | DDIM hyperparameter | 0.5
..
**Model settings**
---
Setting | Description | Default
--- | --- | ---
**Diffusion:**
`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100
`diffusion_steps` || 1000
**Diffusion:**
`clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4
# 1. Set Up
```
#@title 1.1 Check GPU Status
!nvidia-smi -L
from google.colab import drive
#@title 1.2 Prepare Folders
#@markdown If you connect your Google Drive, you can save the final image of each run on your drive.
google_drive = True #@param {type:"boolean"}
#@markdown Click here if you'd like to save the diffusion model checkpoint file to (and/or load from) your Google Drive:
yes_please = True #@param {type:"boolean"}
if google_drive is True:
drive.mount('/content/drive')
root_path = '/content/drive/MyDrive/AI/Disco_Diffusion'
else:
root_path = '/content'
import os
from os import path
#Simple create paths taken with modifications from Datamosh's Batch VQGAN+CLIP notebook
def createPath(filepath):
if path.exists(filepath) == False:
os.makedirs(filepath)
print(f'Made {filepath}')
else:
print(f'filepath {filepath} exists.')
initDirPath = f'{root_path}/init_images'
createPath(initDirPath)
outDirPath = f'{root_path}/images_out'
createPath(outDirPath)
if google_drive and not yes_please or not google_drive:
model_path = '/content/models'
createPath(model_path)
if google_drive and yes_please:
model_path = f'{root_path}/models'
createPath(model_path)
# libraries = f'{root_path}/libraries'
# createPath(libraries)
#@title ### 1.3 Install and import dependencies
if google_drive is not True:
root_path = f'/content'
model_path = '/content/models'
model_256_downloaded = False
model_512_downloaded = False
model_secondary_downloaded = False
!git clone https://github.com/openai/CLIP
# !git clone https://github.com/facebookresearch/SLIP.git
!git clone https://github.com/crowsonkb/guided-diffusion
!git clone https://github.com/assafshocher/ResizeRight.git
!pip install -e ./CLIP
!pip install -e ./guided-diffusion
!pip install lpips datetime timm
!apt install imagemagick
import sys
# sys.path.append('./SLIP')
sys.path.append('./ResizeRight')
from dataclasses import dataclass
from functools import partial
import cv2
import pandas as pd
import gc
import io
import math
import timm
from IPython import display
import lpips
from PIL import Image, ImageOps
import requests
from glob import glob
import json
from types import SimpleNamespace
import torch
from torch import nn
from torch.nn import functional as F
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from tqdm.notebook import tqdm
sys.path.append('./CLIP')
sys.path.append('./guided-diffusion')
import clip
from resize_right import resize
# from models import SLIP_VITB16, SLIP, SLIP_VITL16
from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import random
from ipywidgets import Output
import hashlib
#SuperRes
!git clone https://github.com/CompVis/latent-diffusion.git
!git clone https://github.com/CompVis/taming-transformers
!pip install -e ./taming-transformers
!pip install ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb
#SuperRes
import ipywidgets as widgets
import os
sys.path.append(".")
sys.path.append('./taming-transformers')
from taming.models import vqgan # checking correct import from taming
from torchvision.datasets.utils import download_url
%cd '/content/latent-diffusion'
from functools import partial
from ldm.util import instantiate_from_config
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
# from ldm.models.diffusion.ddim import DDIMSampler
from ldm.util import ismap
%cd '/content'
from google.colab import files
from IPython.display import Image as ipyimg
from numpy import asarray
from einops import rearrange, repeat
import torch, torchvision
import time
from omegaconf import OmegaConf
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
import torch
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
if torch.cuda.get_device_capability(device) == (8,0): ## A100 fix thanks to Emad
print('Disabling CUDNN for A100 gpu', file=sys.stderr)
torch.backends.cudnn.enabled = False
#@title 1.4 Define necessary functions
# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869
def interp(t):
return 3 * t**2 - 2 * t ** 3
def perlin(width, height, scale=10, device=None):
gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device)
xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device)
ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device)
wx = 1 - interp(xs)
wy = 1 - interp(ys)
dots = 0
dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys)
dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys)
dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys))
dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys))
return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale)
def perlin_ms(octaves, width, height, grayscale, device=device):
out_array = [0.5] if grayscale else [0.5, 0.5, 0.5]
# out_array = [0.0] if grayscale else [0.0, 0.0, 0.0]
for i in range(1 if grayscale else 3):
scale = 2 ** len(octaves)
oct_width = width
oct_height = height
for oct in octaves:
p = perlin(oct_width, oct_height, scale, device)
out_array[i] += p * oct
scale //= 2
oct_width *= 2
oct_height *= 2
return torch.cat(out_array)
def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True):
out = perlin_ms(octaves, width, height, grayscale)
if grayscale:
out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0))
out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB')
else:
out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1])
out = TF.resize(size=(side_y, side_x), img=out)
out = TF.to_pil_image(out.clamp(0, 1).squeeze())
out = ImageOps.autocontrast(out)
return out
def regen_perlin():
if perlin_mode == 'color':
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)
elif perlin_mode == 'gray':
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
else:
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)
del init2
return init.expand(batch_size, -1, -1, -1)
def fetch(url_or_path):
if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):
r = requests.get(url_or_path)
r.raise_for_status()
fd = io.BytesIO()
fd.write(r.content)
fd.seek(0)
return fd
return open(url_or_path, 'rb')
def read_image_workaround(path):
"""OpenCV reads images as BGR, Pillow saves them as RGB. Work around
this incompatibility to avoid colour inversions."""
im_tmp = cv2.imread(path)
return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB)
def parse_prompt(prompt):
if prompt.startswith('http://') or prompt.startswith('https://'):
vals = prompt.rsplit(':', 2)
vals = [vals[0] + ':' + vals[1], *vals[2:]]
else:
vals = prompt.rsplit(':', 1)
vals = vals + ['', '1'][len(vals):]
return vals[0], float(vals[1])
def sinc(x):
return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))
def lanczos(x, a):
cond = torch.logical_and(-a < x, x < a)
out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))
return out / out.sum()
def ramp(ratio, width):
n = math.ceil(width / ratio + 1)
out = torch.empty([n])
cur = 0
for i in range(out.shape[0]):
out[i] = cur
cur += ratio
return torch.cat([-out[1:].flip([0]), out])[1:-1]
def resample(input, size, align_corners=True):
n, c, h, w = input.shape
dh, dw = size
input = input.reshape([n * c, 1, h, w])
if dh < h:
kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)
pad_h = (kernel_h.shape[0] - 1) // 2
input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')
input = F.conv2d(input, kernel_h[None, None, :, None])
if dw < w:
kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)
pad_w = (kernel_w.shape[0] - 1) // 2
input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')
input = F.conv2d(input, kernel_w[None, None, None, :])
input = input.reshape([n, c, h, w])
return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)
class MakeCutouts(nn.Module):
def __init__(self, cut_size, cutn, skip_augs=False):
super().__init__()
self.cut_size = cut_size
self.cutn = cutn
self.skip_augs = skip_augs
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=15, translate=(0.1, 0.1)),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomPerspective(distortion_scale=0.4, p=0.7),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.15),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
# T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
])
def forward(self, input):
input = T.Pad(input.shape[2]//4, fill=0)(input)
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
cutouts = []
for ch in range(self.cutn):
if ch > self.cutn - self.cutn//4:
cutout = input.clone()
else:
size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.))
offsetx = torch.randint(0, abs(sideX - size + 1), ())
offsety = torch.randint(0, abs(sideY - size + 1), ())
cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
if not self.skip_augs:
cutout = self.augs(cutout)
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
del cutout
cutouts = torch.cat(cutouts, dim=0)
return cutouts
cutout_debug = False
padargs = {}
class MakeCutoutsDango(nn.Module):
def __init__(self, cut_size,
Overview=4,
InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2
):
super().__init__()
self.cut_size = cut_size
self.Overview = Overview
self.InnerCrop = InnerCrop
self.IC_Size_Pow = IC_Size_Pow
self.IC_Grey_P = IC_Grey_P
if args.animation_mode == 'None':
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.1),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
])
elif args.animation_mode == 'Video Input':
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=15, translate=(0.1, 0.1)),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomPerspective(distortion_scale=0.4, p=0.7),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.15),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
# T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
])
elif args.animation_mode == '2D':
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.4),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.1),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3),
])
def forward(self, input):
cutouts = []
gray = T.Grayscale(3)
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
l_size = max(sideX, sideY)
output_shape = [1,3,self.cut_size,self.cut_size]
output_shape_2 = [1,3,self.cut_size+2,self.cut_size+2]
pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs)
cutout = resize(pad_input, out_shape=output_shape)
if self.Overview>0:
if self.Overview<=4:
if self.Overview>=1:
cutouts.append(cutout)
if self.Overview>=2:
cutouts.append(gray(cutout))
if self.Overview>=3:
cutouts.append(TF.hflip(cutout))
if self.Overview==4:
cutouts.append(gray(TF.hflip(cutout)))
else:
cutout = resize(pad_input, out_shape=output_shape)
for _ in range(self.Overview):
cutouts.append(cutout)
if cutout_debug:
TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("/content/cutout_overview0.jpg",quality=99)
if self.InnerCrop >0:
for i in range(self.InnerCrop):
size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size)
offsetx = torch.randint(0, sideX - size + 1, ())
offsety = torch.randint(0, sideY - size + 1, ())
cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
if i <= int(self.IC_Grey_P * self.InnerCrop):
cutout = gray(cutout)
cutout = resize(cutout, out_shape=output_shape)
cutouts.append(cutout)
if cutout_debug:
TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("/content/cutout_InnerCrop.jpg",quality=99)
cutouts = torch.cat(cutouts)
if skip_augs is not True: cutouts=self.augs(cutouts)
return cutouts
def spherical_dist_loss(x, y):
x = F.normalize(x, dim=-1)
y = F.normalize(y, dim=-1)
return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
def tv_loss(input):
"""L2 total variation loss, as in Mahendran et al."""
input = F.pad(input, (0, 1, 0, 1), 'replicate')
x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]
y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]
return (x_diff**2 + y_diff**2).mean([1, 2, 3])
def range_loss(input):
return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])
stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete
def do_run():
seed = args.seed
print(range(args.start_frame, args.max_frames))
for frame_num in range(args.start_frame, args.max_frames):
if stop_on_next_loop:
break
display.clear_output(wait=True)
# Print Frame progress if animation mode is on
if args.animation_mode != "None":
batchBar = tqdm(range(args.max_frames), desc ="Frames")
batchBar.n = frame_num
batchBar.refresh()
# Inits if not video frames
if args.animation_mode != "Video Input":
if args.init_image == '':
init_image = None
else:
init_image = args.init_image
init_scale = args.init_scale
skip_steps = args.skip_steps
if args.animation_mode == "2D":
if args.key_frames:
angle = args.angle_series[frame_num]
zoom = args.zoom_series[frame_num]
translation_x = args.translation_x_series[frame_num]
translation_y = args.translation_y_series[frame_num]
print(
f'angle: {angle}',
f'zoom: {zoom}',
f'translation_x: {translation_x}',
f'translation_y: {translation_y}',
)
if frame_num > 0:
seed = seed + 1
if resume_run and frame_num == start_frame:
img_0 = cv2.imread(batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png")
else:
img_0 = cv2.imread('prevFrame.png')
center = (1*img_0.shape[1]//2, 1*img_0.shape[0]//2)
trans_mat = np.float32(
[[1, 0, translation_x],
[0, 1, translation_y]]
)
rot_mat = cv2.getRotationMatrix2D( center, angle, zoom )
trans_mat = np.vstack([trans_mat, [0,0,1]])
rot_mat = np.vstack([rot_mat, [0,0,1]])
transformation_matrix = np.matmul(rot_mat, trans_mat)
img_0 = cv2.warpPerspective(
img_0,
transformation_matrix,
(img_0.shape[1], img_0.shape[0]),
borderMode=cv2.BORDER_WRAP
)
cv2.imwrite('prevFrameScaled.png', img_0)
init_image = 'prevFrameScaled.png'
init_scale = args.frames_scale
skip_steps = args.calc_frames_skip_steps
if args.animation_mode == "Video Input":
seed = seed + 1
init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg'
init_scale = args.frames_scale
skip_steps = args.calc_frames_skip_steps
loss_values = []
if seed is not None:
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
target_embeds, weights = [], []
if args.prompts_series is not None and frame_num >= len(args.prompts_series):
frame_prompt = args.prompts_series[-1]
elif args.prompts_series is not None:
frame_prompt = args.prompts_series[frame_num]
else:
frame_prompt = []
print(args.image_prompts_series)
if args.image_prompts_series is not None and frame_num >= len(args.image_prompts_series):
image_prompt = args.image_prompts_series[-1]
elif args.image_prompts_series is not None:
image_prompt = args.image_prompts_series[frame_num]
else:
image_prompt = []
print(f'Frame Prompt: {frame_prompt}')
model_stats = []
for clip_model in clip_models:
cutn = 16
model_stat = {"clip_model":None,"target_embeds":[],"make_cutouts":None,"weights":[]}
model_stat["clip_model"] = clip_model
for prompt in frame_prompt:
txt, weight = parse_prompt(prompt)
txt = clip_model.encode_text(clip.tokenize(prompt).to(device)).float()
if args.fuzzy_prompt:
for i in range(25):
model_stat["target_embeds"].append((txt + torch.randn(txt.shape).cuda() * args.rand_mag).clamp(0,1))
model_stat["weights"].append(weight)
else:
model_stat["target_embeds"].append(txt)
model_stat["weights"].append(weight)
if image_prompt:
model_stat["make_cutouts"] = MakeCutouts(clip_model.visual.input_resolution, cutn, skip_augs=skip_augs)
for prompt in image_prompt:
path, weight = parse_prompt(prompt)
img = Image.open(fetch(path)).convert('RGB')
img = TF.resize(img, min(side_x, side_y, *img.size), T.InterpolationMode.LANCZOS)
batch = model_stat["make_cutouts"](TF.to_tensor(img).to(device).unsqueeze(0).mul(2).sub(1))
embed = clip_model.encode_image(normalize(batch)).float()
if fuzzy_prompt:
for i in range(25):
model_stat["target_embeds"].append((embed + torch.randn(embed.shape).cuda() * rand_mag).clamp(0,1))
weights.extend([weight / cutn] * cutn)
else:
model_stat["target_embeds"].append(embed)
model_stat["weights"].extend([weight / cutn] * cutn)
model_stat["target_embeds"] = torch.cat(model_stat["target_embeds"])
model_stat["weights"] = torch.tensor(model_stat["weights"], device=device)
if model_stat["weights"].sum().abs() < 1e-3:
raise RuntimeError('The weights must not sum to 0.')
model_stat["weights"] /= model_stat["weights"].sum().abs()
model_stats.append(model_stat)
init = None
if init_image is not None:
init = Image.open(fetch(init_image)).convert('RGB')
init = init.resize((args.side_x, args.side_y), Image.LANCZOS)
init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1)
if args.perlin_init:
if args.perlin_mode == 'color':
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)
elif args.perlin_mode == 'gray':
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
else:
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
# init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device)
init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)
del init2
cur_t = None
def cond_fn(x, t, y=None):
with torch.enable_grad():
x_is_NaN = False
x = x.detach().requires_grad_()
n = x.shape[0]
if use_secondary_model is True:
alpha = torch.tensor(diffusion.sqrt_alphas_cumprod[cur_t], device=device, dtype=torch.float32)
sigma = torch.tensor(diffusion.sqrt_one_minus_alphas_cumprod[cur_t], device=device, dtype=torch.float32)
cosine_t = alpha_sigma_to_t(alpha, sigma)
out = secondary_model(x, cosine_t[None].repeat([n])).pred
fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]
x_in = out * fac + x * (1 - fac)
x_in_grad = torch.zeros_like(x_in)
else:
my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t
out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y})
fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]
x_in = out['pred_xstart'] * fac + x * (1 - fac)
x_in_grad = torch.zeros_like(x_in)
for model_stat in model_stats:
for i in range(args.cutn_batches):
t_int = int(t.item())+1 #errors on last step without +1, need to find source
#when using SLIP Base model the dimensions need to be hard coded to avoid AttributeError: 'VisionTransformer' object has no attribute 'input_resolution'
try:
input_resolution=model_stat["clip_model"].visual.input_resolution
except:
input_resolution=224
cuts = MakeCutoutsDango(input_resolution,
Overview= args.cut_overview[1000-t_int],
InnerCrop = args.cut_innercut[1000-t_int], IC_Size_Pow=args.cut_ic_pow, IC_Grey_P = args.cut_icgray_p[1000-t_int]
)
clip_in = normalize(cuts(x_in.add(1).div(2)))
image_embeds = model_stat["clip_model"].encode_image(clip_in).float()
dists = spherical_dist_loss(image_embeds.unsqueeze(1), model_stat["target_embeds"].unsqueeze(0))
dists = dists.view([args.cut_overview[1000-t_int]+args.cut_innercut[1000-t_int], n, -1])
losses = dists.mul(model_stat["weights"]).sum(2).mean(0)
loss_values.append(losses.sum().item()) # log loss, probably shouldn't do per cutn_batch
x_in_grad += torch.autograd.grad(losses.sum() * clip_guidance_scale, x_in)[0] / cutn_batches
tv_losses = tv_loss(x_in)
if use_secondary_model is True:
range_losses = range_loss(out)
else:
range_losses = range_loss(out['pred_xstart'])
sat_losses = torch.abs(x_in - x_in.clamp(min=-1,max=1)).mean()
loss = tv_losses.sum() * tv_scale + range_losses.sum() * range_scale + sat_losses.sum() * sat_scale
if init is not None and args.init_scale:
init_losses = lpips_model(x_in, init)
loss = loss + init_losses.sum() * args.init_scale
x_in_grad += torch.autograd.grad(loss, x_in)[0]
if torch.isnan(x_in_grad).any()==False:
grad = -torch.autograd.grad(x_in, x, x_in_grad)[0]
else:
# print("NaN'd")
x_is_NaN = True
grad = torch.zeros_like(x)
if args.clamp_grad and x_is_NaN == False:
magnitude = grad.square().mean().sqrt()
return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max,
return grad
if model_config['timestep_respacing'].startswith('ddim'):
sample_fn = diffusion.ddim_sample_loop_progressive
else:
sample_fn = diffusion.p_sample_loop_progressive
image_display = Output()
for i in range(args.n_batches):
if args.animation_mode == 'None':
display.clear_output(wait=True)
batchBar = tqdm(range(args.n_batches), desc ="Batches")
batchBar.n = i
batchBar.refresh()
print('')
display.display(image_display)
gc.collect()
torch.cuda.empty_cache()
cur_t = diffusion.num_timesteps - skip_steps - 1
total_steps = cur_t
if perlin_init:
init = regen_perlin()
if model_config['timestep_respacing'].startswith('ddim'):
samples = sample_fn(
model,
(batch_size, 3, args.side_y, args.side_x),
clip_denoised=clip_denoised,
model_kwargs={},
cond_fn=cond_fn,
progress=True,
skip_timesteps=skip_steps,
init_image=init,
randomize_class=randomize_class,
eta=eta,
)
else:
samples = sample_fn(
model,
(batch_size, 3, args.side_y, args.side_x),
clip_denoised=clip_denoised,
model_kwargs={},
cond_fn=cond_fn,
progress=True,
skip_timesteps=skip_steps,
init_image=init,
randomize_class=randomize_class,
)
# with run_display:
# display.clear_output(wait=True)
imgToSharpen = None
for j, sample in enumerate(samples):
cur_t -= 1
intermediateStep = False
if args.steps_per_checkpoint is not None:
if j % steps_per_checkpoint == 0 and j > 0:
intermediateStep = True
elif j in args.intermediate_saves:
intermediateStep = True
with image_display:
if j % args.display_rate == 0 or cur_t == -1 or intermediateStep == True:
for k, image in enumerate(sample['pred_xstart']):
# tqdm.write(f'Batch {i}, step {j}, output {k}:')
current_time = datetime.now().strftime('%y%m%d-%H%M%S_%f')
percent = math.ceil(j/total_steps*100)
if args.n_batches > 0:
#if intermediates are saved to the subfolder, don't append a step or percentage to the name
if cur_t == -1 and args.intermediates_in_subfolder is True:
save_num = f'{frame_num:04}' if animation_mode != "None" else i
filename = f'{args.batch_name}({args.batchNum})_{save_num}.png'
else:
#If we're working with percentages, append it
if args.steps_per_checkpoint is not None:
filename = f'{args.batch_name}({args.batchNum})_{i:04}-{percent:02}%.png'
# Or else, iIf we're working with specific steps, append those
else:
filename = f'{args.batch_name}({args.batchNum})_{i:04}-{j:03}.png'
image = TF.to_pil_image(image.add(1).div(2).clamp(0, 1))
if j % args.display_rate == 0 or cur_t == -1:
image.save('progress.png')
display.clear_output(wait=True)
display.display(display.Image('progress.png'))
if args.steps_per_checkpoint is not None:
if j % args.steps_per_checkpoint == 0 and j > 0:
if args.intermediates_in_subfolder is True:
image.save(f'{partialFolder}/{filename}')
else:
image.save(f'{batchFolder}/{filename}')
else:
if j in args.intermediate_saves:
if args.intermediates_in_subfolder is True:
image.save(f'{partialFolder}/{filename}')
else:
image.save(f'{batchFolder}/{filename}')
if cur_t == -1:
if frame_num == 0:
save_settings()
if args.animation_mode != "None":
image.save('prevFrame.png')
if args.sharpen_preset != "Off" and animation_mode == "None":
imgToSharpen = image
if args.keep_unsharp is True:
image.save(f'{unsharpenFolder}/{filename}')
else:
image.save(f'{batchFolder}/{filename}')
# if frame_num != args.max_frames-1:
# display.clear_output()
with image_display:
if args.sharpen_preset != "Off" and animation_mode == "None":
print('Starting Diffusion Sharpening...')
do_superres(imgToSharpen, f'{batchFolder}/{filename}')
display.clear_output()
plt.plot(np.array(loss_values), 'r')
def save_settings():
setting_list = {
'text_prompts': text_prompts,
'image_prompts': image_prompts,
'clip_guidance_scale': clip_guidance_scale,
'tv_scale': tv_scale,
'range_scale': range_scale,
'sat_scale': sat_scale,
# 'cutn': cutn,
'cutn_batches': cutn_batches,
'max_frames': max_frames,
'interp_spline': interp_spline,
# 'rotation_per_frame': rotation_per_frame,
'init_image': init_image,
'init_scale': init_scale,
'skip_steps': skip_steps,
# 'zoom_per_frame': zoom_per_frame,
'frames_scale': frames_scale,
'frames_skip_steps': frames_skip_steps,
'perlin_init': perlin_init,
'perlin_mode': perlin_mode,
'skip_augs': skip_augs,
'randomize_class': randomize_class,
'clip_denoised': clip_denoised,
'clamp_grad': clamp_grad,
'clamp_max': clamp_max,
'seed': seed,
'fuzzy_prompt': fuzzy_prompt,
'rand_mag': rand_mag,
'eta': eta,
'width': width_height[0],
'height': width_height[1],
'diffusion_model': diffusion_model,
'use_secondary_model': use_secondary_model,
'steps': steps,
'diffusion_steps': diffusion_steps,
'ViTB32': ViTB32,
'ViTB16': ViTB16,
'ViTL14': ViTL14,
'RN101': RN101,
'RN50': RN50,
'RN50x4': RN50x4,
'RN50x16': RN50x16,
'RN50x64': RN50x64,
'cut_overview': str(cut_overview),
'cut_innercut': str(cut_innercut),
'cut_ic_pow': cut_ic_pow,
'cut_icgray_p': str(cut_icgray_p),
'key_frames': key_frames,
'max_frames': max_frames,
'angle': angle,
'zoom': zoom,
'translation_x': translation_x,
'translation_y': translation_y,
'video_init_path':video_init_path,
'extract_nth_frame':extract_nth_frame,
}
# print('Settings:', setting_list)
with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings
json.dump(setting_list, f, ensure_ascii=False, indent=4)
#@title 1.5 Define the secondary diffusion model
def append_dims(x, n):
return x[(Ellipsis, *(None,) * (n - x.ndim))]
def expand_to_planes(x, shape):
return append_dims(x, len(shape)).repeat([1, 1, *shape[2:]])
def alpha_sigma_to_t(alpha, sigma):
return torch.atan2(sigma, alpha) * 2 / math.pi
def t_to_alpha_sigma(t):
return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2)
@dataclass
class DiffusionOutput:
v: torch.Tensor
pred: torch.Tensor
eps: torch.Tensor
class ConvBlock(nn.Sequential):
def __init__(self, c_in, c_out):
super().__init__(
nn.Conv2d(c_in, c_out, 3, padding=1),
nn.ReLU(inplace=True),
)
class SkipBlock(nn.Module):
def __init__(self, main, skip=None):
super().__init__()
self.main = nn.Sequential(*main)
self.skip = skip if skip else nn.Identity()
def forward(self, input):
return torch.cat([self.main(input), self.skip(input)], dim=1)
class FourierFeatures(nn.Module):
def __init__(self, in_features, out_features, std=1.):
super().__init__()
assert out_features % 2 == 0
self.weight = nn.Parameter(torch.randn([out_features // 2, in_features]) * std)
def forward(self, input):
f = 2 * math.pi * input @ self.weight.T
return torch.cat([f.cos(), f.sin()], dim=-1)
class SecondaryDiffusionImageNet(nn.Module):
def __init__(self):
super().__init__()
c = 64 # The base channel count
self.timestep_embed = FourierFeatures(1, 16)
self.net = nn.Sequential(
ConvBlock(3 + 16, c),
ConvBlock(c, c),
SkipBlock([
nn.AvgPool2d(2),
ConvBlock(c, c * 2),
ConvBlock(c * 2, c * 2),
SkipBlock([
nn.AvgPool2d(2),
ConvBlock(c * 2, c * 4),
ConvBlock(c * 4, c * 4),
SkipBlock([
nn.AvgPool2d(2),
ConvBlock(c * 4, c * 8),
ConvBlock(c * 8, c * 4),
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
]),
ConvBlock(c * 8, c * 4),
ConvBlock(c * 4, c * 2),
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
]),
ConvBlock(c * 4, c * 2),
ConvBlock(c * 2, c),
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
]),
ConvBlock(c * 2, c),
nn.Conv2d(c, 3, 3, padding=1),
)
def forward(self, input, t):
timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape)
v = self.net(torch.cat([input, timestep_embed], dim=1))
alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))
pred = input * alphas - v * sigmas
eps = input * sigmas + v * alphas
return DiffusionOutput(v, pred, eps)
class SecondaryDiffusionImageNet2(nn.Module):
def __init__(self):
super().__init__()
c = 64 # The base channel count
cs = [c, c * 2, c * 2, c * 4, c * 4, c * 8]
self.timestep_embed = FourierFeatures(1, 16)
self.down = nn.AvgPool2d(2)
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
self.net = nn.Sequential(
ConvBlock(3 + 16, cs[0]),
ConvBlock(cs[0], cs[0]),
SkipBlock([
self.down,
ConvBlock(cs[0], cs[1]),
ConvBlock(cs[1], cs[1]),
SkipBlock([
self.down,
ConvBlock(cs[1], cs[2]),
ConvBlock(cs[2], cs[2]),
SkipBlock([
self.down,
ConvBlock(cs[2], cs[3]),
ConvBlock(cs[3], cs[3]),
SkipBlock([
self.down,
ConvBlock(cs[3], cs[4]),
ConvBlock(cs[4], cs[4]),
SkipBlock([
self.down,
ConvBlock(cs[4], cs[5]),
ConvBlock(cs[5], cs[5]),
ConvBlock(cs[5], cs[5]),
ConvBlock(cs[5], cs[4]),
self.up,
]),
ConvBlock(cs[4] * 2, cs[4]),
ConvBlock(cs[4], cs[3]),
self.up,
]),
ConvBlock(cs[3] * 2, cs[3]),
ConvBlock(cs[3], cs[2]),
self.up,
]),
ConvBlock(cs[2] * 2, cs[2]),
ConvBlock(cs[2], cs[1]),
self.up,
]),
ConvBlock(cs[1] * 2, cs[1]),
ConvBlock(cs[1], cs[0]),
self.up,
]),
ConvBlock(cs[0] * 2, cs[0]),
nn.Conv2d(cs[0], 3, 3, padding=1),
)
def forward(self, input, t):
timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape)
v = self.net(torch.cat([input, timestep_embed], dim=1))
alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))
pred = input * alphas - v * sigmas
eps = input * sigmas + v * alphas
return DiffusionOutput(v, pred, eps)
#@title 1.6 SuperRes Define
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def register_buffer(self, name, attr):
if type(attr) == torch.Tensor:
if attr.device != torch.device("cuda"):
attr = attr.to(torch.device("cuda"))
setattr(self, name, attr)
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
alphas_cumprod = self.model.alphas_cumprod
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
self.register_buffer('betas', to_torch(self.model.betas))
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
# calculations for diffusion q(x_t | x_{t-1}) and others
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
# ddim sampling parameters
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
ddim_timesteps=self.ddim_timesteps,
eta=ddim_eta,verbose=verbose)
self.register_buffer('ddim_sigmas', ddim_sigmas)
self.register_buffer('ddim_alphas', ddim_alphas)
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
@torch.no_grad()
def sample(self,
S,
batch_size,
shape,
conditioning=None,
callback=None,
normals_sequence=None,
img_callback=None,
quantize_x0=False,
eta=0.,
mask=None,
x0=None,
temperature=1.,
noise_dropout=0.,
score_corrector=None,
corrector_kwargs=None,
verbose=True,
x_T=None,
log_every_t=100,
**kwargs
):
if conditioning is not None:
if isinstance(conditioning, dict):
cbs = conditioning[list(conditioning.keys())[0]].shape[0]
if cbs != batch_size:
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
else:
if conditioning.shape[0] != batch_size:
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
# sampling
C, H, W = shape
size = (batch_size, C, H, W)
# print(f'Data shape for DDIM sampling is {size}, eta {eta}')
samples, intermediates = self.ddim_sampling(conditioning, size,
callback=callback,
img_callback=img_callback,
quantize_denoised=quantize_x0,
mask=mask, x0=x0,
ddim_use_original_steps=False,
noise_dropout=noise_dropout,
temperature=temperature,
score_corrector=score_corrector,
corrector_kwargs=corrector_kwargs,
x_T=x_T,
log_every_t=log_every_t
)
return samples, intermediates
@torch.no_grad()
def ddim_sampling(self, cond, shape,
x_T=None, ddim_use_original_steps=False,
callback=None, timesteps=None, quantize_denoised=False,
mask=None, x0=None, img_callback=None, log_every_t=100,
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
device = self.model.betas.device
b = shape[0]
if x_T is None:
img = torch.randn(shape, device=device)
else:
img = x_T
if timesteps is None:
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
elif timesteps is not None and not ddim_use_original_steps:
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
timesteps = self.ddim_timesteps[:subset_end]
intermediates = {'x_inter': [img], 'pred_x0': [img]}
time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
print(f"Running DDIM Sharpening with {total_steps} timesteps")
iterator = tqdm(time_range, desc='DDIM Sharpening', total=total_steps)
for i, step in enumerate(iterator):
index = total_steps - i - 1
ts = torch.full((b,), step, device=device, dtype=torch.long)
if mask is not None:
assert x0 is not None
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
img = img_orig * mask + (1. - mask) * img
outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
quantize_denoised=quantize_denoised, temperature=temperature,
noise_dropout=noise_dropout, score_corrector=score_corrector,
corrector_kwargs=corrector_kwargs)
img, pred_x0 = outs
if callback: callback(i)
if img_callback: img_callback(pred_x0, i)
if index % log_every_t == 0 or index == total_steps - 1:
intermediates['x_inter'].append(img)
intermediates['pred_x0'].append(pred_x0)
return img, intermediates
@torch.no_grad()
def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
b, *_, device = *x.shape, x.device
e_t = self.model.apply_model(x, t, c)
if score_corrector is not None:
assert self.model.parameterization == "eps"
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
# select parameters corresponding to the currently considered timestep
a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
# current prediction for x_0
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
if quantize_denoised:
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
# direction pointing to x_t
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
if noise_dropout > 0.:
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
return x_prev, pred_x0
def download_models(mode):
if mode == "superresolution":
# this is the small bsr light model
url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1'
url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1'
path_conf = f'{model_path}/superres/project.yaml'
path_ckpt = f'{model_path}/superres/last.ckpt'
download_url(url_conf, path_conf)
download_url(url_ckpt, path_ckpt)
path_conf = path_conf + '/?dl=1' # fix it
path_ckpt = path_ckpt + '/?dl=1' # fix it
return path_conf, path_ckpt
else:
raise NotImplementedError
def load_model_from_config(config, ckpt):
print(f"Loading model from {ckpt}")
pl_sd = torch.load(ckpt, map_location="cpu")
global_step = pl_sd["global_step"]
sd = pl_sd["state_dict"]
model = instantiate_from_config(config.model)
m, u = model.load_state_dict(sd, strict=False)
model.cuda()
model.eval()
return {"model": model}, global_step
def get_model(mode):
path_conf, path_ckpt = download_models(mode)
config = OmegaConf.load(path_conf)
model, step = load_model_from_config(config, path_ckpt)
return model
def get_custom_cond(mode):
dest = "data/example_conditioning"
if mode == "superresolution":
uploaded_img = files.upload()
filename = next(iter(uploaded_img))
name, filetype = filename.split(".") # todo assumes just one dot in name !
os.rename(f"{filename}", f"{dest}/{mode}/custom_{name}.{filetype}")
elif mode == "text_conditional":
w = widgets.Text(value='A cake with cream!', disabled=True)
display.display(w)
with open(f"{dest}/{mode}/custom_{w.value[:20]}.txt", 'w') as f:
f.write(w.value)
elif mode == "class_conditional":
w = widgets.IntSlider(min=0, max=1000)
display.display(w)
with open(f"{dest}/{mode}/custom.txt", 'w') as f:
f.write(w.value)
else:
raise NotImplementedError(f"cond not implemented for mode{mode}")
def get_cond_options(mode):
path = "data/example_conditioning"
path = os.path.join(path, mode)
onlyfiles = [f for f in sorted(os.listdir(path))]
return path, onlyfiles
def select_cond_path(mode):
path = "data/example_conditioning" # todo
path = os.path.join(path, mode)
onlyfiles = [f for f in sorted(os.listdir(path))]
selected = widgets.RadioButtons(
options=onlyfiles,
description='Select conditioning:',
disabled=False
)
display.display(selected)
selected_path = os.path.join(path, selected.value)
return selected_path
def get_cond(mode, img):
example = dict()
if mode == "superresolution":
up_f = 4
# visualize_cond_img(selected_path)
c = img
c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)
c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True)
c_up = rearrange(c_up, '1 c h w -> 1 h w c')
c = rearrange(c, '1 c h w -> 1 h w c')
c = 2. * c - 1.
c = c.to(torch.device("cuda"))
example["LR_image"] = c
example["image"] = c_up
return example
def visualize_cond_img(path):
display.display(ipyimg(filename=path))
def sr_run(model, img, task, custom_steps, eta, resize_enabled=False, classifier_ckpt=None, global_step=None):
# global stride
example = get_cond(task, img)
save_intermediate_vid = False
n_runs = 1
masked = False
guider = None
ckwargs = None
mode = 'ddim'
ddim_use_x0_pred = False
temperature = 1.
eta = eta
make_progrow = True
custom_shape = None
height, width = example["image"].shape[1:3]
split_input = height >= 128 and width >= 128
if split_input:
ks = 128
stride = 64
vqf = 4 #
model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride),
"vqf": vqf,
"patch_distributed_vq": True,
"tie_braker": False,
"clip_max_weight": 0.5,
"clip_min_weight": 0.01,
"clip_max_tie_weight": 0.5,
"clip_min_tie_weight": 0.01}
else:
if hasattr(model, "split_input_params"):
delattr(model, "split_input_params")
invert_mask = False
x_T = None
for n in range(n_runs):
if custom_shape is not None:
x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)
x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0])
logs = make_convolutional_sample(example, model,
mode=mode, custom_steps=custom_steps,
eta=eta, swap_mode=False , masked=masked,
invert_mask=invert_mask, quantize_x0=False,
custom_schedule=None, decode_interval=10,
resize_enabled=resize_enabled, custom_shape=custom_shape,
temperature=temperature, noise_dropout=0.,
corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid,
make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred
)
return logs
@torch.no_grad()
def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None,
mask=None, x0=None, quantize_x0=False, img_callback=None,
temperature=1., noise_dropout=0., score_corrector=None,
corrector_kwargs=None, x_T=None, log_every_t=None
):
ddim = DDIMSampler(model)
bs = shape[0] # dont know where this comes from but wayne
shape = shape[1:] # cut batch dim
# print(f"Sampling with eta = {eta}; steps: {steps}")
samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback,
normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta,
mask=mask, x0=x0, temperature=temperature, verbose=False,
score_corrector=score_corrector,
corrector_kwargs=corrector_kwargs, x_T=x_T)
return samples, intermediates
@torch.no_grad()
def make_convolutional_sample(batch, model, mode="vanilla", custom_steps=None, eta=1.0, swap_mode=False, masked=False,
invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000,
resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,
corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False):
log = dict()
z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,
return_first_stage_outputs=True,
force_c_encode=not (hasattr(model, 'split_input_params')
and model.cond_stage_key == 'coordinates_bbox'),
return_original_cond=True)
log_every_t = 1 if save_intermediate_vid else None
if custom_shape is not None:
z = torch.randn(custom_shape)
# print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}")
z0 = None
log["input"] = x
log["reconstruction"] = xrec
if ismap(xc):
log["original_conditioning"] = model.to_rgb(xc)
if hasattr(model, 'cond_stage_key'):
log[model.cond_stage_key] = model.to_rgb(xc)
else:
log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x)
if model.cond_stage_model:
log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x)
if model.cond_stage_key =='class_label':
log[model.cond_stage_key] = xc[model.cond_stage_key]
with model.ema_scope("Plotting"):
t0 = time.time()
img_cb = None
sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape,
eta=eta,
quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0,
temperature=temperature, noise_dropout=noise_dropout,
score_corrector=corrector, corrector_kwargs=corrector_kwargs,
x_T=x_T, log_every_t=log_every_t)
t1 = time.time()
if ddim_use_x0_pred:
sample = intermediates['pred_x0'][-1]
x_sample = model.decode_first_stage(sample)
try:
x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)
log["sample_noquant"] = x_sample_noquant
log["sample_diff"] = torch.abs(x_sample_noquant - x_sample)
except:
pass
log["sample"] = x_sample
log["time"] = t1 - t0
return log
sr_diffMode = 'superresolution'
sr_model = get_model('superresolution')
def do_superres(img, filepath):
if args.sharpen_preset == 'Faster':
sr_diffusion_steps = "25"
sr_pre_downsample = '1/2'
if args.sharpen_preset == 'Fast':
sr_diffusion_steps = "100"
sr_pre_downsample = '1/2'
if args.sharpen_preset == 'Slow':
sr_diffusion_steps = "25"
sr_pre_downsample = 'None'
if args.sharpen_preset == 'Very Slow':
sr_diffusion_steps = "100"
sr_pre_downsample = 'None'
sr_post_downsample = 'Original Size'
sr_diffusion_steps = int(sr_diffusion_steps)
sr_eta = 1.0
sr_downsample_method = 'Lanczos'
gc.collect()
torch.cuda.empty_cache()
im_og = img
width_og, height_og = im_og.size
#Downsample Pre
if sr_pre_downsample == '1/2':
downsample_rate = 2
elif sr_pre_downsample == '1/4':
downsample_rate = 4
else:
downsample_rate = 1
width_downsampled_pre = width_og//downsample_rate
height_downsampled_pre = height_og//downsample_rate
if downsample_rate != 1:
# print(f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]')
im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS)
# im_og.save('/content/temp.png')
# filepath = '/content/temp.png'
logs = sr_run(sr_model["model"], im_og, sr_diffMode, sr_diffusion_steps, sr_eta)
sample = logs["sample"]
sample = sample.detach().cpu()
sample = torch.clamp(sample, -1., 1.)
sample = (sample + 1.) / 2. * 255
sample = sample.numpy().astype(np.uint8)
sample = np.transpose(sample, (0, 2, 3, 1))
a = Image.fromarray(sample[0])
#Downsample Post
if sr_post_downsample == '1/2':
downsample_rate = 2
elif sr_post_downsample == '1/4':
downsample_rate = 4
else:
downsample_rate = 1
width, height = a.size
width_downsampled_post = width//downsample_rate
height_downsampled_post = height//downsample_rate
if sr_downsample_method == 'Lanczos':
aliasing = Image.LANCZOS
else:
aliasing = Image.NEAREST
if downsample_rate != 1:
# print(f'Downsampling from [{width}, {height}] to [{width_downsampled_post}, {height_downsampled_post}]')
a = a.resize((width_downsampled_post, height_downsampled_post), aliasing)
elif sr_post_downsample == 'Original Size':
# print(f'Downsampling from [{width}, {height}] to Original Size [{width_og}, {height_og}]')
a = a.resize((width_og, height_og), aliasing)
display.display(a)
a.save(filepath)
return
print(f'Processing finished!')
```
# 2. Diffusion and CLIP model settings
```
#@markdown ####**Models Settings:**
diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"]
use_secondary_model = True #@param {type: 'boolean'}
timestep_respacing = '50' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000']
diffusion_steps = 1000 # param {type: 'number'}
use_checkpoint = True #@param {type: 'boolean'}
ViTB32 = True #@param{type:"boolean"}
ViTB16 = True #@param{type:"boolean"}
ViTL14 = False #@param{type:"boolean"}
RN101 = False #@param{type:"boolean"}
RN50 = True #@param{type:"boolean"}
RN50x4 = False #@param{type:"boolean"}
RN50x16 = False #@param{type:"boolean"}
RN50x64 = False #@param{type:"boolean"}
SLIPB16 = False # param{type:"boolean"}
SLIPL16 = False # param{type:"boolean"}
#@markdown If you're having issues with model downloads, check this to compare SHA's:
check_model_SHA = False #@param{type:"boolean"}
model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'
model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648'
model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'
model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'
model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt'
model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth'
model_256_path = f'{model_path}/256x256_diffusion_uncond.pt'
model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt'
model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth'
# Download the diffusion model
if diffusion_model == '256x256_diffusion_uncond':
if os.path.exists(model_256_path) and check_model_SHA:
print('Checking 256 Diffusion File')
with open(model_256_path,"rb") as f:
bytes = f.read()
hash = hashlib.sha256(bytes).hexdigest();
if hash == model_256_SHA:
print('256 Model SHA matches')
model_256_downloaded = True
else:
print("256 Model SHA doesn't match, redownloading...")
!wget --continue {model_256_link} -P {model_path}
model_256_downloaded = True
elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:
print('256 Model already downloaded, check check_model_SHA if the file is corrupt')
else:
!wget --continue {model_256_link} -P {model_path}
model_256_downloaded = True
elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':
if os.path.exists(model_512_path) and check_model_SHA:
print('Checking 512 Diffusion File')
with open(model_512_path,"rb") as f:
bytes = f.read()
hash = hashlib.sha256(bytes).hexdigest();
if hash == model_512_SHA:
print('512 Model SHA matches')
model_512_downloaded = True
else:
print("512 Model SHA doesn't match, redownloading...")
!wget --continue {model_512_link} -P {model_path}
model_512_downloaded = True
elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True:
print('512 Model already downloaded, check check_model_SHA if the file is corrupt')
else:
!wget --continue {model_512_link} -P {model_path}
model_512_downloaded = True
# Download the secondary diffusion model v2
if use_secondary_model == True:
if os.path.exists(model_secondary_path) and check_model_SHA:
print('Checking Secondary Diffusion File')
with open(model_secondary_path,"rb") as f:
bytes = f.read()
hash = hashlib.sha256(bytes).hexdigest();
if hash == model_secondary_SHA:
print('Secondary Model SHA matches')
model_secondary_downloaded = True
else:
print("Secondary Model SHA doesn't match, redownloading...")
!wget --continue {model_secondary_link} -P {model_path}
model_secondary_downloaded = True
elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True:
print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt')
else:
!wget --continue {model_secondary_link} -P {model_path}
model_secondary_downloaded = True
model_config = model_and_diffusion_defaults()
if diffusion_model == '512x512_diffusion_uncond_finetune_008100':
model_config.update({
'attention_resolutions': '32, 16, 8',
'class_cond': False,
'diffusion_steps': diffusion_steps,
'rescale_timesteps': True,
'timestep_respacing': timestep_respacing,
'image_size': 512,
'learn_sigma': True,
'noise_schedule': 'linear',
'num_channels': 256,
'num_head_channels': 64,
'num_res_blocks': 2,
'resblock_updown': True,
'use_checkpoint': use_checkpoint,
'use_fp16': True,
'use_scale_shift_norm': True,
})
elif diffusion_model == '256x256_diffusion_uncond':
model_config.update({
'attention_resolutions': '32, 16, 8',
'class_cond': False,
'diffusion_steps': diffusion_steps,
'rescale_timesteps': True,
'timestep_respacing': timestep_respacing,
'image_size': 256,
'learn_sigma': True,
'noise_schedule': 'linear',
'num_channels': 256,
'num_head_channels': 64,
'num_res_blocks': 2,
'resblock_updown': True,
'use_checkpoint': use_checkpoint,
'use_fp16': True,
'use_scale_shift_norm': True,
})
secondary_model_ver = 2
model_default = model_config['image_size']
if secondary_model_ver == 2:
secondary_model = SecondaryDiffusionImageNet2()
secondary_model.load_state_dict(torch.load(f'{model_path}/secondary_model_imagenet_2.pth', map_location='cpu'))
secondary_model.eval().requires_grad_(False).to(device)
clip_models = []
if ViTB32 is True: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device))
if ViTB16 is True: clip_models.append(clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device) )
if ViTL14 is True: clip_models.append(clip.load('ViT-L/14', jit=False)[0].eval().requires_grad_(False).to(device) )
if RN50 is True: clip_models.append(clip.load('RN50', jit=False)[0].eval().requires_grad_(False).to(device))
if RN50x4 is True: clip_models.append(clip.load('RN50x4', jit=False)[0].eval().requires_grad_(False).to(device))
if RN50x16 is True: clip_models.append(clip.load('RN50x16', jit=False)[0].eval().requires_grad_(False).to(device))
if RN50x64 is True: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device))
if RN101 is True: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device))
if SLIPB16:
SLIPB16model = SLIP_VITB16(ssl_mlp_dim=4096, ssl_emb_dim=256)
if not os.path.exists(f'{model_path}/slip_base_100ep.pt'):
!wget https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt -P {model_path}
sd = torch.load(f'{model_path}/slip_base_100ep.pt')
real_sd = {}
for k, v in sd['state_dict'].items():
real_sd['.'.join(k.split('.')[1:])] = v
del sd
SLIPB16model.load_state_dict(real_sd)
SLIPB16model.requires_grad_(False).eval().to(device)
clip_models.append(SLIPB16model)
if SLIPL16:
SLIPL16model = SLIP_VITL16(ssl_mlp_dim=4096, ssl_emb_dim=256)
if not os.path.exists(f'{model_path}/slip_large_100ep.pt'):
!wget https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt -P {model_path}
sd = torch.load(f'{model_path}/slip_large_100ep.pt')
real_sd = {}
for k, v in sd['state_dict'].items():
real_sd['.'.join(k.split('.')[1:])] = v
del sd
SLIPL16model.load_state_dict(real_sd)
SLIPL16model.requires_grad_(False).eval().to(device)
clip_models.append(SLIPL16model)
normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])
lpips_model = lpips.LPIPS(net='vgg').to(device)
```
# 3. Settings
```
#@markdown ####**Basic Settings:**
batch_name = 'TimeToDisco60' #@param{type: 'string'}
steps = 250#@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true}
width_height = [1280, 768]#@param{type: 'raw'}
clip_guidance_scale = 5000 #@param{type: 'number'}
tv_scale = 0#@param{type: 'number'}
range_scale = 150#@param{type: 'number'}
sat_scale = 0#@param{type: 'number'}
cutn_batches = 1 #@param{type: 'number'}
skip_augs = False#@param{type: 'boolean'}
#@markdown ---
#@markdown ####**Init Settings:**
init_image = None #@param{type: 'string'}
init_scale = 1000 #@param{type: 'integer'}
skip_steps = 0 #@param{type: 'integer'}
#@markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.*
#Get corrected sizes
side_x = (width_height[0]//64)*64;
side_y = (width_height[1]//64)*64;
if side_x != width_height[0] or side_y != width_height[1]:
print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.')
#Update Model Settings
timestep_respacing = f'ddim{steps}'
diffusion_steps = (1000//steps)*steps if steps < 1000 else steps
model_config.update({
'timestep_respacing': timestep_respacing,
'diffusion_steps': diffusion_steps,
})
#Make folder for batch
batchFolder = f'{outDirPath}/{batch_name}'
createPath(batchFolder)
```
###Animation Settings
```
#@markdown ####**Animation Mode:**
animation_mode = "None" #@param['None', '2D', 'Video Input']
#@markdown *For animation, you probably want to turn `cutn_batches` to 1 to make it quicker.*
#@markdown ---
#@markdown ####**Video Input Settings:**
video_init_path = "/content/training.mp4" #@param {type: 'string'}
extract_nth_frame = 2 #@param {type:"number"}
if animation_mode == "Video Input":
videoFramesFolder = f'/content/videoFrames'
createPath(videoFramesFolder)
print(f"Exporting Video Frames (1 every {extract_nth_frame})...")
try:
!rm {videoFramesFolder}/*.jpg
except:
print('')
vf = f'"select=not(mod(n\,{extract_nth_frame}))"'
!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg
#@markdown ---
#@markdown ####**2D Animation Settings:**
#@markdown `zoom` is a multiplier of dimensions, 1 is no zoom.
key_frames = True #@param {type:"boolean"}
max_frames = 100#@param {type:"number"}
if animation_mode == "Video Input":
max_frames = len(glob(f'{videoFramesFolder}/*.jpg'))
interp_spline = 'Linear' #Do not change, currently will not look good. param ['Linear','Quadratic','Cubic']{type:"string"}
angle = "0:(0)"#@param {type:"string"}
zoom = "0: (1), 10: (1.05)"#@param {type:"string"}
translation_x = "0: (0)"#@param {type:"string"}
translation_y = "0: (0)"#@param {type:"string"}
#@markdown ---
#@markdown ####**Coherency Settings:**
#@markdown `frame_scale` tries to guide the new frame to looking like the old one. A good default is 1500.
frames_scale = 1500 #@param{type: 'integer'}
#@markdown `frame_skip_steps` will blur the previous frame - higher values will flicker less but struggle to add enough new detail to zoom into.
frames_skip_steps = '60%' #@param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'}
def parse_key_frames(string, prompt_parser=None):
"""Given a string representing frame numbers paired with parameter values at that frame,
return a dictionary with the frame numbers as keys and the parameter values as the values.
Parameters
----------
string: string
Frame numbers paired with parameter values at that frame number, in the format
'framenumber1: (parametervalues1), framenumber2: (parametervalues2), ...'
prompt_parser: function or None, optional
If provided, prompt_parser will be applied to each string of parameter values.
Returns
-------
dict
Frame numbers as keys, parameter values at that frame number as values
Raises
------
RuntimeError
If the input string does not match the expected format.
Examples
--------
>>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)")
{10: 'Apple: 1| Orange: 0', 20: 'Apple: 0| Orange: 1| Peach: 1'}
>>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)", prompt_parser=lambda x: x.lower()))
{10: 'apple: 1| orange: 0', 20: 'apple: 0| orange: 1| peach: 1'}
"""
import re
pattern = r'((?P<frame>[0-9]+):[\s]*[\(](?P<param>[\S\s]*?)[\)])'
frames = dict()
for match_object in re.finditer(pattern, string):
frame = int(match_object.groupdict()['frame'])
param = match_object.groupdict()['param']
if prompt_parser:
frames[frame] = prompt_parser(param)
else:
frames[frame] = param
if frames == {} and len(string) != 0:
raise RuntimeError('Key Frame string not correctly formatted')
return frames
def get_inbetweens(key_frames, integer=False):
"""Given a dict with frame numbers as keys and a parameter value as values,
return a pandas Series containing the value of the parameter at every frame from 0 to max_frames.
Any values not provided in the input dict are calculated by linear interpolation between
the values of the previous and next provided frames. If there is no previous provided frame, then
the value is equal to the value of the next provided frame, or if there is no next provided frame,
then the value is equal to the value of the previous provided frame. If no frames are provided,
all frame values are NaN.
Parameters
----------
key_frames: dict
A dict with integer frame numbers as keys and numerical values of a particular parameter as values.
integer: Bool, optional
If True, the values of the output series are converted to integers.
Otherwise, the values are floats.
Returns
-------
pd.Series
A Series with length max_frames representing the parameter values for each frame.
Examples
--------
>>> max_frames = 5
>>> get_inbetweens({1: 5, 3: 6})
0 5.0
1 5.0
2 5.5
3 6.0
4 6.0
dtype: float64
>>> get_inbetweens({1: 5, 3: 6}, integer=True)
0 5
1 5
2 5
3 6
4 6
dtype: int64
"""
key_frame_series = pd.Series([np.nan for a in range(max_frames)])
for i, value in key_frames.items():
key_frame_series[i] = value
key_frame_series = key_frame_series.astype(float)
interp_method = interp_spline
if interp_method == 'Cubic' and len(key_frames.items()) <=3:
interp_method = 'Quadratic'
if interp_method == 'Quadratic' and len(key_frames.items()) <= 2:
interp_method = 'Linear'
key_frame_series[0] = key_frame_series[key_frame_series.first_valid_index()]
key_frame_series[max_frames-1] = key_frame_series[key_frame_series.last_valid_index()]
# key_frame_series = key_frame_series.interpolate(method=intrp_method,order=1, limit_direction='both')
key_frame_series = key_frame_series.interpolate(method=interp_method.lower(),limit_direction='both')
if integer:
return key_frame_series.astype(int)
return key_frame_series
def split_prompts(prompts):
prompt_series = pd.Series([np.nan for a in range(max_frames)])
for i, prompt in prompts.items():
prompt_series[i] = prompt
# prompt_series = prompt_series.astype(str)
prompt_series = prompt_series.ffill().bfill()
return prompt_series
if key_frames:
try:
angle_series = get_inbetweens(parse_key_frames(angle))
except RuntimeError as e:
print(
"WARNING: You have selected to use key frames, but you have not "
"formatted `angle` correctly for key frames.\n"
"Attempting to interpret `angle` as "
f'"0: ({angle})"\n'
"Please read the instructions to find out how to use key frames "
"correctly.\n"
)
angle = f"0: ({angle})"
angle_series = get_inbetweens(parse_key_frames(angle))
try:
zoom_series = get_inbetweens(parse_key_frames(zoom))
except RuntimeError as e:
print(
"WARNING: You have selected to use key frames, but you have not "
"formatted `zoom` correctly for key frames.\n"
"Attempting to interpret `zoom` as "
f'"0: ({zoom})"\n'
"Please read the instructions to find out how to use key frames "
"correctly.\n"
)
zoom = f"0: ({zoom})"
zoom_series = get_inbetweens(parse_key_frames(zoom))
try:
translation_x_series = get_inbetweens(parse_key_frames(translation_x))
except RuntimeError as e:
print(
"WARNING: You have selected to use key frames, but you have not "
"formatted `translation_x` correctly for key frames.\n"
"Attempting to interpret `translation_x` as "
f'"0: ({translation_x})"\n'
"Please read the instructions to find out how to use key frames "
"correctly.\n"
)
translation_x = f"0: ({translation_x})"
translation_x_series = get_inbetweens(parse_key_frames(translation_x))
try:
translation_y_series = get_inbetweens(parse_key_frames(translation_y))
except RuntimeError as e:
print(
"WARNING: You have selected to use key frames, but you have not "
"formatted `translation_y` correctly for key frames.\n"
"Attempting to interpret `translation_y` as "
f'"0: ({translation_y})"\n'
"Please read the instructions to find out how to use key frames "
"correctly.\n"
)
translation_y = f"0: ({translation_y})"
translation_y_series = get_inbetweens(parse_key_frames(translation_y))
else:
angle = float(angle)
zoom = float(zoom)
translation_x = float(translation_x)
translation_y = float(translation_y)
```
### Extra Settings
Partial Saves, Diffusion Sharpening, Advanced Settings, Cutn Scheduling
```
#@markdown ####**Saving:**
intermediate_saves = 150#@param{type: 'raw'}
intermediates_in_subfolder = True #@param{type: 'boolean'}
#@markdown Intermediate steps will save a copy at your specified intervals. You can either format it as a single integer or a list of specific steps
#@markdown A value of `2` will save a copy at 33% and 66%. 0 will save none.
#@markdown A value of `[5, 9, 34, 45]` will save at steps 5, 9, 34, and 45. (Make sure to include the brackets)
if type(intermediate_saves) is not list:
if intermediate_saves:
steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1))
steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1
print(f'Will save every {steps_per_checkpoint} steps')
else:
steps_per_checkpoint = steps+10
else:
steps_per_checkpoint = None
if intermediate_saves and intermediates_in_subfolder is True:
partialFolder = f'{batchFolder}/partials'
createPath(partialFolder)
#@markdown ---
#@markdown ####**SuperRes Sharpening:**
#@markdown *Sharpen each image using latent-diffusion. Does not run in animation mode. `keep_unsharp` will save both versions.*
sharpen_preset = 'Fast' #@param ['Off', 'Faster', 'Fast', 'Slow', 'Very Slow']
keep_unsharp = True #@param{type: 'boolean'}
if sharpen_preset != 'Off' and keep_unsharp is True:
unsharpenFolder = f'{batchFolder}/unsharpened'
createPath(unsharpenFolder)
#@markdown ---
#@markdown ####**Advanced Settings:**
#@markdown *There are a few extra advanced settings available if you double click this cell.*
#@markdown *Perlin init will replace your init, so uncheck if using one.*
perlin_init = False #@param{type: 'boolean'}
perlin_mode = 'mixed' #@param ['mixed', 'color', 'gray']
set_seed = 'random_seed' #@param{type: 'string'}
eta = 0.8#@param{type: 'number'}
clamp_grad = True #@param{type: 'boolean'}
clamp_max = 0.05 #@param{type: 'number'}
### EXTRA ADVANCED SETTINGS:
randomize_class = True
clip_denoised = False
fuzzy_prompt = False
rand_mag = 0.05
#@markdown ---
#@markdown ####**Cutn Scheduling:**
#@markdown Format: `[40]*400+[20]*600` = 40 cuts for the first 400 /1000 steps, then 20 for the last 600/1000
#@markdown cut_overview and cut_innercut are cumulative for total cutn on any given step. Overview cuts see the entire image and are good for early structure, innercuts are your standard cutn.
cut_overview = "[12]*400+[4]*600" #@param {type: 'string'}
cut_innercut ="[4]*400+[12]*600"#@param {type: 'string'}
cut_ic_pow = 1#@param {type: 'number'}
cut_icgray_p = "[0.2]*400+[0]*600"#@param {type: 'string'}
```
###Prompts
`animation_mode: None` will only use the first set. `animation_mode: 2D / Video` will run through them per the set frames and hold on the last one.
```
text_prompts = {
0: ["A scary painting of a man with the head of a lizard, and blood dripping from its fangs.", "red and blue color scheme"],
100: ["This set of prompts start at frame 100","This prompt has weight five:5"],
}
image_prompts = {
# 0:['ImagePromptsWorkButArentVeryGood.png:2',],
}
```
# 4. Diffuse!
```
#@title Do the Run!
#@markdown `n_batches` ignored with animation modes.
display_rate = 50 #@param{type: 'number'}
n_batches = 1 #@param{type: 'number'}
batch_size = 1
def move_files(start_num, end_num, old_folder, new_folder):
for i in range(start_num, end_num):
old_file = old_folder + f'/{batch_name}({batchNum})_{i:04}.png'
new_file = new_folder + f'/{batch_name}({batchNum})_{i:04}.png'
os.rename(old_file, new_file)
#@markdown ---
resume_run = True #@param{type: 'boolean'}
run_to_resume = 'latest' #@param{type: 'string'}
resume_from_frame = 'latest' #@param{type: 'string'}
retain_overwritten_frames = True #@param{type: 'boolean'}
if retain_overwritten_frames is True:
retainFolder = f'{batchFolder}/retained'
createPath(retainFolder)
skip_step_ratio = int(frames_skip_steps.rstrip("%")) / 100
calc_frames_skip_steps = math.floor(steps * skip_step_ratio)
if steps <= calc_frames_skip_steps:
sys.exit("ERROR: You can't skip more steps than your total steps")
if resume_run:
if run_to_resume == 'latest':
try:
batchNum
except:
batchNum = len(glob(f"{batchFolder}/{batch_name}(*)_settings.txt"))-1
else:
batchNum = int(run_to_resume)
if resume_from_frame == 'latest':
start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png"))
else:
start_frame = int(resume_from_frame)+1
if retain_overwritten_frames is True:
existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png"))
frames_to_save = existing_frames - start_frame
print(f'Moving {frames_to_save} frames to the Retained folder')
move_files(start_frame, existing_frames, batchFolder, retainFolder)
else:
start_frame = 0
batchNum = len(glob(batchFolder+"/*.txt"))
while path.isfile(f"{batchFolder}/{batch_name}({batchNum})_settings.txt") is True or path.isfile(f"{batchFolder}/{batch_name}-{batchNum}_settings.txt") is True:
batchNum += 1
print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}')
if set_seed == 'random_seed':
random.seed()
seed = random.randint(0, 2**32)
# print(f'Using seed: {seed}')
else:
seed = int(set_seed)
args = {
'batchNum': batchNum,
'prompts_series':split_prompts(text_prompts) if text_prompts else None,
'image_prompts_series':split_prompts(image_prompts) if image_prompts else None,
'seed': seed,
'display_rate':display_rate,
'n_batches':n_batches if animation_mode == 'None' else 1,
'batch_size':batch_size,
'batch_name': batch_name,
'steps': steps,
'width_height': width_height,
'clip_guidance_scale': clip_guidance_scale,
'tv_scale': tv_scale,
'range_scale': range_scale,
'sat_scale': sat_scale,
'cutn_batches': cutn_batches,
'init_image': init_image,
'init_scale': init_scale,
'skip_steps': skip_steps,
'sharpen_preset': sharpen_preset,
'keep_unsharp': keep_unsharp,
'side_x': side_x,
'side_y': side_y,
'timestep_respacing': timestep_respacing,
'diffusion_steps': diffusion_steps,
'animation_mode': animation_mode,
'video_init_path': video_init_path,
'extract_nth_frame': extract_nth_frame,
'key_frames': key_frames,
'max_frames': max_frames if animation_mode != "None" else 1,
'interp_spline': interp_spline,
'start_frame': start_frame,
'angle': angle,
'zoom': zoom,
'translation_x': translation_x,
'translation_y': translation_y,
'angle_series':angle_series,
'zoom_series':zoom_series,
'translation_x_series':translation_x_series,
'translation_y_series':translation_y_series,
'frames_scale': frames_scale,
'calc_frames_skip_steps': calc_frames_skip_steps,
'skip_step_ratio': skip_step_ratio,
'calc_frames_skip_steps': calc_frames_skip_steps,
'text_prompts': text_prompts,
'image_prompts': image_prompts,
'cut_overview': eval(cut_overview),
'cut_innercut': eval(cut_innercut),
'cut_ic_pow': cut_ic_pow,
'cut_icgray_p': eval(cut_icgray_p),
'intermediate_saves': intermediate_saves,
'intermediates_in_subfolder': intermediates_in_subfolder,
'steps_per_checkpoint': steps_per_checkpoint,
'perlin_init': perlin_init,
'perlin_mode': perlin_mode,
'set_seed': set_seed,
'eta': eta,
'clamp_grad': clamp_grad,
'clamp_max': clamp_max,
'skip_augs': skip_augs,
'randomize_class': randomize_class,
'clip_denoised': clip_denoised,
'fuzzy_prompt': fuzzy_prompt,
'rand_mag': rand_mag,
}
args = SimpleNamespace(**args)
print('Prepping model...')
model, diffusion = create_model_and_diffusion(**model_config)
model.load_state_dict(torch.load(f'{model_path}/{diffusion_model}.pt', map_location='cpu'))
model.requires_grad_(False).eval().to(device)
for name, param in model.named_parameters():
if 'qkv' in name or 'norm' in name or 'proj' in name:
param.requires_grad_()
if model_config['use_fp16']:
model.convert_to_fp16()
gc.collect()
torch.cuda.empty_cache()
try:
do_run()
except KeyboardInterrupt:
pass
finally:
print('Seed used:', seed)
gc.collect()
torch.cuda.empty_cache()
```
| github_jupyter |
```
# default_exp exec.parse_data
```
# uberduck_ml_dev.exec.parse_data
Log a speech dataset to the filelist database
Usage:
```
python -m uberduck_ml_dev.exec.parse_data \
--input ~/multispeaker-root \
--format standard-multispeaker \
--ouput list.txt
```
### Supported formats:
### `standard-multispeaker`
```
root
speaker1
list.txt
wavs
speaker2
list.txt
wavs
```
### `standard-singlespeaker`
```
root
list.txt
wavs
```
### Unsupported formats (yet):
### `vctk`
Format of the VCTK dataset as downloaded from the [University of Edinburgh](https://datashare.ed.ac.uk/handle/10283/3443).
```
root
wav48_silence_trimmed
p228
p228_166_mic1.flac
...
txt
p228
p228_166.txt
...
```
```
# export
import argparse
import os
from pathlib import Path
import sqlite3
from tqdm import tqdm
from uberduck_ml_dev.data.cache import ensure_speaker_table, CACHE_LOCATION
from uberduck_ml_dev.data.parse import (
_cache_filelists,
_write_db_to_csv,
STANDARD_MULTISPEAKER,
STANDARD_SINGLESPEAKER,
)
FORMATS = [
STANDARD_MULTISPEAKER,
STANDARD_SINGLESPEAKER,
]
CACHE_LOCATION.parent.exists()
# export
from typing import List
import sys
def _parse_args(args: List[str]):
parser = argparse.ArgumentParser()
parser.add_argument(
"-i", "--input", help="Path to input dataset file or directory", required=True
)
parser.add_argument(
"-f", "--format", help="Input dataset format", default=STANDARD_MULTISPEAKER
)
parser.add_argument(
"-n", "--name", help="Dataset name", default=STANDARD_MULTISPEAKER
)
parser.add_argument(
"-d", "--database", help="Output database", default=CACHE_LOCATION
)
parser.add_argument("--csv_path", help="Path to save csv", default=None)
return parser.parse_args(args)
try:
from nbdev.imports import IN_NOTEBOOK
except:
IN_NOTEBOOK = False
if __name__ == "__main__" and not IN_NOTEBOOK:
args = _parse_args(sys.argv[1:])
ensure_speaker_table(args.database)
conn = sqlite3.connect(args.database)
_cache_filelists(
folder=args.input, fmt=args.format, conn=conn, dataset_name=args.name
)
if args.csv_path is not None:
_write_db_to_csv(conn, args.csv_path)
# skip
python -m uberduck_ml_dev.exec.parse_data -i /mnt/disks/uberduck-experiments-v0/data/eminem/ \
-f standard-singlespeaker \
-d /home/s_uberduck_ai/.cache/uberduck/uberduck-ml-exp.db \
--csv_path $UBMLEXP/filelist_list \
-n eminem
# skip
from tempfile import NamedTemporaryFile, TemporaryFile
with NamedTemporaryFile("w") as f:
_generate_filelist(
str(Path("/Users/zwf/data/voice/dvc-managed/uberduck-multispeaker/").resolve()),
"standard-multispeaker",
f.name,
)
with TemporaryFile("w") as f:
_convert_to_multispeaker(
f,
str(Path("/Users/zwf/data/voice/dvc-managed/uberduck-multispeaker/").resolve()),
"standard-multispeaker",
)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/mattiapocci/PhilosopherRank/blob/master/scrapingWikiDumps.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Import
```
from google.colab import drive
import os
import json
import re
drive.mount('/content/drive')
```
## Download and extract Wikipedia dump
```
!wget -P "/content/drive/My Drive/Wiki_dump/" "https://dumps.wikimedia.org/enwiki/20200120/enwiki-20200120-pages-articles-multistream.xml.bz2"
!bunzip2 -d -k -s /content/drive/My\ Drive/Wiki_dump/enwiki-20200120-pages-articles-multistream.xml.bz2
!python3 WikiExtractor.py "enwiki-20200120-pages-articles-multistream.xml" --json --processes 2
```
# Parsing
## Parsing utility
```
def create_valid_json(filename):
"""
Create a valid json with the commas and the square brackets
:param string:
:return: None
"""
with open(filename, 'r+') as f:
data = f.read().replace('}', '},')
data = data[:-2]
f.seek(0, 0)
f.write('['.rstrip('\r\n') + '\n' + data)
with open(filename, 'a') as f:
f.write("]")
def find_matches(filename,word,phil_list):
"""
Find matches inside the articles with the given word and add it to the given phil_list
:param string:
:param string:
:param list:
:return: list of the articles containg the word philosopher
"""
#phil_list = []
with open(filename, 'r', encoding='utf-8') as file:
try:
data = json.loads(file.read())
for article in data:
if word in article['text']:
phil_list.append(article)
return phil_list
except:
print("Error with: ", filename)
def write_json(data, name):
"""
Write into a file the data given with the name given
:param lst of json:
:param string:
:return: None
"""
with open('/content/drive/My Drive/Wiki_dump/'+name, 'w') as outfile:
json.dump(data, outfile)
```
## Executing the parsing
If the wikipedia articles are yet parsed with the create_valid_json function, do NOT redo the parsing, otherwise you will mess all the articles!!! To avoid this, comment the indicated line.
```
def parse_data(rootdir="/home/luigi/Downloads/wir/wikiextractor-master/text/"):
"""
Parse all the files presents in the rootdir and its subdirectories
:param string:
:return: None
"""
lst = []
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filename_fullpath = os.path.join(subdir, file)
create_valid_json(filename_fullpath) #THIS LINE TO BE COMMENTED according to what is written above
lst = find_matches(filename_fullpath,"philosopher",lst)
write_json(lst,file+".json")
```
Formatting the data to be uniform with the beautiful soup data.
```
lst = []
with open("/content/drive/My Drive/Wiki_dump/wiki_75.json", 'r', encoding='utf-8') as file:
data = json.loads(file.read())
for article in data:
if "philosopher" in article['text']:
var = prototype = {
"philosopher":"" ,
"article": "",
"pageid": "",
"table_influenced": [],
"table_influences": []
}
var['philosopher'] = article['title']
var['article'] = article['text']
var['pageid'] = article['id']
lst.append(var)
write_json(lst,"uniformat.json")
```
# Compare with the category dump
Construct lists from the entire dump
```
reg_a_phil_dump = []
born_lived_dump = []
with open("/content/drive/My Drive/Wiki_dump/uniformat.json", 'r', encoding='utf-8') as file:
data = json.loads(file.read())
for article in data:
if "born" in article['article'] or "lived" in article['article']:
born_lived_dump.append(article)
if re.match(r".*a.*philosopher",article['article']):
reg_a_phil_dump.append(article)
```
construct lists from the category dump
```
born_lived = []
phil = []
reg_a_phil = []
with open("/content/drive/My Drive/Wiki_dump/mattia_ground_t.json", 'r', encoding='utf-8') as file:
data_cat = json.loads(file.read())
for a in data_cat:
if 'philosopher' in a['article']:
phil.append(a)
if "born" in a['article'] or "lived" in a['article']:
born_lived.append(a)
if re.match(r".*a.*philosopher",a['article']):
reg_a_phil.append(a)
```
Finding the articles presents in both the dumps
```
match = 0
trovato = False
for cat_art in phil:
trovato = False
for dump_art in data:
if not trovato and cat_art['pageid'] == dump_art['pageid']:
match = match + 1
trovato = True
if not trovato:
print(cat_art)
```
Printing the scores
```
print("===============DATA ANALYSIS OF CATEGORY DUMP ============")
print("Length of category dump: ",len(data_cat))
print("Length with 'philosopher' in article: ",len(phil))
print("Length with 'born' or 'lived' in article: ",len(born_lived))
print("Length with regex '.* a.* philosopher' in article: ",len(reg_a_phil))
print("\n")
print("===============DATA ANALYSIS OF ENTIRE DUMP ============")
print("Length of dump: 62000000")
print("Length with 'philosopher' in article: ",len(data))
print("Length with 'born' or 'lived' in article: ",len(born_lived_dump))
print("Length with regex '.* a.* philosopher' in article: ",len(reg_a_phil_dump))
print("\n")
print("Matched ",match," articles between category dump and all wiki")
print("Missing",len(phil)-match," articles from all dump")
```
| github_jupyter |
```
#problem - given an csv/excel format file >> find you from present customers who should be given the loan
#Data load
import pandas as pd
import numpy as np
import matplotlib as plt
%matplotlib inline
df = pd.read_csv('train_loan_predict.csv')
df.head()
#Quick Data Exploration
df.head()
df.columns
df.describe()
df['Property_Area'].value_counts()
df['Property_Area'].hist(bins=10)
df['ApplicantIncome'].hist(bins=10)
df.boxplot(column = 'ApplicantIncome', by = 'Education')
df['LoanAmount'].hist(bins=50)
temp1 = df['Credit_History'].value_counts(ascending=True)
temp2 = df.pivot_table(values='Loan_Status',index=['Credit_History'],aggfunc=lambda x: x.map({'Y':1,'N':0}).mean())
print ('Frequency Table for Credit History:')
print (temp1)
print ('\nProbility of getting loan for each Credit History class:')
print (temp2)
df['Gender'].value_counts()
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,4))
ax1 = fig.add_subplot(121)
ax1.set_xlabel('Credit_History')
ax1.set_ylabel('Count of Applicants')
ax1.set_title("Applicants by Credit_History")
temp1.plot(kind='bar')
ax2 = fig.add_subplot(122)
temp2.plot(kind = 'bar')
ax2.set_xlabel('Credit_History')
ax2.set_ylabel('Probability of getting loan')
ax2.set_title("Probability of getting loan by credit history")
temp3 = pd.crosstab(df['Credit_History'], df['Loan_Status'])
temp3.plot(kind='bar', stacked=True, color=['red','blue'], grid=False)
df.apply(lambda x: sum(x.isnull()),axis=0)
df['Gender'].fillna('Female',inplace=True)
df['LoanAmount'].fillna(df['LoanAmount'].mean(), inplace=True)
df['Self_Employed'].fillna('No',inplace=True)
df.apply(lambda x: sum(x.isnull()),axis=0)
df['LoanAmount_log'] = np.log(df['LoanAmount'])
df['LoanAmount_log'].hist(bins=20)
df['TotalIncome'] = df['ApplicantIncome'] + df['CoapplicantIncome']
df['TotalIncome_log'] = np.log(df['TotalIncome'])
df['LoanAmount_log'].hist(bins=20)
#Missing value correction
df['Married'].value_counts()
df['Married'].fillna('No',inplace=True)
df.apply(lambda x: sum(x.isnull()),axis=0)
df['Dependents'].fillna('3+',inplace=True)
df['Dependents'].value_counts()
df.apply(lambda x: sum(x.isnull()),axis=0)
df['Loan_Amount_Term'].value_counts()
df['Loan_Amount_Term'].fillna(df['Loan_Amount_Term'].mean(), inplace=True)
df.apply(lambda x: sum(x.isnull()),axis=0)
df['Credit_History'].fillna('0.0', inplace=True)
df.describe()
# Building a Predicting model in python
df['Gender'].fillna(df['Gender'].mode()[0], inplace=True)
df['Married'].fillna(df['Married'].mode()[0], inplace=True)
df['Dependents'].fillna(df['Dependents'].mode()[0], inplace=True)
df['Loan_Amount_Term'].fillna(df['Loan_Amount_Term'].mode()[0], inplace=True)
df['Credit_History'].fillna(df['Credit_History'].mode()[0], inplace=True)
df.head()
from sklearn.preprocessing import LabelEncoder
var_mod = ['Gender','Married','Dependents','Education','Self_Employed','Property_Area','Loan_Status']
le = LabelEncoder()
for i in var_mod:
df[i] = le.fit_transform(df[i])
df.dtypes
df.head()
#Import models from scikit learn module:
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold #For K-fold cross validation
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn import metrics
#Generic function for making a classification model and accessing performance:
def classification_model(model, data, predictors, outcome):
#Fit the model:
model.fit(data[predictors],data[outcome])
#Make predictions on training set:
predictions = model.predict(data[predictors])
#Print accuracy
accuracy = metrics.accuracy_score(predictions,data[outcome])
print ("Accuracy : %s" % "{0:.3%}".format(accuracy))
#Perform k-fold cross-validation with 5 folds
kf = KFold(n_splits=5, random_state=None)
error = []
for train, test in kf.split(data[predictors]):
# Filter training data
train_predictors = (data[predictors].iloc[train,:])
# The target we're using to train the algorithm.
train_target = data[outcome].iloc[train]
# Training the algorithm using the predictors and target.
model.fit(train_predictors, train_target)
#Record error from each cross-validation run
error.append(model.score(data[predictors].iloc[test,:], data[outcome].iloc[test]))
print ("Cross-Validation Score : %s" % "{0:.3%}".format(np.mean(error)))
#Fit the model again so that it can be refered outside the function:
model.fit(data[predictors],data[outcome])
outcome_var = 'Loan_Status'
model = LogisticRegression()
predictor_var = ['Credit_History']
classification_model(model, df,predictor_var,outcome_var)
#We can try different combination of variables:
predictor_var = ['Credit_History','Education','Married','Self_Employed','Property_Area']
classification_model(model, df,predictor_var,outcome_var)
#Decision Trees
model = DecisionTreeClassifier()
predictor_var = ['Credit_History','Gender','Married','Education']
classification_model(model, df,predictor_var,outcome_var)
#We can try different combination of variables:
predictor_var = ['Credit_History','Loan_Amount_Term','LoanAmount_log']
classification_model(model, df,predictor_var,outcome_var)
model = RandomForestClassifier(n_estimators=100)
predictor_var = ['Gender', 'Married', 'Dependents', 'Education',
'Self_Employed', 'Loan_Amount_Term', 'Credit_History', 'Property_Area',
'LoanAmount_log','TotalIncome_log']
classification_model(model, df,predictor_var,outcome_var)
#Create a series with feature importances:
featimp = pd.Series(model.feature_importances_, index=predictor_var).sort_values(ascending=False)
print (featimp)
model = RandomForestClassifier(n_estimators=25, min_samples_split=25, max_depth=7, max_features=1)
predictor_var = ['TotalIncome_log','LoanAmount_log','Credit_History','Dependents','Property_Area']
classification_model(model, df,predictor_var,outcome_var)
#Loan Prediction Done
```
| github_jupyter |
## Loading the Data
We will be working with the Babi Data Set from Facebook Research.
Full Details: https://research.fb.com/downloads/babi/
- Jason Weston, Antoine Bordes, Sumit Chopra, Tomas Mikolov, Alexander M. Rush,
"Towards AI-Complete Question Answering: A Set of Prerequisite Toy Tasks",
http://arxiv.org/abs/1502.05698
```
import pickle
import numpy as np
pwd
with open("train_qa.txt", "rb") as fp: # Unpickling
train_data = pickle.load(fp)
with open("test_qa.txt", "rb") as fp: # Unpickling
test_data = pickle.load(fp)
```
----
## Exploring the Format of the Data
```
type(test_data)
type(train_data)
len(test_data)
len(train_data)
train_data[0]
' '.join(train_data[0][0])
' '.join(train_data[0][1])
train_data[8][2]
```
-----
## Setting up Vocabulary of All Words
```
# Create a set that holds the vocab words
vocab = set()
all_data = test_data + train_data
for story, question , answer in all_data:
vocab = vocab.union(set(story))
vocab = vocab.union(set(question))
vocab.add('no')
vocab.add('yes')
vocab
vocab_len = len(vocab) + 1 #we add an extra space to hold a 0 for Keras's pad_sequences
vocab_len
max_story_len = max([len(data[0]) for data in all_data])
max_story_len
max_question_len = max([len(data[1]) for data in all_data])
max_question_len
```
## Vectorizing the Data
```
vocab
# Reserve 0 for pad_sequences
vocab_size = len(vocab) + 1
```
-----------
```
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
# integer encode sequences of words
tokenizer = Tokenizer(filters=[])
tokenizer.fit_on_texts(vocab)
tokenizer.word_index
train_story_text = []
train_question_text = []
train_answers = []
for story,question,answer in train_data:
train_story_text.append(story)
train_question_text.append(question)
train_story_seq = tokenizer.texts_to_sequences(train_story_text)
len(train_story_text)
len(train_story_seq)
# word_index = tokenizer.word_index
```
### Functionalize Vectorization
```
def vectorize_stories(data, word_index=tokenizer.word_index, max_story_len=max_story_len,max_question_len=max_question_len):
'''
INPUT:
data: consisting of Stories,Queries,and Answers
word_index: word index dictionary from tokenizer
max_story_len: the length of the longest story (used for pad_sequences function)
max_question_len: length of the longest question (used for pad_sequences function)
OUTPUT:
Vectorizes the stories,questions, and answers into padded sequences. We first loop for every story, query , and
answer in the data. Then we convert the raw words to an word index value. Then we append each set to their appropriate
output list. Then once we have converted the words to numbers, we pad the sequences so they are all of equal length.
Returns this in the form of a tuple (X,Xq,Y) (padded based on max lengths)
'''
# X = STORIES
X = []
# Xq = QUERY/QUESTION
Xq = []
# Y = CORRECT ANSWER
Y = []
for story, query, answer in data:
# Grab the word index for every word in story
x = [word_index[word.lower()] for word in story]
# Grab the word index for every word in query
xq = [word_index[word.lower()] for word in query]
# Grab the Answers (either Yes/No so we don't need to use list comprehension here)
# Index 0 is reserved so we're going to use + 1
y = np.zeros(len(word_index) + 1)
# Now that y is all zeros and we know its just Yes/No , we can use numpy logic to create this assignment
#
y[word_index[answer]] = 1
# Append each set of story,query, and answer to their respective holding lists
X.append(x)
Xq.append(xq)
Y.append(y)
# Finally, pad the sequences based on their max length so the RNN can be trained on uniformly long sequences.
# RETURN TUPLE FOR UNPACKING
return (pad_sequences(X, maxlen=max_story_len),pad_sequences(Xq, maxlen=max_question_len), np.array(Y))
inputs_train, queries_train, answers_train = vectorize_stories(train_data)
inputs_test, queries_test, answers_test = vectorize_stories(test_data)
inputs_test
queries_test
answers_test
sum(answers_test)
tokenizer.word_index['yes']
tokenizer.word_index['no']
```
## Creating the Model
```
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Input, Activation, Dense, Permute, Dropout,Embedding, LSTM
from tensorflow.keras.layers import add, dot, concatenate
```
### Placeholders for Inputs
Recall we technically have two inputs, stories and questions. So we need to use placeholders. `Input()` is used to instantiate a Keras tensor.
```
input_sequence = Input((max_story_len,))
question = Input((max_question_len,))
input_sequence
question
```
### Building the Networks
To understand why we chose this setup, make sure to read the paper we are using:
* Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, Rob Fergus,
"End-To-End Memory Networks",
http://arxiv.org/abs/1503.08895
## Encoders
### Input Encoder m
```
# Input gets embedded to a sequence of vectors
input_encoder_m = Sequential()
input_encoder_m.add(Embedding(input_dim=vocab_size,output_dim=64))
input_encoder_m.add(Dropout(0.3))
# This encoder will output:
# (samples, story_maxlen, embedding_dim)
```
### Input Encoder c
```
# embed the input into a sequence of vectors of size query_maxlen
input_encoder_c = Sequential()
input_encoder_c.add(Embedding(input_dim=vocab_size,output_dim=max_question_len))
input_encoder_c.add(Dropout(0.3))
# output: (samples, story_maxlen, query_maxlen)
```
### Question Encoder
```
# embed the question into a sequence of vectors
question_encoder = Sequential()
question_encoder.add(Embedding(input_dim=vocab_size,
output_dim=64,
input_length=max_question_len))
question_encoder.add(Dropout(0.3))
# output: (samples, query_maxlen, embedding_dim)
```
### Encode the Sequences
```
# encode input sequence and questions (which are indices)
# to sequences of dense vectors
input_encoded_m = input_encoder_m(input_sequence)
input_encoded_c = input_encoder_c(input_sequence)
question_encoded = question_encoder(question)
```
##### Use dot product to compute the match between first input vector seq and the query
```
# shape: `(samples, story_maxlen, query_maxlen)`
match = dot([input_encoded_m, question_encoded], axes=(2, 2))
match = Activation('softmax')(match)
```
#### Add this match matrix with the second input vector sequence
```
# add the match matrix with the second input vector sequence
response = add([match, input_encoded_c]) # (samples, story_maxlen, query_maxlen)
response = Permute((2, 1))(response) # (samples, query_maxlen, story_maxlen)
```
#### Concatenate
```
# concatenate the match matrix with the question vector sequence
answer = concatenate([response, question_encoded])
answer
# Reduce with RNN (LSTM)
answer = LSTM(32)(answer) # (samples, 32)
# Regularization with Dropout
answer = Dropout(0.5)(answer)
answer = Dense(vocab_size)(answer) # (samples, vocab_size)
# we output a probability distribution over the vocabulary
answer = Activation('softmax')(answer)
# build the final model
model = Model([input_sequence, question], answer)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()
# train
history = model.fit([inputs_train, queries_train], answers_train,batch_size=32,epochs=120,validation_data=([inputs_test, queries_test], answers_test))
```
### Saving the Model
```
filename = 'chatbot_120_epochs.h5'
model.save(filename)
```
## Evaluating the Model
### Plotting Out Training History
```
import matplotlib.pyplot as plt
%matplotlib inline
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
```
### Evaluating on Given Test Set
```
model.load_weights(filename)
pred_results = model.predict(([inputs_test, queries_test]))
test_data[0][0]
story =' '.join(word for word in test_data[0][0])
print(story)
query = ' '.join(word for word in test_data[0][1])
print(query)
print("True Test Answer from Data is:",test_data[0][2])
#Generate prediction from model
val_max = np.argmax(pred_results[0])
for key, val in tokenizer.word_index.items():
if val == val_max:
k = key
print("Predicted answer is: ", k)
print("Probability of certainty was: ", pred_results[0][val_max])
```
## Writing Your Own Stories and Questions
Remember you can only use words from the existing vocab
```
vocab
# Note the whitespace of the periods
my_story = "John left the kitchen . Sandra dropped the football in the garden ."
my_story.split()
my_question = "Is the football in the garden ?"
my_question.split()
mydata = [(my_story.split(),my_question.split(),'yes')]
my_story,my_ques,my_ans = vectorize_stories(mydata)
pred_results = model.predict(([ my_story, my_ques]))
#Generate prediction from model
val_max = np.argmax(pred_results[0])
for key, val in tokenizer.word_index.items():
if val == val_max:
k = key
print("Predicted answer is: ", k)
print("Probability of certainty was: ", pred_results[0][val_max])
```
# Great Job!
| github_jupyter |
# Amazon Fraud Detector - Data Profiler Notebook
### Dataset Guidance
-------
AWS Fraud Detector's Online Fraud Insights(OFI) model supports a flexible schema, enabling you to train an OFI model to your specific data and business need. This notebook was developed to help you profile your data and identify potenital issues before you train an OFI model. The following summarizes the minimimum CSV File requirements:
* The files are in CSV UTF-8 (comma delimited) format (*.csv).
* The file should contain at least 10k rows and the following __four__ required fields:
* Event timestamp
* IP address
* Email address
* Fraud label
* The maximum file size is 10 gigabytes (GB).
* The following dates and datetime formats are supported:
* Dates: YYYY-MM-DD (eg. 2019-03-21)
* Datetime: YYYY-MM-DD HH:mm:ss (eg. 2019-03-21 12:01:32)
* ISO 8601 Datetime: YYYY-MM-DDTHH:mm:ss+/-HH:mm (eg. 2019-03-21T20:58:41+07:00)
* The decimal precision is up to four decimal places.
* Numeric data should not contain commas and currency symbols.
* Columns with values that could contain commas, such as address or custom text should be enclosed in double quotes.
### Getting Started with Data
-------
The following general guidance is provided to get the most out of your AWS Fraud Detector Online Fraud Insights Model.
* Gathering Data - The OFI model requires a minimum of 10k records. We recommend that a minimum of 6 weeks of historic data is collected, though 3 - 6 months of data is preferable. As part of the process the OFI model partitions your data based on the Event Timestamp such that performance metrics are calculated on the out of sample (latest) data, thus the format of the event timestamp is important.
* Data & Label Maturity: As part of the data gathering process we want to insure that records have had sufficient time to “mature”, i.e. that enough time has passed to insure “non-fraud" and “fraud” records have been correctly identified. It often takes 30 - 45 days (or more) to correctly identify fraudulent events, because of this it is important to insure that the latest records are at least 30 days old or older.
* Sampling: The OFI training process will sample and partition historic based on event timestamp. There is no need to manually sample the data and doing so may negatively influence your model’s results.
* Fraud Labels: The OFI model requires that a minimum of 500 observations are identified and labeled as “fraud”. As noted above, fraud label maturity is important. Insure that extracted data has sufficiently matured to insure that fraudulent events have been reliably found.
* Custom Fields: the OFI model requires 4 fields: event timestamp, IP address, email address and fraud label. The more custom fields you provide the better the OFI model can differentiate between fraud and not fraud.
* Nulls and Missing Values: OFI model handles null and missing values, however the percentage of nulls in key fields should be limited. Especially timestamp and fraud label columns should not contain any missing values.
If you would like to know more, please check out the [Fraud Detector's Documentation](https://docs.aws.amazon.com/frauddetector/).
```
from IPython.core.display import display, HTML
from IPython.display import clear_output
display(HTML("<style>.container { width:90% }</style>"))
from IPython.display import IFrame
# ------------------------------------------------------------------
import numpy as np
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
pd.options.display.float_format = '{:.4f}'.format
# -- AWS stuff --
import boto3
```
### Amazon Fraud Detector Profiling
-----
from github download and copy the afd_profile.py python program and template directory to your notebook
<div class="alert alert-info"> <strong> afd_profile.py </strong>
- afd_profile.py - is the python package which will generate your profile report.
- /templates - directory contains the supporting profile templates
</div>
```
# -- get this package from github --
import afd_profile
```
### Intialize your S3 client
-----
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html
```
client = boto3.client('s3')
```
### File & Field Mapping
-----
Simply map your file and field names to the required config values.
<div class="alert alert-info"> <strong> Map the Required fields </strong>
- input_file: this is your CSV file in your s3 bucket
<b> required_features </b> are the minimally required freatures to run Amazon Fraud Detector
- EVENT_TIMESTAMP: map this to your file's Date or Datetime field.
- IP_ADDRESS: map this to your file's IP address field.
- EMAIL_ADDRESS: map this to your file's email address field.
- FRAUD_LABEL: map this to your file's fraud label field.
**note: the profiler will identify the "rare" case and assume that it is fraud**
</div>
```
# -- update your configuration --
config = {
"input_file" : "<training dataset name>.csv",
"required_features" : {
"EVENT_TIMESTAMP" : "EVENT_DATE",
"EVENT_LABEL" : "EVENT_LABEL",
"IP_ADDRESS" : "ip_address",
"EMAIL_ADDRESS" : "user_email"
}
}
```
#### Run Profiler
-----
The profiler will read your file and produce an HTML file as a result which will be displayed inline within this notebook.
Note: you can also open **report.html** in a separate browser tab.
```
# -- generate the report object --
report = afd_profile.profile_report(config)
with open("report.html", "w") as file:
file.write(report)
IFrame(src='report.html', width=1500, height=800)
```
| github_jupyter |
# V0.1.6 - Simulate a Predefined Model
Example created by Wilson Rocha Lacerda Junior
```
pip install sysidentpy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sysidentpy.metrics import root_relative_squared_error
from sysidentpy.utils.generate_data import get_miso_data, get_siso_data
from sysidentpy.polynomial_basis.simulation import SimulatePolynomialNarmax
```
## Generating 1 input 1 output sample data
### The data is generated by simulating the following model:
$y_k = 0.2y_{k-1} + 0.1y_{k-1}x_{k-1} + 0.9x_{k-2} + e_{k}$
If *colored_noise* is set to True:
$e_{k} = 0.8\nu_{k-1} + \nu_{k}$
where $x$ is a uniformly distributed random variable and $\nu$ is a gaussian distributed variable with $\mu=0$ and $\sigma=0.1$
In the next example we will generate a data with 1000 samples with white noise and selecting 90% of the data to train the model.
```
x_train, x_test, y_train, y_test = get_siso_data(n=1000,
colored_noise=False,
sigma=0.001,
train_percentage=90)
```
## Defining the model
We already know that the generated data is a result of the model $𝑦_𝑘=0.2𝑦_{𝑘−1}+0.1𝑦_{𝑘−1}𝑥_{𝑘−1}+0.9𝑥_{𝑘−2}+𝑒_𝑘$ . Thus, we can create a model with those regressors follwing a codification pattern:
- $0$ is the constant term,
- $[1001] = y_{k-1}$
- $[100n] = y_{k-n}$
- $[200n] = x1_{k-n}$
- $[300n] = x2_{k-n}$
- $[1011, 1001] = y_{k-11} \times y_{k-1}$
- $[100n, 100m] = y_{k-n} \times y_{k-m}$
- $[12001, 1003, 1001] = x11_{k-1} \times y_{k-3} \times y_{k-1}$
- and so on
### Importante Note
The order of the arrays matter.
If you use [2001, 1001], it will work, but [1001, 2001] will not (the regressor will be ignored). Always put the highest value first:
- $[2003, 2001]$ **works**
- $[2001, 2003]$ **do not work**
We will handle this limitation in upcoming update.
```
s = SimulatePolynomialNarmax()
# the model must be a numpy array
model = np.array(
[
[1001, 0], # y(k-1)
[2001, 1001], # x1(k-1)y(k-1)
[2002, 0], # x1(k-2)
]
)
# theta must be a numpy array of shape (n, 1) where n is the number of regressors
theta = np.array([[0.2, 0.9, 0.1]]).T
```
## Simulating the model
After defining the model and theta we just need to use the simulate method.
The simulate method returns the predicted values and the results where we can look at regressors,
parameters and ERR values.
```
yhat, results = s.simulate(
X_test=x_test,
y_test=y_test,
model_code=model,
theta=theta,
plot=True)
results = pd.DataFrame(results, columns=['Regressors', 'Parameters', 'ERR'])
results
```
### Options
You can set the `steps_ahead` to run the prediction/simulation:
```
yhat, results = s.simulate(
X_test=x_test,
y_test=y_test,
model_code=model,
theta=theta,
plot=False,
steps_ahead=1)
rrse = root_relative_squared_error(y_test, yhat)
rrse
yhat, results = s.simulate(
X_test=x_test,
y_test=y_test,
model_code=model,
theta=theta,
plot=False,
steps_ahead=21)
rrse = root_relative_squared_error(y_test, yhat)
rrse
```
### Estimating the parameters
If you have only the model strucuture, you can create an object with `estimate_parameter=True` and
choose the methed for estimation using `estimator`. In this case, you have to pass the training data
for parameters estimation.
When `estimate_parameter=True`, we also computate the ERR considering only the regressors defined by the user.
```
s2 = SimulatePolynomialNarmax(estimate_parameter=True, estimator='recursive_least_squares')
yhat, results = s2.simulate(
X_train=x_train,
y_train=y_train,
X_test=x_test,
y_test=y_test,
model_code=model,
# theta will be estimated using the defined estimator
plot=True)
results = pd.DataFrame(results, columns=['Regressors', 'Parameters', 'ERR'])
results
yhat, results = s2.simulate(
X_train=x_train,
y_train=y_train,
X_test=x_test,
y_test=y_test,
model_code=model,
# theta will be estimated using the defined estimator
plot=True,
steps_ahead=8)
results = pd.DataFrame(results, columns=['Regressors', 'Parameters', 'ERR'])
results
yhat, results = s2.simulate(
X_train=x_train,
y_train=y_train,
X_test=x_test,
y_test=y_test,
model_code=model,
# theta will be estimated using the defined estimator
plot=True,
steps_ahead=8)
```
| github_jupyter |
#1. Install Dependencies
First install the libraries needed to execute recipes, this only needs to be done once, then click play.
```
!pip install git+https://github.com/google/starthinker
```
#2. Get Cloud Project ID
To run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/master/tutorials/cloud_project.md), this only needs to be done once, then click play.
```
CLOUD_PROJECT = 'PASTE PROJECT ID HERE'
print("Cloud Project Set To: %s" % CLOUD_PROJECT)
```
#3. Get Client Credentials
To read and write to various endpoints requires [downloading client credentials](https://github.com/google/starthinker/blob/master/tutorials/cloud_client_installed.md), this only needs to be done once, then click play.
```
CLIENT_CREDENTIALS = 'PASTE CREDENTIALS HERE'
print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS)
```
#4. Enter DV360 SDF To BigQuery Parameters
Download SDF reports into a BigQuery table.
1. Select your filter types and the filter ideas.
1. Enter the <a href='https://developers.google.com/bid-manager/v1.1/sdf/download' target='_blank'>file types</a> using commas.
1. SDF_ will be prefixed to all tables and date appended to daily tables.
1. File types take the following format: FILE_TYPE_CAMPAIGN, FILE_TYPE_AD_GROUP,...
Modify the values below for your use case, can be done multiple times, then click play.
```
FIELDS = {
'auth_write': 'service', # Credentials used for writing data.
'partner_id': '', # The sdf file types.
'file_types': [], # The sdf file types.
'filter_type': '', # The filter type for the filter ids.
'filter_ids': [], # Comma separated list of filter ids for the request.
'dataset': '', # Dataset to be written to in BigQuery.
'version': '5', # The sdf version to be returned.
'table_suffix': '', # Optional: Suffix string to put at the end of the table name (Must contain alphanumeric or underscores)
'time_partitioned_table': False, # Is the end table a time partitioned
'create_single_day_table': False, # Would you like a separate table for each day? This will result in an extra table each day and the end table with the most up to date SDF.
}
print("Parameters Set To: %s" % FIELDS)
```
#5. Execute DV360 SDF To BigQuery
This does NOT need to be modified unless you are changing the recipe, click play.
```
from starthinker.util.configuration import Configuration
from starthinker.util.configuration import commandline_parser
from starthinker.util.configuration import execute
from starthinker.util.recipe import json_set_fields
USER_CREDENTIALS = '/content/user.json'
TASKS = [
{
'dataset': {
'auth': 'user',
'dataset': {'field': {'name': 'dataset','kind': 'string','order': 6,'default': '','description': 'Dataset to be written to in BigQuery.'}}
}
},
{
'sdf': {
'auth': 'user',
'version': {'field': {'name': 'version','kind': 'choice','order': 6,'default': '5','description': 'The sdf version to be returned.','choices': ['SDF_VERSION_5','SDF_VERSION_5_1']}},
'partner_id': {'field': {'name': 'partner_id','kind': 'integer','order': 1,'description': 'The sdf file types.'}},
'file_types': {'field': {'name': 'file_types','kind': 'string_list','order': 2,'default': [],'description': 'The sdf file types.'}},
'filter_type': {'field': {'name': 'filter_type','kind': 'choice','order': 3,'default': '','description': 'The filter type for the filter ids.','choices': ['FILTER_TYPE_ADVERTISER_ID','FILTER_TYPE_CAMPAIGN_ID','FILTER_TYPE_INSERTION_ORDER_ID','FILTER_TYPE_MEDIA_PRODUCT_ID','FILTER_TYPE_LINE_ITEM_ID']}},
'read': {
'filter_ids': {
'single_cell': True,
'values': {'field': {'name': 'filter_ids','kind': 'integer_list','order': 4,'default': [],'description': 'Comma separated list of filter ids for the request.'}}
}
},
'time_partitioned_table': {'field': {'name': 'time_partitioned_table','kind': 'boolean','order': 7,'default': False,'description': 'Is the end table a time partitioned'}},
'create_single_day_table': {'field': {'name': 'create_single_day_table','kind': 'boolean','order': 8,'default': False,'description': 'Would you like a separate table for each day? This will result in an extra table each day and the end table with the most up to date SDF.'}},
'dataset': {'field': {'name': 'dataset','kind': 'string','order': 6,'default': '','description': 'Dataset to be written to in BigQuery.'}},
'table_suffix': {'field': {'name': 'table_suffix','kind': 'string','order': 6,'default': '','description': 'Optional: Suffix string to put at the end of the table name (Must contain alphanumeric or underscores)'}}
}
}
]
json_set_fields(TASKS, FIELDS)
execute(Configuration(project=CLOUD_PROJECT, client=CLIENT_CREDENTIALS, user=USER_CREDENTIALS, verbose=True), TASKS, force=True)
```
| github_jupyter |
```
import nltk
nltk.download('averaged_perceptron_tagger')
import pickle as pk
import pandas as pd
from gensim.models import KeyedVectors
EMBEDDING_FILE = 'GoogleNews-vectors-negative300.bin'
google_word2vec = KeyedVectors.load_word2vec_format(EMBEDDING_FILE, binary=True)
categories={'food':['ration', 'shop', 'community', 'kitchen'], 'jobs':['training', 'professional', 'job'],
'money':['invest','save','bank','donation'],
'utilities':['internet', 'phone', 'electricity', 'water', 'landlord', 'hotel', 'shelter', 'lpg', 'waste'],
'medical':['hospitals', 'facilities', 'specialists', 'blood'],
'education':['school', 'college', 'tuitions', 'career', 'consultations'],
'medical':['hospitals', 'facilities', 'specialists', 'blood'], 'security':['police', 'theft', 'army', 'guard'],
'infrastructure':['road', 'bridge', 'sewage', 'traffic'],
'buy':['shopkeeper', 'land', 'apartment', 'furniture', 'electronics', 'rental'],
'sell':['shopkeeper', 'land', 'apartment', 'furniture', 'electronics', 'rental'],
'government':['schemes', 'corruption'], 'politics':['politics'],
'emergency':['covid', 'blood', 'robbery', 'crime'],
'travel':['transport', 'cab', 'public', 'auto', 'hotel', 'traffic', 'tourism', 'tolls'],
'services':['business', 'legal', 'accountant', 'carpenter', 'mechanic', 'electrician', 'plumber', 'house', 'help', 'labour'],
'other':['parking', 'women', 'human', 'rights', 'consumer', 'sanitation'], 'technology':['technology'], 'environment':['environment', 'animals']}
sent= pk.load(open('translated.pk', 'rb'))
#sent would be a list in which each element is another list that comprises of the following 3 things:
##1) an ID
##2) original text
##3) translated text (in the form of another list)
######Example shown below########
###[1601345851000,'मुख्यमंत्री गहलोत बोले-प्रदेश में जब भी कोई नया जिला बनेगा तो सबसे पहले ब्यावर का होगा नाम',
### ['Chief Minister Gehlot said - whenever a new district is formed in the state, Beawar will be named first.']]
text= []
for i in range(len(sent)):
text.append(sent[i][2]) #to select just the translated text
#text
```
## Data Preprocessing
```
from nltk.tokenize import sent_tokenize
import re
from nltk.corpus import stopwords
nltk.download('stopwords')
def get_unigram(text):
'''
preprocessing: tokenization; stemming
'''
tt=[]
for j in text:
j=re.sub(r"\W", " ",j, flags=re.I).strip()
for i in j.split():
# i=ps.stem(i.lower())
i=i.lower()
if i.isdigit() or len(i)<=2:
continue
if i in stopwords.words('english'):
continue
else:
tt.append(i)
return list(set(tt))
text2= []
for txt in text:
sentence= ' '.join([str(elem) for elem in txt])
tagged_sentence = nltk.tag.pos_tag(sentence.split())
edited_sentence = [word for word,tag in tagged_sentence if tag != 'NNP' and tag != 'NNPS']
sent_final= ' '.join(edited_sentence)
text2.append([sent_final])
#print(' '.join(edited_sentence))
#text2
```
## Sentence Tokenization
```
tokens= []
for txt in text2:
tokens.append(get_unigram(txt))
#tokens
```
## Determining Cosine Similarity using Word Vectors
```
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
```
## POC for first token
```
tk={}
for i in tokens[0]:
vec1=google_word2vec[i]
cat = {}
for j in categories.keys():
vec2=google_word2vec[j]
sim = cosine_similarity(vec1.reshape(1, -1),vec2.reshape(1, -1))
if sim>0.1:
cat[j]=sim[0][0]
categ=sorted(cat.items(),key=lambda x:x[1])[::-1]
if categ!=[]:
for k in categories[categ[0][0]]:
print(k)
tk[i]=categ[0][0]
#tk
cat= list(categories.keys())
#cat[0]
#tk
col= []
for cat in tk.values():
vec1=google_word2vec[cat]
for token in tk.keys():
vec2=google_word2vec[token]
row= {}
for subcat in categories.get(cat):
row[subcat]= cosine_similarity(vec1.reshape(1, -1),vec2.reshape(1, -1)).tolist()
col.append(row)
col
li_0= []
li= []
for dic in col:
li_0.append(list(dic.values()))
li.append(li_0[0][0][0])
```
| github_jupyter |
Deep Learning
=============
Assignment 5
------------
The goal of this assignment is to train a Word2Vec skip-gram model over [Text8](http://mattmahoney.net/dc/textdata) data.
```
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
%matplotlib inline
from __future__ import print_function
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import zipfile
from matplotlib import pylab
from six.moves import range
from six.moves.urllib.request import urlretrieve
from sklearn.manifold import TSNE
```
Download the data from the source website if necessary.
```
url = 'http://mattmahoney.net/dc/'
def maybe_download(filename, expected_bytes):
"""Download a file if not present, and make sure it's the right size."""
if not os.path.exists(filename):
filename, _ = urlretrieve(url + filename, filename)
statinfo = os.stat(filename)
if statinfo.st_size == expected_bytes:
print('Found and verified %s' % filename)
else:
print(statinfo.st_size)
raise Exception(
'Failed to verify ' + filename + '. Can you get to it with a browser?')
return filename
filename = maybe_download('text8.zip', 31344016)
```
Read the data into a string.
```
def read_data(filename):
"""Extract the first file enclosed in a zip file as a list of words"""
with zipfile.ZipFile(filename) as f:
data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data
words = read_data(filename)
print('Data size %d' % len(words))
```
Build the dictionary and replace rare words with UNK token.
```
vocabulary_size = 50000
def build_dataset(words):
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
if word in dictionary:
index = dictionary[word]
else:
index = 0 # dictionary['UNK']
unk_count = unk_count + 1
data.append(index)
count[0][1] = unk_count
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reverse_dictionary
data, count, dictionary, reverse_dictionary = build_dataset(words)
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10])
del words # Hint to reduce memory.
```
Function to generate a training batch for the skip-gram model.
```
data_index = 0
def generate_batch(batch_size, num_skips, skip_window):
global data_index
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
batch = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span)
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
for i in range(batch_size // num_skips):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [ skip_window ]
for j in range(num_skips):
while target in targets_to_avoid:
target = random.randint(0, span - 1)
targets_to_avoid.append(target)
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
return batch, labels
print('data:', [reverse_dictionary[di] for di in data[:8]])
for num_skips, skip_window in [(2, 1), (4, 2)]:
data_index = 0
batch, labels = generate_batch(batch_size=8, num_skips=num_skips, skip_window=skip_window)
print('\nwith num_skips = %d and skip_window = %d:' % (num_skips, skip_window))
print(' batch:', [reverse_dictionary[bi] for bi in batch])
print(' labels:', [reverse_dictionary[li] for li in labels.reshape(8)])
```
Train a skip-gram model.
```
batch_size = 128
embedding_size = 128 # Dimension of the embedding vector.
skip_window = 1 # How many words to consider left and right.
num_skips = 2 # How many times to reuse an input to generate a label.
# We pick a random validation set to sample nearest neighbors. here we limit the
# validation samples to the words that have a low numeric ID, which by
# construction are also the most frequent.
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100 # Only pick dev samples in the head of the distribution.
valid_examples = np.array(random.sample(range(valid_window), valid_size))
num_sampled = 64 # Number of negative examples to sample.
graph = tf.Graph()
with graph.as_default(), tf.device('/cpu:0'):
# Input data.
train_dataset = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
# Variables.
embeddings = tf.Variable(
tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
softmax_weights = tf.Variable(
tf.truncated_normal([vocabulary_size, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
softmax_biases = tf.Variable(tf.zeros([vocabulary_size]))
# Model.
# Look up embeddings for inputs.
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
# Compute the softmax loss, using a sample of the negative labels each time.
loss = tf.reduce_mean(
tf.nn.sampled_softmax_loss(softmax_weights, softmax_biases, embed,
train_labels, num_sampled, vocabulary_size))
# Optimizer.
# Note: The optimizer will optimize the softmax_weights AND the embeddings.
# This is because the embeddings are defined as a variable quantity and the
# optimizer's `minimize` method will by default modify all variable quantities
# that contribute to the tensor it is passed.
# See docs on `tf.train.Optimizer.minimize()` for more details.
optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss)
# Compute the similarity between minibatch examples and all embeddings.
# We use the cosine distance:
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
valid_embeddings = tf.nn.embedding_lookup(
normalized_embeddings, valid_dataset)
similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings))
num_steps = 100001
with tf.Session(graph=graph) as session:
tf.initialize_all_variables().run()
print('Initialized')
average_loss = 0
for step in range(num_steps):
batch_data, batch_labels = generate_batch(
batch_size, num_skips, skip_window)
feed_dict = {train_dataset : batch_data, train_labels : batch_labels}
_, l = session.run([optimizer, loss], feed_dict=feed_dict)
average_loss += l
if step % 2000 == 0:
if step > 0:
average_loss = average_loss / 2000
# The average loss is an estimate of the loss over the last 2000 batches.
print('Average loss at step %d: %f' % (step, average_loss))
average_loss = 0
# note that this is expensive (~20% slowdown if computed every 500 steps)
if step % 10000 == 0:
sim = similarity.eval()
for i in range(valid_size):
valid_word = reverse_dictionary[valid_examples[i]]
top_k = 8 # number of nearest neighbors
nearest = (-sim[i, :]).argsort()[1:top_k+1]
log = 'Nearest to %s:' % valid_word
for k in range(top_k):
close_word = reverse_dictionary[nearest[k]]
log = '%s %s,' % (log, close_word)
print(log)
final_embeddings = normalized_embeddings.eval()
num_points = 400
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
two_d_embeddings = tsne.fit_transform(final_embeddings[1:num_points+1, :])
def plot(embeddings, labels):
assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
pylab.figure(figsize=(15,15)) # in inches
for i, label in enumerate(labels):
x, y = embeddings[i,:]
pylab.scatter(x, y)
pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
ha='right', va='bottom')
pylab.show()
words = [reverse_dictionary[i] for i in range(1, num_points+1)]
plot(two_d_embeddings, words)
```
---
Problem
-------
An alternative to skip-gram is another Word2Vec model called [CBOW](http://arxiv.org/abs/1301.3781) (Continuous Bag of Words). In the CBOW model, instead of predicting a context word from a word vector, you predict a word from the sum of all the word vectors in its context. Implement and evaluate a CBOW model trained on the text8 dataset.
---
| github_jupyter |
# Lab 04 - Polynomial Fitting
In the previous lab we discussed linear regression and the OLS estimator for solving the minimization of the RSS. As we
mentioned, regression problems are a very wide family of settings and algorithms which we use to try to estimate the relation between a set of explanatory variables and a **continuous** response (i.e. $\mathcal{Y}\in\mathbb{R^p}$). In the following lab we will discuss one such setting called "Polynomial Fitting".
Sometimes, the data (and the relation between the explanatory variables and response) can be described by some polynomial
of some degree. Here, we only focus on the case where it is a polynomial of a single variable. That is:
$$ p_k\left(x\right)=\sum_{i=0}^{k}\alpha_i x_i^k\quad\alpha_1,\ldots,\alpha_k\in\mathbb{R} $$
So our hypothesis class is of the form:
$$ \mathcal{H}^k_{poly}=\left\{p_k|p_k\left(x\right)=\sum_{i=0}^{k}\alpha_i x_i^k\quad\alpha_1,\ldots,\alpha_k\in\mathbb{R}\right\} $$
Notice that similar to linear regression, each hypothesis in the class is defined by a coefficients vector. Below are two
examples (simulated and real) for datasets where the relation between the explanatory variable and response is polynomial.
```
import sys
sys.path.append("../")
from utils import *
response = lambda x: x**4 - 2*x**3 - .5*x**2 + 1
x = np.linspace(-1.2, 2, 20)
y_ = response(x)
df = pd.read_csv("../data/Position_Salaries.csv", skiprows=2, index_col=0)
x2, y2 = df.index, df.Salary
make_subplots(1, 2, subplot_titles=(r"$\text{Simulated Data: }y=x^4-2x^3-0.5x^2+1$", r"$\text{Positions Salary}$"))\
.add_traces([go.Scatter(x=x, y=y_, mode="markers", marker=dict(color="black", opacity=.7), showlegend=False),
go.Scatter(x=x2, y=y2, mode="markers",marker=dict(color="black", opacity=.7), showlegend=False)],
rows=[1,1], cols=[1,2])\
.update_layout(title=r"$\text{(1) Datasets For Polynomial Fitting}$", margin=dict(t=100)).show()
```
As we have discussed in class, solving a polynomial fitting problem can be done by first manipulating the input data,
such that we represent each sample $x_i\in\mathbb{R}$ as a vector $\mathbf{x}_i=\left(x^0,x^1,\ldots,x^k\right)$. Then,
we treat the data as a design matrix $\mathbf{X}\in\mathbb{R}^{m\times k}$ of a linear regression problem.
For the simulated dataset above, which is of a polynomial of degree 4, the design matrix looks as follows:
```
from sklearn.preprocessing import PolynomialFeatures
m, k, X = 5, 4, x.reshape(-1, 1)
pd.DataFrame(PolynomialFeatures(k).fit_transform(X[:m]),
columns=[rf"$x^{{0}}$".format(i) for i in range(0, k+1)],
index=[rf"$x_{{0}}$".format(i) for i in range(1, m+1)])
```
## Fitting A Polynomial Of Different Degrees
Next, let us fit polynomials of different degrees and different noise properties to study how it influences the learned model.
We begin with the noise-less case where we fit for different values of $k$. As we increase $k$ we manage to fit a model
that describes the data in a better way, reflected by the decrease in the MSE.
```
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
ks = [2, 3, 4, 5]
fig = make_subplots(1, 4, subplot_titles=list(ks))
for i, k in enumerate(ks):
y_hat = make_pipeline(PolynomialFeatures(k), LinearRegression()).fit(X, y_).predict(X)
fig.add_traces([go.Scatter(x=x, y=y_, mode="markers", name="Real Points", marker=dict(color="black", opacity=.7), showlegend=False),
go.Scatter(x=x, y=y_hat, mode="markers", name="Predicted Points", marker=dict(color="blue", opacity=.7), showlegend=False)], rows=1, cols=i+1)
fig["layout"]["annotations"][i]["text"] = rf"$k={{0}}, MSE={{1}}$".format(k, round(np.mean((y_-y_hat)**2), 2))
fig.update_layout(title=r"$\text{(2) Simulated Data - Fitting Polynomials of Different Degrees}$",
margin=dict(t=60),
yaxis_title=r"$\widehat{y}$",
height=300).show()
```
Once we find the right $k$ (which in our case is 4) we managed to fit a perfect model, after which, as we increase $k$,
the additional coefficients will be zero.
```
coefs = {}
for k in ks:
fit = make_pipeline(PolynomialFeatures(k), LinearRegression()).fit(X, y_)
coefs[rf"$k={{{k}}}$"] = [round(c,3) for c in fit.steps[1][1].coef_]
pd.DataFrame.from_dict(coefs, orient='index', columns=[rf"$w_{{{i}}}$" for i in range(max(ks)+1)])
```
## Fitting Polynomial Of Different Degrees - With Sample Noise
Still fitting for different values of $k$, let us add some standard Gaussian noise (i.e. $\mathcal{N}\left(0,1\right)$).
This time we observe two things:
- Even for the correct $k=4$ model we are not able to achieve zero MSE.
- As we increase $4<k\rightarrow 7$ we manage to decrease the error more and more.
```
y = y_ + np.random.normal(size=len(y_))
ks = range(2, 8)
fig = make_subplots(2, 3, subplot_titles=list(ks))
for i, k in enumerate(ks):
r,c = i//3+1, i%3+1
y_hat = make_pipeline(PolynomialFeatures(k), LinearRegression()).fit(X, y).predict(X)
fig.add_traces([go.Scatter(x=x, y=y_, mode="markers", name="Real Points", marker=dict(color="black", opacity=.7), showlegend=False),
go.Scatter(x=x, y=y, mode="markers", name="Observed Points", marker=dict(color="red", opacity=.7), showlegend=False),
go.Scatter(x=x, y=y_hat, mode="markers", name="Predicted Points", marker=dict(color="blue", opacity=.7), showlegend=False)], rows=r, cols=c)
fig["layout"]["annotations"][i]["text"] = rf"$k={{0}}, MSE={{1}}$".format(k, round(np.mean((y-y_hat)**2), 2))
fig.update_layout(title=r"$\text{(4) Simulated Data With Noise - Fitting Polynomials of Different Degrees}$", margin=dict(t=80)).show()
```
How is it that we are able to fit "better" models for $k$s larger than the true one? As we increase $k$ we enable the model
more "degrees of freedom" to try and adapt itself to the observed data. The higher $k$ the more the learner will "go after
the noise" and miss the real signal of the data. In other words, what we have just observed is what is known as **overfitting**.
Later in the course we will learn methods for detection and avoidance of overfitting.
## Fitting Polynomial Over Different Sample Noise Levels
Next, let us set $k=4$ (the true values) and study the outputted models when training over different noise levels. Though
we will only be changing the scale of the noise (i.e. the variance, $\sigma^2$), changing other properties such as its
distribution is interesting too. As we would expect, as we increase the scale of the noise our error increases. We can
observe this also in a visual manner, where the fitted polynomial (in blue) less and less resembles the actual model (in black).
```
scales = range(6)
fig = make_subplots(2, 3, subplot_titles=list(map(str, scales)))
for i, s in enumerate(scales):
r,c = i//3+1, i%3+1
y = y_ + np.random.normal(scale=s, size=len(y_))
y_hat = make_pipeline(PolynomialFeatures(4), LinearRegression()).fit(X, y).predict(X)
fig.add_traces([go.Scatter(x=x, y=y_, mode="markers", name="Real Points", marker=dict(color="black", opacity=.7), showlegend=False),
go.Scatter(x=x, y=y, mode="markers", name="Observed Points", marker=dict(color="red", opacity=.7), showlegend=False),
go.Scatter(x=x, y=y_hat, mode="markers", name="Predicted Points", marker=dict(color="blue", opacity=.7), showlegend=False)], rows=r, cols=c)
fig["layout"]["annotations"][i]["text"] = rf"$\sigma^2={{0}}, MSE={{1}}$".format(s, round(np.mean((y-y_hat)**2), 2))
fig.update_layout(title=r"$\text{(5) Simulated Data - Different Noise Scales}$", margin=dict(t=80)).show()
```
## The Influence Of $k$ And $\sigma^2$ On Error
Lastly, let us check how the error is influenced by both $k$ and $\sigma^2$. For each value of $k$ and $\sigma^2$ we will
add noise drawn from $\mathcal{N}\left(0,\sigma^2\right)$ and then, based on the noisy data, let the learner select an
hypothesis from $\mathcal{H}_{poly}^k$. We repeat the process for each set of $\left(k,\sigma^2\right)$ 10 times and report
the mean MSE value. Results are seen in heatmap below:
```
from sklearn.model_selection import ParameterGrid
df = []
for setting in ParameterGrid(dict(k=range(10), s=np.linspace(0, 5, 10), repetition=range(10))):
y = y_ + np.random.normal(scale=setting["s"], size=len(y_))
y_hat = make_pipeline(PolynomialFeatures(setting["k"]), LinearRegression()).fit(X, y).predict(X)
df.append([setting["k"], setting["s"], np.mean((y-y_hat)**2)])
df = pd.DataFrame.from_records(df, columns=["k", "sigma","mse"]).groupby(["k","sigma"]).mean().reset_index()
go.Figure(go.Heatmap(x=df.k, y=df.sigma, z=df.mse, colorscale="amp"),
layout=go.Layout(title=r"$\text{(6) Average Train } MSE \text{ As Function of } \left(k,\sigma^2\right)$",
xaxis_title=r"$k$ - Fitted Polynomial Degree",
yaxis_title=r"$\sigma^2$ - Noise Levels")).show()
```
# Time To Think...
In the above figure, we observe the following trends:
- As already seen before, for the noise-free data, once we reach the correct $k$ we achieve zero MSE.
- Across all values of $k$, as we increase $\sigma^2$ we get higher MSE values.
- For all noise levels, we manage to reduce MSE values by increasing $k$.
So, by choosing a **richer** hypothesis class (i.e. larger and that can express more functions - polynomials of higher
degree) we are able to choose an hypothesis that fits the **observed** data **better**, regardless to how noisy the data is.
Try and think how the above heatmap would look if instead of calculating the MSE over the training samples (i.e train error)
we would have calculated it over a **new** set of test samples drawn from the same distribution.
Use the below code to create a test set. Change the code generating figure 6 such that the reported error is a test error. Do not forget to add the noise (that depends on $\sigma^2$) to the test data. What has changed between what we observe for the train error to the test error? What happens for high/low values of $\sigma^2$? What happens for high/low values of $k$?
```
testX = np.linspace(-1.2, 2, 40)[1::2].reshape(-1,1)
testY = response(testX)
```
| github_jupyter |
# Segmentation
<div class="alert alert-info">
This tutorial is available as an IPython notebook at [Malaya/example/segmentation](https://github.com/huseinzol05/Malaya/tree/master/example/segmentation).
</div>
<div class="alert alert-info">
This module trained on both standard and local (included social media) language structures, so it is save to use for both.
</div>
```
%%time
import malaya
```
Common problem for social media texts, there are missing spaces in the text, so text segmentation can help you,
1. huseinsukamakan ayam,dia sgtrisaukan -> husein suka makan ayam, dia sgt risaukan.
2. drmahathir sangat menekankan budaya budakzamansekarang -> dr mahathir sangat menekankan budaya budak zaman sekarang.
3. ceritatunnajibrazak -> cerita tun najib razak.
4. TunM sukakan -> Tun M sukakan.
Segmentation only,
1. Solve spacing error.
3. Not correcting any grammar.
```
string1 = 'huseinsukamakan ayam,dia sgtrisaukan'
string2 = 'drmahathir sangat menekankan budaya budakzamansekarang'
string3 = 'ceritatunnajibrazak'
string4 = 'TunM sukakan'
string_hard = 'IPOH-AhliDewanUndangan Negeri(ADUN) HuluKinta, MuhamadArafat Varisai Mahamadmenafikanmesejtularmendakwa beliau akan melompatparti menyokong UMNO membentuk kerajaannegeridiPerak.BeliauyangjugaKetua Penerangan Parti Keadilan Rakyat(PKR)Perak dalam satumesejringkaskepadaSinar Harian menjelaskan perkara itutidakbenarsama sekali.'
string_socialmedia = 'aqxsukalah apeyg tejadidekat mamattu'
```
### Viterbi algorithm
Commonly people use Viterbi algorithm to solve this problem, we also added viterbi using ngram from bahasa papers and wikipedia.
```python
def viterbi(max_split_length: int = 20, **kwargs):
"""
Load Segmenter class using viterbi algorithm.
Parameters
----------
max_split_length: int, (default=20)
max length of words in a sentence to segment
validate: bool, optional (default=True)
if True, malaya will check model availability and download if not available.
Returns
-------
result : malaya.segmentation.SEGMENTER class
"""
```
```
viterbi = malaya.segmentation.viterbi()
```
#### Segmentize
```python
def segment(self, strings: List[str]):
"""
Segment strings.
Example, "sayasygkan negarasaya" -> "saya sygkan negara saya"
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
```
```
%%time
viterbi.segment([string1, string2, string3, string4])
%%time
viterbi.segment([string_hard, string_socialmedia])
```
### List available Transformer model
```
malaya.segmentation.available_transformer()
```
### Load Transformer model
```python
def transformer(model: str = 'small', quantized: bool = False, **kwargs):
"""
Load transformer encoder-decoder model to Segmentize.
Parameters
----------
model : str, optional (default='base')
Model architecture supported. Allowed values:
* ``'small'`` - Transformer SMALL parameters.
* ``'base'`` - Transformer BASE parameters.
quantized : bool, optional (default=False)
if True, will load 8-bit quantized model.
Quantized model not necessary faster, totally depends on the machine.
Returns
-------
result: malaya.model.tf.Segmentation class
"""
```
```
model = malaya.segmentation.transformer(model = 'small')
quantized_model = malaya.segmentation.transformer(model = 'small', quantized = True)
model_base = malaya.segmentation.transformer(model = 'base')
quantized_model_base = malaya.segmentation.transformer(model = 'base', quantized = True)
```
#### Predict using greedy decoder
```python
def greedy_decoder(self, strings: List[str]):
"""
Segment strings using greedy decoder.
Example, "sayasygkan negarasaya" -> "saya sygkan negara saya"
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
```
```
%%time
model.greedy_decoder([string1, string2, string3, string4])
%%time
quantized_model.greedy_decoder([string1, string2, string3, string4])
%%time
model_base.greedy_decoder([string1, string2, string3, string4])
%%time
quantized_model_base.greedy_decoder([string1, string2, string3, string4])
%%time
model.greedy_decoder([string_hard, string_socialmedia])
%%time
quantized_model.greedy_decoder([string_hard, string_socialmedia])
%%time
model_base.greedy_decoder([string_hard, string_socialmedia])
%%time
quantized_model_base.greedy_decoder([string_hard, string_socialmedia])
```
**Problem with batching string, short string might repeating itself, so to solve this, you need to give a single string only**,
```
%%time
quantized_model_base.greedy_decoder([string_socialmedia])
%%time
quantized_model_base.greedy_decoder([string3])
%%time
quantized_model_base.greedy_decoder([string4])
```
#### Predict using beam decoder
```python
def beam_decoder(self, strings: List[str]):
"""
Segment strings using beam decoder, beam width size 3, alpha 0.5 .
Example, "sayasygkan negarasaya" -> "saya sygkan negara saya"
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
```
```
%%time
quantized_model.beam_decoder([string_socialmedia])
%%time
quantized_model_base.beam_decoder([string_socialmedia])
```
**We can expect beam decoder is much more slower than greedy decoder**.
| github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Load-the-Data" data-toc-modified-id="Load-the-Data-1"><span class="toc-item-num">1 </span>Load the Data</a></span><ul class="toc-item"><li><span><a href="#Download-data-(if-needed)" data-toc-modified-id="Download-data-(if-needed)-1.1"><span class="toc-item-num">1.1 </span>Download data (if needed)</a></span></li><li><span><a href="#Read-in-log-file" data-toc-modified-id="Read-in-log-file-1.2"><span class="toc-item-num">1.2 </span>Read in log file</a></span></li></ul></li><li><span><a href="#Data-Augmentation" data-toc-modified-id="Data-Augmentation-2"><span class="toc-item-num">2 </span>Data Augmentation</a></span><ul class="toc-item"><li><span><a href="#Flip-the-image" data-toc-modified-id="Flip-the-image-2.1"><span class="toc-item-num">2.1 </span>Flip the image</a></span></li><li><span><a href="#Adjust-off-center-images" data-toc-modified-id="Adjust-off-center-images-2.2"><span class="toc-item-num">2.2 </span>Adjust off-center images</a></span></li><li><span><a href="#Don't-use-some-small-steering-values" data-toc-modified-id="Don't-use-some-small-steering-values-2.3"><span class="toc-item-num">2.3 </span>Don't use some small steering values</a></span></li><li><span><a href="#Translate-Images" data-toc-modified-id="Translate-Images-2.4"><span class="toc-item-num">2.4 </span>Translate Images</a></span></li></ul></li><li><span><a href="#Creating-own-generator-to-read-data" data-toc-modified-id="Creating-own-generator-to-read-data-3"><span class="toc-item-num">3 </span>Creating own generator to read data</a></span><ul class="toc-item"><li><span><a href="#Read-in-images-by-path-from-log-file" data-toc-modified-id="Read-in-images-by-path-from-log-file-3.1"><span class="toc-item-num">3.1 </span>Read in images by path from log file</a></span></li><li><span><a href="#Split-the-data-into-training-and-validation" data-toc-modified-id="Split-the-data-into-training-and-validation-3.2"><span class="toc-item-num">3.2 </span>Split the data into training and validation</a></span><ul class="toc-item"><li><span><a href="#Generators-for-both-train-and-validation-sets" data-toc-modified-id="Generators-for-both-train-and-validation-sets-3.2.1"><span class="toc-item-num">3.2.1 </span>Generators for both train and validation sets</a></span></li></ul></li></ul></li><li><span><a href="#Model" data-toc-modified-id="Model-4"><span class="toc-item-num">4 </span>Model</a></span><ul class="toc-item"><li><span><a href="#Using-center-images-only" data-toc-modified-id="Using-center-images-only-4.1"><span class="toc-item-num">4.1 </span>Using center images only</a></span><ul class="toc-item"><li><span><a href="#Evaluation" data-toc-modified-id="Evaluation-4.1.1"><span class="toc-item-num">4.1.1 </span>Evaluation</a></span></li></ul></li></ul></li></ul></div>
```
import pandas as pd
import numpy as np
import cv2
import sklearn
import sklearn.model_selection
import tensorflow.keras as keras
%matplotlib inline
```
# Load the Data
We'll load the log data & also load the images (found in the log file).
## Download data (if needed)
```
# Download data & unzip if it doesn't already exist
import os.path
from io import BytesIO
from urllib.request import urlopen
from zipfile import ZipFile
def load_ext_file(data_zip_url, data_path='data/'):
'''Download the zip file from URL and extract it to path (if specified).
'''
# Check if path already exits
if not os.path.exists(data_path):
with urlopen(data_zip_url) as zip_resp:
with ZipFile(BytesIO(zip_resp.read())) as zfile:
# Extract files into the data directory
zfile.extractall(path=None)
# Use particular release for data from a simulation run
load_ext_file('https://github.com/MrGeislinger/clone-driving-behavior/releases/download/v0.14.0/data.zip')
```
## Read in log file
```
def create_img_meas_dfs(log_csv, data_dir=None, orig_dir=None, skiprows=None):
'''Creates DataFrames for the image paths and measurements using CSV path.
Returns tuple of two DataFrames.
'''
data_header = [
'image_center',
'image_left',
'image_right',
'steer_angle', # [-1,1]
'throttle', # boolen (if accelerating)
'break', # boolean (if breaking)
'speed' # mph
]
df = pd.read_csv(
log_csv,
names=data_header,
skiprows=skiprows
)
# Replace the original directory from dataset (if specified)
if orig_dir and data_dir:
for col in ['image_center','image_left','image_right']:
df[col] = df[col].str.replace(orig_dir,data_dir)
# Get specifics for each DF
df_img_paths = df.iloc[:,:3]
df_measurments = df.iloc[:,3:]
return df_img_paths,df_measurments, df
df_imgs, df_meas, df_all = create_img_meas_dfs(
log_csv='data/driving_log.csv',
skiprows=1)
display(df_imgs.head())
print('Stats for measurements:')
display(df_meas.describe())
ax = df_meas.steer_angle.hist(bins=50)
```
# Data Augmentation
We can do some data augmentation to the images to have more variety in the training material.
## Flip the image
We can flip the image and the steering angle to better generalize.
```
def flip_image(image, target):
'''Horizontally flip image and target value.
'''
image_flipped = np.fliplr(image)
target_flipped = -target
return image_flipped, target_flipped
```
## Adjust off-center images
```
def adjust_offcenter_image(image, target, correction: float = 1e-2,
img_camera_type: str = 'center'):
'''
img_camera_type: The type of camera image
target: The target value (to be adjusted)
'''
# TODO: Adjust the target slightly for off-center image
if img_camera_type == 'left':
new_target = target + correction
elif img_camera_type == 'right':
new_target = target - correction
# Don't make any correction if unknown or centere
else:
new_target = target
return image, new_target
```
## Don't use some small steering values
Since the data is biased towards to low steering (driving straight), randomly drop some of the data to discourage simply driving straight.
```
def skip_low_steering(steer_value, steer_threshold=0.05, drop_percent=0.2):
'''
'''
# Keep value if greater than threshold or by chance
return (steer_value < steer_threshold['left']
or steer_value > steer_threshold['right']
or np.random.rand() > drop_percent)
```
## Translate Images
```
def translate_image (image, target, correction=100, scale_factor=0.2):
'''
'''
# Translate the image randomly about correction factor (then scaled)
adjustment = int(correction * np.random.uniform(-1*scale_factor, scale_factor))
# Get a new
target_new = target + (adjustment / correction)
n,m,c=image.shape
bigsquare=np.zeros((n,m+100,c),image.dtype)
if adjustment < 0:
bigsquare[:,:m+adjustment]=image[:,-adjustment:m]
else:
bigsquare[:,adjustment:m+adjustment]=image
return bigsquare[:n,:m,:], target_new
```
# Creating own generator to read data
```
def data_generator(X, y ,batch_size=64, center_only=True, data_dir='data/'):
'''
Generate a batch of training images and targets from a DataFrame.
Inputs:
X: array-like of paths to images
y: array-like of targerts (in order of X)
'''
# Loop forever so the generator never terminates
while True:
# Shuffle the image paths and targets
X_final = []
y_final = []
X_shuffled, y_shuffled = sklearn.utils.shuffle(X, y, n_samples=batch_size)
# We grab the first element since there is 1 column
for img_path,target in zip(X_shuffled,y_shuffled):
fname = data_dir+img_path
img = cv2.imread(fname[0])
# Skip specifically for the center image (still checks left/right)
steer_thresh = {'left':-0.01, 'right':0.005}
drop_ratio = 0.3
if skip_low_steering(target[0], steer_thresh, drop_ratio):
X_final.append(img)
y_final.append(target[0])
# Use horizontally flipped images (new target)
img_flipped, target_flipped = flip_image(img,target)
X_final.append(img_flipped)
y_final.append(target_flipped[0])
# Check if we should use all images or just center
if not center_only:
# Translate the image randomly
img_trans, target_trans = translate_image(img, target[0], scale_factor=0.5)
X_final.append(img_trans)
y_final.append(target_trans)
# Order: center, left, right
# Corret left image target & add image with target to array
img_l = cv2.imread(fname[1])
target_l = adjust_offcenter_image(img, target, 0.25, 'left')
# Corret right image target & add image with target to array
img_r = cv2.imread(fname[2])
target_r = adjust_offcenter_image(img, target, 0.25, 'right')
X_final.append(img_l)
y_final.append(target_l[0])
# Use horizontally flipped images (new target)
img_flipped, target_flipped = flip_image(img_l,target_l)
X_final.append(img_flipped)
y_final.append(target_flipped[0])
X_final.append(img_r)
y_final.append(target_r[0])
# Use horizontally flipped images (new target)
img_flipped, target_flipped = flip_image(img_r,target_r)
X_final.append(img_flipped)
y_final.append(target_flipped[0])
batch_x = np.array(X_final)
batch_y = np.array(y_final)
yield (batch_x, batch_y)
```
## Read in images by path from log file
We'll use the generator created above to read in images by a batch while training (and validating). But to ensure it works, let's test it out below.
```
# Note the multiple images will keep the proper shape
temp_generator = data_generator(
df_all[['image_center','image_left','image_right']].values,
df_all['steer_angle'].values.reshape(-1,1)
)
imgs,targets = next(temp_generator)
# Test to see if image reading works
import matplotlib.pyplot as plt
f = plt.figure(figsize=(25,25))
ax_left = f.add_subplot(1, 3, 1)
ax_center = f.add_subplot(1, 3, 2)
ax_right = f.add_subplot(1, 3, 3)
# Print out three image examples
ax_center.imshow(imgs[0])
ax_left.imshow(imgs[1])
ax_right.imshow(imgs[2])
```
## Split the data into training and validation
```
# Adjust the target for off-center images to be used in training
X = df_all[['image_center','image_left','image_right']].values
y = df_all[['steer_angle']].values
X_train, X_valid, y_train, y_valid = sklearn.model_selection.train_test_split(
X, y, test_size=0.2, random_state=27)
```
### Generators for both train and validation sets
```
# Using reasobable batch size so GPU can process enough images
train_generator = data_generator(X_train, y_train, batch_size=256)
valid_generator = data_generator(X_valid, y_valid, batch_size=256)
```
# Model
## Using center images only
We'll try just using center images for training the model. If we simply put in the left and right images for the camera angle, we'd likely have issues with the model learning incorrect behavior. There are some techniques that could allow us to use these other images but for simplicity's sake we'll only use the center images for now.
```
# Creating a resuable default convolution
from functools import partial
DefaultConv2D = partial(keras.layers.Conv2D, kernel_initializer='he_normal',
kernel_size=3, activation='elu', padding='SAME')
input_shape = (160,320,3)
# Based on https://developer.nvidia.com/blog/deep-learning-self-driving-cars/
model_list = [
# Normalize the images
keras.layers.Lambda(lambda x: (x/255.0) - 0.5, input_shape=input_shape),
DefaultConv2D(filters=24, kernel_size=5),
keras.layers.MaxPooling2D(pool_size=2),
DefaultConv2D(filters=36, kernel_size=5),
keras.layers.MaxPooling2D(pool_size=2),
DefaultConv2D(filters=36, kernel_size=5),
keras.layers.MaxPooling2D(pool_size=2),
keras.layers.Dropout(0.4), # Dropout to regularize
DefaultConv2D(filters=48),
keras.layers.MaxPooling2D(pool_size=2),
DefaultConv2D(filters=64),
keras.layers.MaxPooling2D(pool_size=2),
DefaultConv2D(filters=64),
keras.layers.MaxPooling2D(pool_size=2),
keras.layers.Dropout(0.4), # Dropout to regularize
# Fully connected network
keras.layers.Flatten(),
keras.layers.Dense(units=1024, activation='relu'),
keras.layers.Dropout(0.2), # Dropout to regularize
keras.layers.Dense(units=128, activation='relu'),
keras.layers.Dropout(0.2), # Dropout to regularize
keras.layers.Dense(units=64, activation='relu'),
keras.layers.Dense(units=16, activation='relu'),
keras.layers.Dense(units=1)
]
# Adding in model to crop images first
model_list = (
[model_list[0]] +
# Crop out "unnecessary parts of the image"
[keras.layers.Cropping2D(cropping=((60,20), (0,0)))] +
model_list[1:]
)
model = keras.models.Sequential(model_list)
model.compile(
loss='mse',
optimizer='nadam'
)
model.summary()
# Allow early stopping after not changing
stop_after_no_change = keras.callbacks.EarlyStopping(
monitor='val_loss',
patience=15,
restore_best_weights=True
)
history = model.fit(
x=train_generator,
y=None, # Since using a generator
batch_size=None, # Since using a generator
epochs=256, # Large since we want to ensure we stop by early stopping
steps_per_epoch=128, # Ideal: steps*batch_size = # of images
validation_data=valid_generator,
validation_steps=32,
callbacks=[stop_after_no_change]
)
```
### Evaluation
```
import matplotlib.pyplot as plt
%matplotlib inline
def eval_model(model, model_history, X, y, show=True):
'''
'''
score = model.evaluate(X, y)
print(f'Loss: {score:.2f}')
if show:
plt.plot(model_history.history['loss'], label='Loss (training data)')
plt.plot(model_history.history['val_loss'], label='Loss (validation data)')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(loc='upper right')
plt.show()
```
Let's checkout how the previous model turned while training.
```
test_generator = data_generator(X_valid, y_valid, batch_size=64)
X_test, y_test = next(test_generator)
eval_model(model, history, X_test, y_test)
# Ignore the first epoch since it's typically very high compared to the rest
plt.plot(history.history['loss'], label='Loss (training data)')
plt.plot(history.history['val_loss'], label='Loss (validation data)')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.ylim(
top=np.median(history.history['val_loss'])+np.std(history.history['val_loss']),
bottom=0.0
)
plt.legend(loc='upper right')
plt.show()
model.save('model.h5')
# Clean up the data downloaded (not needed for output)
!rm -rf data/
!rm -rf __MACOSX/
```
| github_jupyter |
# Models trained on Mean and Max DistilBert Embeddings
```
#Imports
import keras
import pandas as pd
import numpy as np
import joblib
import tensorflow as tf
from keras import Model
from sklearn.metrics import precision_recall_fscore_support, classification_report
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
# Graphing
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
df_test = joblib.load('BERT_embeddings/lstm_test.sav')
df_train = joblib.load('BERT_embeddings/lstm_train.sav')
df_val = joblib.load('BERT_embeddings/lstm_val.sav')
```
# Mean Model on outputs
```
input_ids = np.array(df_train['mean_features'].tolist())
labels = np.array(df_train['label'].tolist())
test_input_ids = np.array(df_test['mean_features'].tolist())
test_labels = np.array(df_test['label'].tolist())
val_input_ids = np.array(df_val['mean_features'].tolist())
val_labels = np.array(df_val['label'].tolist())
# Re-train model with best results
inp = tf.keras.layers.Input(shape=(768))
X = tf.keras.layers.Dense(1000, activation='tanh')(inp)
X = tf.keras.layers.Dropout(0.2)(X)
X = tf.keras.layers.Dense(2, activation='softmax')(X)
model = tf.keras.Model(inputs=inp, outputs = X)
opt = keras.optimizers.Adam(learning_rate=2e-5)
model.compile(optimizer=opt,
loss='sparse_categorical_crossentropy',
metrics=['acc'])
model.summary()
epochs = 10
history = model.fit(x = input_ids,
y = labels,
epochs=epochs,
batch_size = 8,
validation_data=(val_input_ids, val_labels))
# evaluate
model.evaluate(test_input_ids, test_labels)
y_log = model.predict(test_input_ids)
y_pred = np.argmax(y_log, axis=1)
# Show classification report
from sklearn.metrics import precision_recall_fscore_support, classification_report
print("Mean Pooling split chunks")
print(classification_report(df_test['label'], y_pred))
```
# MAX Model on fixed outputs
```
input_ids = np.array(df_train['max_features'].tolist())
labels = np.array(df_train['label'].tolist())
test_input_ids = np.array(df_test['max_features'].tolist())
test_labels = np.array(df_test['label'].tolist())
val_input_ids = np.array(df_val['max_features'].tolist())
val_labels = np.array(df_val['label'].tolist())
# Re-train model with best results
inp = tf.keras.layers.Input(shape=(768))
X = tf.keras.layers.Dense(1000, activation='tanh')(inp)
X = tf.keras.layers.Dropout(0.2)(X)
X = tf.keras.layers.Dense(2, activation='softmax')(X)
model = tf.keras.Model(inputs=inp, outputs = X)
opt = keras.optimizers.Adam(learning_rate=2e-5)
model.compile(optimizer=opt,
loss='sparse_categorical_crossentropy',
metrics=['acc'])
model.summary()
epochs = 10
history = model.fit(x = input_ids,
y = labels,
epochs=epochs,
batch_size = 8,
validation_data=(val_input_ids, val_labels))
model.evaluate(test_input_ids, test_labels)
y_log = model.predict(test_input_ids)
y_pred = np.argmax(y_log, axis=1)
# Show classification report
from sklearn.metrics import precision_recall_fscore_support, classification_report
print("Max Pooled split chunks")
print(classification_report(df_test['label'], y_pred))
sns.set(style='darkgrid')
sns.set(font_scale=1.5)
plt.rcParams["figure.figsize"] = (12,6)
plt.plot(history.history['loss'], 'b-o', label="Training")
plt.plot(history.history['val_loss'], 'g-o', label="Validation")
plt.title("Training & Validation Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend()
plt.xticks([1, 2, 3, 4, 5, 6, 7, 8, 9,10])
plt.show()
sns.set(style='darkgrid')
sns.set(font_scale=1.5)
plt.rcParams["figure.figsize"] = (10,6)
plt.plot(history.history['acc'], 'r-o', label="Train Accuracy")
plt.plot(history.history['val_acc'], 'y-o', label="Val Accuracy")
plt.title("Accuracy")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend()
plt.xticks([1, 2, 3, 4, 5, 6, 7, 8, 9,10])
plt.show()
```
| github_jupyter |
```
import geopandas as gpd
import pandas_bokeh
import re
import pandas as pd
pandas_bokeh.output_notebook()
from script.function3dto2d import remove_third_dimension
capacity_list = ['conservative estimate Mt','neutral estimate Mt','optimistic estimate Mt']
move = ['COUNTRY','COUNTRYCOD','ID','geometry']
#load data
storage_unit = gpd.read_file('data/storage_unit_map_lite.geojson')
storage_unit.geometry = storage_unit.geometry.apply(remove_third_dimension)
storage_unit.to_file('geodata verfication/storage_unit.geojson', driver = 'GeoJSON')
trap_unit = gpd.read_file('data/trap_map_lite.geojson')
trap_unit.geometry = trap_unit.geometry.apply(remove_third_dimension)
complete_map = gpd.read_file('data/complete_map_37.geojson')
complete_map.geometry = complete_map.geometry.apply(remove_third_dimension)
complete_map.geometry = complete_map.geometry.buffer(0)
```
# Prepare Data for Visualization
```
# prepare data of capacity detail
storage_unit_summary = storage_unit.groupby('COUNTRYCOD').sum()[[i for i in storage_unit.columns if i not in move]]
storage_unit_summary.columns = [x+'storage_unit' for x in storage_unit_summary.columns]
trap_unit_summary = trap_unit.groupby('COUNTRYCOD').sum()[[i for i in trap_unit.columns if i not in move]]
trap_unit_summary.drop(capacity_list,axis=1,inplace=True)
storage_type_detail = storage_unit_summary.merge(trap_unit_summary,
left_index= True,
right_index= True,
how= 'outer')
def view_storage_type_detail(estimation_type = 'conservative'):
# columns selection
tmp_df = storage_type_detail[[x for x in storage_type_detail.columns if re.search(estimation_type,x)]].copy()
tmp_df.columns = ['Storage_unit (normal density, geological formation to store CO2)',
'Aquifer (high density storage unit)',
'Oil (high density storage unit)',
'Gas (high density storage unit)']
for i in tmp_df.columns:
tmp_df[i] = tmp_df[i]/1e3
tmp_df.plot_bokeh.bar(stacked = True,figsize=(900, 500), xlabel = 'country', ylabel = 'capacity Gt',title = estimation_type + ' per country (unit: (Gt) gigaton)')
# total capacity
summary = complete_map.groupby('COUNTRYCOD').sum()[capacity_list]
summary.columns = [x.replace('Mt','') for x in summary.columns]
capacity_list_ = list(summary.columns)
summary = summary.reset_index()
summary = pd.melt(summary, id_vars= ['COUNTRYCOD'],value_vars = capacity_list_)
summary.value = summary.value/1e3 #Mt to Gt
# print
print('+'*20)
print('total capacity of whole Europe unit: Gigaton')
print('+'*20)
print(summary.groupby('variable').sum()['value'])
#---------------------------------------------------
# offshore capacity
offshore = gpd.read_file('data/offshore_shapes.geojson')
only_offshore = gpd.clip(complete_map, offshore)
summary_position_holder = summary.copy()
summary_position_holder.value = 0
summary_2 = only_offshore.groupby('COUNTRYCOD').sum()[capacity_list]
summary_2.columns = [x.replace('Mt','') for x in summary_2.columns]
capacity_list_ = list(summary_2.columns)
summary_2 = summary_2.reset_index()
summary_2 = pd.melt(summary_2, id_vars= ['COUNTRYCOD'],value_vars = capacity_list_)
summary_2.value = summary_2.value/1e3 #Mt to Gt
summary_2 = pd.concat([summary_2, summary_position_holder]).groupby(['COUNTRYCOD','variable']).sum().reset_index()
print('\n\n')
print('+'*20)
print('total offshore capacity of whole Europe unit: Gigaton')
print('+'*20)
print(summary_2.groupby('variable').sum()['value'])
```
# Capacity of all European countries split by storage type
```
view_storage_type_detail('neutral')
```
**external GB dataset's capacity estimation (only for United Kingdom):**
- total 61.768 Gt | storage_unit + aquifer: 52.749 Gt | oil: 2.678 Gt | gas: 5.997 Gt
# Total offshore capacity of each country under different estimations
## vs
# Total capacity of each country under different estimations
```
import seaborn as sns
from matplotlib import pyplot as plt
f,axes = plt.subplots(2,1,figsize = (20,12))
sub1 = sns.barplot(x = 'COUNTRYCOD', y='value', hue = 'variable',data= summary_2, ax = axes[0] )
sub1.set_yscale("log")
sub1.title.set_text('Offshore Capacity')
sub1.set_ylabel('Capacity (Gt) log scale',fontsize = 20)
#sub1.set_xlabel('Country',fontsize = 20)
sub2 = sns.barplot(x = 'COUNTRYCOD', y='value', hue = 'variable',data= summary, ax = axes[1] )
sub2.set_yscale("log")
sub2.title.set_text('Total Capacity')
sub2.set_ylabel('Capacity (Gt) log scale',fontsize = 20)
#sub2.set_xlabel('Country',fontsize = 20)
plt.show()
# y in log scale change the name of y axis
```
# Storage Map
```
pandas_bokeh.output_notebook()
#pandas_bokeh.output_file("Interactive storage unit.html")
complete_map = complete_map.sort_values('conservative estimate Mt',ascending= True)
complete_map.plot_bokeh(
figsize=(900, 600),
simplify_shapes=5000,
dropdown=capacity_list,
colormap="Viridis",
hovertool_columns=capacity_list+['ID'],
colormap_range = (0,100)
)
```
| github_jupyter |
```
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/'
'mushroom/agaricus-lepiota.data', header=None, engine='python')
column_name = ['classes','cap-shape', 'cap-surface','cap-color','bruises?','odor',
'gill-attachment','gill-spacing','gill-size','gill-color',
'stalk-shape','stalk-root','stalk-surface-above-ring',
'stalk-surface-below-ring','stalk-color-above-ring',
'stalk-color-below-ring','veil-type','veil-color','ring-number',
'ring-type','spore-print-color','population','habitat']
df.columns = column_name
df.head()
import numpy as np
from sklearn.preprocessing import LabelEncoder
# Todo
# deal missing value denoted by '?'
# encode label first
label_le = LabelEncoder()
df['classes'] = label_le.fit_transform(df['classes'].values)
catego_le = LabelEncoder()
num_values = []
for i in column_name[1:]:
df[i] = catego_le.fit_transform(df[i].values)
classes_list = catego_le.classes_.tolist()
# store the total number of values
num_values.append(len(classes_list))
# replace '?' with 'NaN'
if '?' in classes_list:
idx = classes_list.index('?')
df[i] = df[i].replace(idx, np.nan)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
X = df.drop('classes', axis=1).values
y = df['classes'].values
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0)
catego_features_idx = []
for fea in column_name[1:]:
catego_features_idx.append(df.columns.tolist().index(fea))
# define pipeline with an arbitrary number of transformer in a tuple array
pipe_knn = Pipeline([('imr', Imputer(missing_values='NaN', strategy='most_frequent', axis=0)),
('ohe', OneHotEncoder(n_values=num_values, sparse=False)),
('scl', StandardScaler()),
('clf', KNeighborsClassifier(n_neighbors=10, p=2, metric='minkowski'))])
pipe_svm = Pipeline([('imr', Imputer(missing_values='NaN', strategy='most_frequent', axis=0)),
('ohe', OneHotEncoder(n_values=num_values, sparse=False)),
('scl', StandardScaler()),
('clf', SVC(kernel='rbf', random_state=0, gamma=0.001, C=100.0))])
# use the pipeline model to train
pipe_knn.fit(X_train, y_train)
y_pred = pipe_knn.predict(X_test)
print('[KNN]')
print('Misclassified samples: %d' % (y_test != y_pred).sum())
print('Accuracy: %.4f' % accuracy_score(y_test, y_pred))
pipe_svm.fit(X_train, y_train)
y_pred = pipe_svm.predict(X_test)
print('\n[SVC]')
print('Misclassified samples: %d' % (y_test != y_pred).sum())
print('Accuracy: %.4f' % accuracy_score(y_test, y_pred))
```
### Report ###
In this homework, I tried two different models using the sklearn pipeline.
For the preprocessing part, I used imputer to impute the missing data, and one-hot encoding for category features.
And then I use KNN classifier for the first model, SVC for the second model.
They both perform quite well, so I thought there's no need to do additional feature selection.
| github_jupyter |
# python behaves like a calculator
```
8*8
```
#### Predict the following output
```
print((5+5)/25)
print(5 + 5/25)
```
python does order of operations, etc. just like a calculator
#### Most of the notation is intuitive.
Write out the following in a cell. What value to you get?
$$ (5 \times 5 + \frac{4}{2} - 8)^{2}$$
Most notation is intuitive. Only weirdo is that "raise x to the power of y" is given by `x**y` rather than `x^y`.
What is the value of $sin(2)$?
```
sin(2)
```
Python gives very informative errors (if you know how to read them). What do you think `NameError` means?
`NameError` means that the current python "interpreter" does know what `sin` means
To get access to more math, you need
`import math`
```
import math
math.sin(2)
```
Once you have math imported, you have access to a whole slew of math functions.
```
print(math.factorial(10))
print(math.sqrt(10))
print(math.sin(math.pi))
print(math.cos(10))
print(math.exp(10))
print(math.log(10))
print(math.log10(10))
```
If you want to see what the `math` module has to offer, type `math.` and then hit `TAB`.
<img src="python-as-a-calculator/math-dropdown.png" />
```
# for example
math.
```
You can also get information about a function by typing `help(FUNCTION)`. If you run the next cell, it will give you information about the `math.factorial` function.
```
help(math.factorial)
```
### Variables
#### Predict what will happen.
```
x = 5
print(x)
x = 5
x = x + 2
print(x)
```
In python "`=`" means "assign the stuff on the right into the stuff on the left."
#### Predict what will happen.
```
x = 7
5*5 = x
print(x)
```
What happened?
`SyntaxError` is something python can't interpret.
In python, `=` means store the output of the stuff on the **right** in the variable on the **left**. It's nonsensical to try to store anything in `5*5`, so the command fails.
#### Predict what will happen.
```
this_is_a_variable = 5
another_variable = 2
print(this_is_a_variable*another_variable)
```
Variables can (and **should**) have descriptive names.
#### Implement
Stirling's approximation says that you can approximate $n!$ using some nifty log tricks.
$$ ln(n!) \approx nln(n) - n + 1 $$
Write code to check this approximation for **any** value of $n$.
## Summary
+ Python behaves like a calculator (order of operations, etc.).
+ You can assign the results of calculations to variables using "`=`"
+ Python does the stuff on the right first, then assigns it to the name on the left.
+ You can access more math by `import math`
| github_jupyter |
```
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from pathlib import Path
from sklearn.preprocessing import StandardScaler
# Loading data
file_path = Path("crypto_data.csv")
df = pd.read_csv(file_path)
df
df.dtypes
#filter for currencies that are currently being traded
df_drop_trading=df.loc[(df['IsTrading']==True)]
df_drop_trading
df_drop_trading.count()
#drop the IsTrading column from the dataframe.
df_drop_trading=df_drop_trading.drop("IsTrading", axis=1)
df_drop_trading
# Count of rows with null values
df_drop_trading.isnull().sum()
# Delete rows with null values
df_trading = df_drop_trading.dropna()
#Check data again, we drop the row which column value is null
df_trading.count()
#Filter for cryptocurrencies that have been mined. That is, the total coins mined should be greater than zero.
df_filter=df_trading.loc[(df_trading['TotalCoinsMined']>0)]
df_filter #the row drop from 685 to 532
#Drop the coin names do not contribute to the analysis of the data
df_clean=df_filter.drop(["Unnamed: 0", "CoinName"], axis=1)
df_clean
#convert the remaining features with text values, Algorithm and ProofType, into numerical data.
X=pd.get_dummies(df_clean)
X #Feature colmuns increase from 4 to 377
#Standardize dataset
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
X_scaled
# Applying PCA to reduce dimensions from 377 to 100
# Initialize PCA model
from sklearn.decomposition import PCA
pca = PCA(n_components=0.99)
# Get principal components for the X_scaled data.
X_pca = pca.fit_transform(X_scaled)
X_pca
# Fetch the explained variance
pca.explained_variance_ratio_
#reduce the dataset dimensions with t-SNE and visually inspect the results.
from sklearn.manifold import TSNE
# Initialize t-SNE model
tsne = TSNE(learning_rate=35)
# Reduce dimensions
tsne_features = tsne.fit_transform(X_pca)
# The dataset has 2 columns
tsne_features.shape
tsne_features
# Prepare to plot the dataset
# The first column of transformed features
X['x'] = tsne_features[:,0]
# The second column of transformed features
X['y'] = tsne_features[:,1]
# Visualize the clusters
plt.scatter(X['x'], X['y'])
plt.show()
#Create an elbow plot to identify the best number of clusters.
from sklearn.cluster import KMeans
inertia = []
# Same as k = list(range(1, 11))
k = [1,2,3,4,5,6,7,8,9,10]
# Looking for the best k
for i in k:
km = KMeans(n_clusters=i, random_state=0)
km.fit(X_pca)
inertia.append(km.inertia_)
# Define a DataFrame to plot the Elbow Curve using hvPlot
elbow_data = {"k": k, "inertia": inertia}
df_elbow = pd.DataFrame(elbow_data)
plt.plot(df_elbow['k'], df_elbow['inertia'])
plt.xticks(range(1,11))
plt.xlabel('Number of clusters')
plt.ylabel('Inertia')
plt.show()
```
## By using t-SNE
I got 2 cluster which it's really interesting!! Like moon outside and sun inside the moon, which may mean there has lots of noise in the dataset.
I run t-SNE several times, I got different chart, it's really interesting but the chart are similar like one cluster in the center, and other point around the center.
## KMeans
After that using KMeans by fit the pca dataset, we got elbow plot but hrad to siad that which point is the best n_clusters? Maybe we should run the model more than 10 which mean range (1,20), and see that if we can get better result.
| github_jupyter |
```
try:
from openmdao.utils.notebook_utils import notebook_mode
except ImportError:
!python -m pip install openmdao[notebooks]
```
# How to know if a System is under FD or CS
All Systems (Components and Groups) have two flags that indicate whether the System is running under finite difference or complex step. The `under_finite_difference` flag is True if the System is being finite differenced and the `under_complex_step` flag is True if the System is being complex stepped.
## Usage
First we'll show how to detect when a component is being finite differenced:
```
import numpy as np
import openmdao.api as om
class MyFDPartialComp(om.ExplicitComponent):
def setup(self):
self.num_fd_computes = 0
self.add_input('x')
self.add_output('y')
def setup_partials(self):
self.declare_partials('y', 'x', method='fd')
def compute(self, inputs, outputs):
outputs['y'] = 1.5 * inputs['x']
if self.under_finite_difference:
self.num_fd_computes += 1
print(f"{self.pathname} is being finite differenced!")
p = om.Problem()
p.model.add_subsystem('comp', MyFDPartialComp())
p.setup()
p.run_model()
# there shouldn't be any finite difference computes yet
print("Num fd calls = ", p.model.comp.num_fd_computes)
totals = p.compute_totals(['comp.y'], ['comp.x'])
# since we're doing forward difference, there should be 1 call to compute under fd
print("Num fd calls =", p.model.comp.num_fd_computes)
assert p.model.comp.num_fd_computes == 1
```
Now we'll do the same thing for a complex stepped component:
```
import numpy as np
import openmdao.api as om
class MyCSPartialComp(om.ExplicitComponent):
def setup(self):
self.num_cs_computes = 0
self.add_input('x')
self.add_output('y')
def setup_partials(self):
self.declare_partials('y', 'x', method='cs')
def compute(self, inputs, outputs):
outputs['y'] = 1.5 * inputs['x']
if self.under_complex_step:
self.num_cs_computes += 1
print(f"{self.pathname} is being complex stepped!")
p = om.Problem()
p.model.add_subsystem('comp', MyCSPartialComp())
p.setup()
p.run_model()
# there shouldn't be any complex step computes yet
print("Num cs calls =", p.model.comp.num_cs_computes)
totals = p.compute_totals(['comp.y'], ['comp.x'])
# there should be 1 call to compute under cs
print("Num cs calls =", p.model.comp.num_cs_computes)
assert p.model.comp.num_cs_computes == 1
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import descartes
import geopandas as gpd
from shapely.geometry import Point, Polygon
from shapely.ops import nearest_points
import seaborn as sns
from mpl_toolkits.axes_grid1 import make_axes_locatable
import math
import time
from matplotlib import cm
import matplotlib.lines as mlines
%matplotlib inline
```
### AIR POLLUTION MONITORING DATA FROM EDF
```
df = pd.read_csv('EDF_Data.csv', header = 1)
df['TimePeriod'] = 'Jun2015-May2016'
df.tail()
df.shape
geometry = [Point(xy) for xy in zip(df['Longitude'], df['Latitude'])]
```
### Split the dataset into BC and NO2 since we are interested only in those two pollutants
```
BC_df = df[['Longitude', 'Latitude', 'BC Value', 'TimePeriod']]
NO2_df = df[['Longitude', 'Latitude', 'NO2 Value', 'TimePeriod']]
crs = {'init': 'epsg:4326'}
geo_df = gpd.GeoDataFrame(df, crs = crs, geometry = geometry)
```
## TRAFFIC DATA
```
### Load Annual Average Daily Traffic (AADT) file from Caltrans
traffic = pd.read_csv('Data/Traffic_Oakland_AADT.csv', header = 0)
# Drop columns that are unneccessary and choose only Ahead_AADT, along with N/E latitude and longitude
traffic.drop(columns = ['OBJECTID','District','Route','County', 'Postmile',
'Back_pk_h', 'Back_pk_m', 'Ahead_pk_h', 'Ahead_pk_m','Back_AADT','Lat_S_or_W', 'Lon_S_or_W'], inplace=True)
traffic.rename(columns={"Ahead_AADT":"AADT", "Lat_N_or_E":"Latitude", "Lon_N_or_E":"Longitude", "Descriptn":"Description"}, inplace=True)
traffic.head()
# Taking a closer look at the traffic data, there are some intersections where the AADT is zero, or the latitude and longitude are zero. We want to drop these rows
traffic = traffic[(traffic['Longitude']<-1) & (traffic['AADT']>1)]
traffic.shape
```
## Converting facility and traffic dataframe into a geopandas dataframe for plotting
```
# Create a geopandas dataframe with traffic data
geometry_traffic = [Point(xy) for xy in zip(traffic['Longitude'], traffic['Latitude'])]
geo_df_traffic = gpd.GeoDataFrame(traffic, crs = crs, geometry = geometry_traffic)
# Create a list of x and y coordinates for the Black Carbon concentration data using geopandas
geometry_df_BC = [Point(xy) for xy in zip(BC_df['Longitude'], BC_df['Latitude'])]
geo_df_BC = gpd.GeoDataFrame(BC_df, crs = crs, geometry = geometry_df_BC)
```
### Calculate distance between point of measurement and each facility and add it to the _dist column
```
### Defining a function to calculate the distance between two GPS coordinates (latitude and longitude)
def distance(origin, destination):
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
dlat = math.radians(lat2-lat1)
dlon = math.radians(lon2-lon1)
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
* math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
d = radius * c
return d
```
#### Loading Traffic Data
```
traffic.head()
## Assign an intersection number to each traffic intersection instead of using description
traffic.reset_index(inplace=True)
#Rename index as Intersection
traffic.rename(columns={"index":"Intersection"}, inplace=True)
#Drop the description column
traffic.drop(columns=['Description'], inplace=True)
### Add an empty column for distance
traffic['dist'] = 0
traffic['dist'].astype(float)
traffic_lat = traffic[['Intersection', 'Latitude']].T
traffic_long = traffic[['Intersection', 'Longitude']].T
traffic_AADT = traffic[['Intersection', 'AADT']].T
traffic_dist = traffic[['Intersection', 'dist']].T
traffic_geo = traffic[['Intersection', 'geometry']].T
traffic_lat.head()
## Make the header as the first row in each transposed dataframe
traffic_lat = traffic_lat.rename(columns=traffic_lat.iloc[0].astype(int)).drop(traffic_lat.index[0])
traffic_long = traffic_long.rename(columns=traffic_long.iloc[0].astype(int)).drop(traffic_long.index[0])
traffic_AADT = traffic_AADT.rename(columns=traffic_AADT.iloc[0].astype(int)).drop(traffic_AADT.index[0])
traffic_dist = traffic_dist.rename(columns=traffic_dist.iloc[0].astype(int)).drop(traffic_dist.index[0])
traffic_geo = traffic_geo.rename(columns=traffic_geo.iloc[0].astype(int)).drop(traffic_geo.index[0])
## Add suffix to column header based on the dataframe type
traffic_lat.columns = [str(col) + '_latitude' for col in traffic_lat.columns]
traffic_long.columns = [str(col) + '_longitude' for col in traffic_long.columns]
traffic_AADT.columns = [str(col) + '_AADT' for col in traffic_AADT.columns]
traffic_dist.columns = [str(col) + '_traf_dist' for col in traffic_dist.columns]
traffic_geo.columns = [str(col) + '_geo' for col in traffic_geo.columns]
## Remove index for each dataframe
traffic_lat.reset_index(drop=True, inplace=True)
traffic_long.reset_index(drop=True, inplace=True)
traffic_AADT.reset_index(drop=True, inplace=True)
traffic_dist.reset_index(drop=True, inplace=True)
traffic_geo.reset_index(drop=True, inplace=True)
traffic_combined = traffic_lat.join(traffic_long).join(traffic_AADT).join(traffic_dist).join(traffic_geo)
traffic_combined
traffic_combined = traffic_combined.reindex(columns=sorted(traffic_combined.columns))
#Create a datafram where each row contains emissions of PM10 and PM2.5 for each facility
traffic_combined = traffic_combined.loc[traffic_combined.index.repeat(21488)].reset_index(drop=True)
BC_Traffic = BC_df.join(traffic_combined)
BC_Traffic.head()
# Convert distance column to float type
for idx, col in enumerate(BC_Traffic.columns):
if "_traf_dist" in col:
BC_Traffic[col] = pd.to_numeric(BC_Traffic[col], downcast="float")
```
#### Calculate distance between each traffic intersection and point of measurement and store this in the _dist column
```
for index, row in BC_Traffic.iterrows():
for idx, col in enumerate(BC_Traffic.columns):
if "_traf_dist" in col:
BC_Traffic.at[index,col] = float(distance((row.iloc[1], row.iloc[0]), (row.iloc[idx-2], row.iloc[idx-1])))*0.621
#BC_Facility_Traffic.at[index,col] = float(row.iloc[idx])
BC_Traffic.head()
#### Write this to a dataframe
BC_Traffic.to_csv("Data/BC_Traffic_ALL.csv")
```
#### Similar to the facility dataframe, drop latitude and longitude since its captured in the distance column. Also drop AADT
```
BC_Traffic.drop(list(BC_Traffic.filter(regex = '_latitude')), axis = 1, inplace = True)
BC_Traffic.drop(list(BC_Traffic.filter(regex = '_longitude')), axis = 1, inplace = True)
BC_Traffic.drop(list(BC_Traffic.filter(regex = '_AADT')), axis = 1, inplace = True)
BC_Traffic.drop(list(BC_Traffic.filter(regex = '_geo')), axis = 1, inplace = True)
BC_Traffic.drop(list(BC_Traffic.filter(regex = 'Longitude')), axis = 1, inplace = True)
BC_Traffic.drop(list(BC_Traffic.filter(regex = 'Latitude')), axis = 1, inplace = True)
BC_Traffic.drop(list(BC_Traffic.filter(regex = 'TimePeriod')), axis = 1, inplace = True)
BC_Traffic.drop(list(BC_Traffic.filter(regex = 'geometry')), axis = 1, inplace = True)
BC_Traffic.head()
corr = BC_Traffic.corr()
arr_corr = corr.as_matrix()
arr_corr[0]
```
#### Plotting correlation between all features as a heatmap - but this visualization is not easy to follow....
fig, ax = plt.subplots(figsize=(100, 100))
ax = sns.heatmap(
corr,
vmin=-1, vmax=1, center=0,
cmap=sns.diverging_palette(20, 220, n=500),
square=False
)
ax.set_xticklabels(
ax.get_xticklabels(),
rotation=45,
horizontalalignment='right'
);
plt.show()
```
print(plt.get_backend())
# close any existing plots
plt.close("all")
# mask out the top triangle
arr_corr[np.triu_indices_from(arr_corr)] = np.nan
fig, ax = plt.subplots(figsize=(50, 50))
hm = sns.heatmap(arr_corr, cbar=True, vmin = -1, vmax = 1, center = 0,
fmt='.2f', annot_kws={'size': 8}, annot=True,
square=False, cmap = 'coolwarm')
#cmap=plt.cm.Blues
ticks = np.arange(corr.shape[0]) + 0.5
ax.set_xticks(ticks)
ax.set_xticklabels(corr.columns, rotation=90, fontsize=8)
ax.set_yticks(ticks)
ax.set_yticklabels(corr.index, rotation=360, fontsize=8)
ax.set_title('correlation matrix')
plt.tight_layout()
#plt.savefig("corr_matrix_incl_anno_double.png", dpi=300)
```
#### Once again there doesn't seem to be much correlation between BC concentrations and the closest major traffic intersection. Next option is to identify all the traffic intersections in the area.
import chart_studio.plotly as py
import plotly.graph_objs as go
import chart_studio
chart_studio.tools.set_credentials_file(username='varsha2509', api_key='QLfBsWWLPKoLjY5hW0Fu')
heatmap = go.Heatmap(z=arr_corr, x=BC_Facility_Traffic_Met.columns, y=BC_Facility_Traffic_Met.index)
data = [heatmap]
py.iplot(data, filename='basic-heatmap')
| github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Datasets/Vectors/world_database_on_protected_areas.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Datasets/Vectors/world_database_on_protected_areas.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td>
<td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Datasets/Vectors/world_database_on_protected_areas.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Datasets/Vectors/world_database_on_protected_areas.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td>
</table>
## Install Earth Engine API
Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`.
The magic command `%%capture` can be used to hide output from a specific cell. Uncomment these lines if you are running this notebook for the first time.
```
# %%capture
# !pip install earthengine-api
# !pip install geehydro
```
Import libraries
```
import ee
import folium
import geehydro
```
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()`
if you are running this notebook for the first time or if you are getting an authentication error.
```
# ee.Authenticate()
ee.Initialize()
```
## Create an interactive map
This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function.
The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.
```
Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID')
```
## Add Earth Engine Python script
```
dataset = ee.FeatureCollection('WCMC/WDPA/current/polygons')
visParams = {
'palette': ['2ed033', '5aff05', '67b9ff', '5844ff', '0a7618', '2c05ff'],
'min': 0.0,
'max': 1550000.0,
'opacity': 0.8,
}
image = ee.Image().float().paint(dataset, 'REP_AREA')
Map.setCenter(41.104, -17.724, 6)
Map.addLayer(image, visParams, 'WCMC/WDPA/current/polygons')
# Map.addLayer(dataset, {}, 'for Inspector', False)
dataset = ee.FeatureCollection('WCMC/WDPA/current/points')
styleParams = {
'color': '#4285F4',
'width': 1,
}
protectedAreaPoints = dataset.style(**styleParams)
# Map.setCenter(110.57, 0.88, 4)
Map.addLayer(protectedAreaPoints, {}, 'WCMC/WDPA/current/points')
```
## Display Earth Engine data layers
```
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map
```
| github_jupyter |
# Self-Driving Car Engineer Nanodegree
## Project: **Finding Lane Lines on the Road**
***
In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip "raw-lines-example.mp4" (also contained in this repository) to see what the output should look like after using the helper functions below.
Once you have a result that looks roughly like "raw-lines-example.mp4", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.
In addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.
---
Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the "play" button above) to display the image.
**Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the "Kernel" menu above and selecting "Restart & Clear Output".**
---
**The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.**
---
<figure>
<img src="examples/line-segments-example.jpg" width="380" alt="Combined Image" />
<figcaption>
<p></p>
<p style="text-align: center;"> Your output should look something like this (above) after detecting line segments using the helper functions below </p>
</figcaption>
</figure>
<p></p>
<figure>
<img src="examples/laneLines_thirdPass.jpg" width="380" alt="Combined Image" />
<figcaption>
<p></p>
<p style="text-align: center;"> Your goal is to connect/average/extrapolate line segments to get output like this</p>
</figcaption>
</figure>
**Run the cell below to import some packages. If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**
## Import Packages
```
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
```
## Read in an Image
```
#reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type(image), 'with dimensions:', image.shape)
plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')
```
## Ideas for Lane Detection Pipeline
**Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**
`cv2.inRange()` for color selection
`cv2.fillPoly()` for regions selection
`cv2.line()` to draw lines on an image given endpoints
`cv2.addWeighted()` to coadd / overlay two images
`cv2.cvtColor()` to grayscale or change color
`cv2.imwrite()` to output images to file
`cv2.bitwise_and()` to apply a mask to an image
**Check out the OpenCV documentation to learn about these and discover even more awesome functionality!**
## Helper Functions
Below are some helper functions to help get you started. They should look familiar from the lesson!
```
import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
# return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold)
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
`vertices` should be a numpy array of integer points.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
#returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def draw_lines(img, lines, color=[255, 0, 0], thickness=2):
"""
NOTE: this is the function you might want to use as a starting point once you want to
average/extrapolate the line segments you detect to map out the full
extent of the lane (going from the result shown in raw-lines-example.mp4
to that shown in P1_example.mp4).
Think about things like separating line segments by their
slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left
line vs. the right line. Then, you can average the position of each of
the lines and extrapolate to the top and bottom of the lane.
This function draws `lines` with `color` and `thickness`.
Lines are drawn on the image inplace (mutates the image).
If you want to make the lines semi-transparent, think about combining
this function with the weighted_img() function below
"""
for line in lines:
for x1,y1,x2,y2 in line:
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
Returns an image with hough lines drawn.
"""
lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
draw_lines(line_img, lines)
return line_img
# Python 3 has support for cool math symbols.
def weighted_img(img, initial_img, α=0.8, β=1., γ=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * α + img * β + γ
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, α, img, β, γ)
```
## Test Images
Build your pipeline to work on the images in the directory "test_images"
**You should make sure your pipeline works well on these images before you try the videos.**
```
import os
os.listdir("test_images/")
```
## Build a Lane Finding Pipeline
Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.
Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.
```
# TODO: Build your pipeline that will draw lane lines on the test_images
# then save them to the test_images_output directory.
```
## Test on Videos
You know what's cooler than drawing lanes over images? Drawing lanes over video!
We can test our solution on two provided videos:
`solidWhiteRight.mp4`
`solidYellowLeft.mp4`
**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**
**If you get an error that looks like this:**
```
NeedDownloadError: Need ffmpeg exe.
You can download it by calling:
imageio.plugins.ffmpeg.download()
```
**Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**
```
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
def process_image(image):
# NOTE: The output you return should be a color image (3 channel) for processing video below
# TODO: put your pipeline here,
# you should return the final output (image where lines are drawn on lanes)
return result
```
Let's try the one with the solid white lane on the right first ...
```
white_output = 'test_videos_output/solidWhiteRight.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
##clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4").subclip(0,5)
clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4")
white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
%time white_clip.write_videofile(white_output, audio=False)
```
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.
```
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output))
```
## Improve the draw_lines() function
**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4".**
**Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**
Now for the one with the solid yellow lane on the left. This one's more tricky!
```
yellow_output = 'test_videos_output/solidYellowLeft.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)
clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image)
%time yellow_clip.write_videofile(yellow_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(yellow_output))
```
## Writeup and Submission
If you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) to the writeup template file.
## Optional Challenge
Try your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!
```
challenge_output = 'test_videos_output/challenge.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
##clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)
clip3 = VideoFileClip('test_videos/challenge.mp4')
challenge_clip = clip3.fl_image(process_image)
%time challenge_clip.write_videofile(challenge_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(challenge_output))
```
| github_jupyter |
# The Unique Properties of Qubits
```
from qiskit import *
from qiskit.visualization import plot_histogram
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
```
You now know something about bits, and about how our familiar digital computers work. All the complex variables, objects and data structures used in modern software are basically all just big piles of bits. Those of us who work on quantum computing call these *classical variables.* The computers that use them, like the one you are using to read this article, we call *classical computers*.
In quantum computers, our basic variable is the _qubit_: a quantum variant of the bit. These are quantum objects, obeying the laws of quantum mechanics. Unlike any classical variable, these cannot be represented by some number of classical bits. They are fundamentally different.
The purpose of this section is to give you your first taste of what a qubit is, and how they are unique. We'll do this in a way that requires essentially no math. This means leaving terms like 'superposition' and 'entanglement' until future sections, since it is difficult to properly convey their meaning without pointing at an equation.
Instead, we will use another well-known feature of quantum mechanics: the uncertainty principle.
### Heisenberg's uncertainty principle
The most common formulation of the uncertainty principle refers to the position and momentum of a particle: the more precisely its position is defined, the more uncertainty there is in its momentum, and vice-versa.

This is a common feature of quantum objects, though it need not always refer to position and momentum. There are many possible sets of parameters for different quantum objects, where certain knowledge of one means that our observations of the others will be completely random.
To see how the uncertainty principle affects qubits, we need to look at measurement. As we saw in the last section, this is the method by which we extract a bit from a qubit.
```
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0)
measure_z.draw(output='mpl')
```
On the [Circuit Composer](https://quantum-computing.ibm.com/composer), the same operation looks like this.

This version has a small ‘z’ written in the box that represents the operation. This hints at the fact that this kind of measurement is not the only one. In fact, it is only one of an infinite number of possible ways to extract a bit from a qubit. Specifically, it is known as a *z measurement*.
Another commonly used measurement is the *x measurement*. It can be performed using the following sequence of gates.
```
measure_x = QuantumCircuit(1,1)
measure_x.h(0)
measure_x.measure(0,0)
measure_x.draw(output='mpl')
```
Later chapters will explain why this sequence of operations performs a new kind of measurement. For now, you'll need to trust us.
Like the position and momentum of a quantum particle, the z and x measurements of a qubit are governed by the uncertainty principle. Below we'll look at results from a few different circuits to see this effect in action.
#### Results for an empty circuit
The easiest way to see an example is to take a freshly initialized qubit.
```
qc_0 = QuantumCircuit(1)
qc_0.draw(output='mpl')
```
Qubits are always initialized such that they are certain to give the result `0` for a z measurement. The resulting histogram will therefore simply have a single column, showing the 100% probability of getting a `0`.
```
qc = qc_0 + measure_z
print('Results for z measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
```
If we instead do an x measurement, the results will be completely random.
```
qc = qc_0 + measure_x
print('Results for x measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
```
Note that the reason why the results are not split exactly 50/50 here is because we take samples by repeating the circuit a finite number of times, and so there will always be statistical noise. In this case, the default of `shots=1024` was used.
#### Results for a single Hadamard
Now we'll try a different circuit. This has a single gate called a Hadamard, which we will learn more about in future sections.
```
qc_plus = QuantumCircuit(1)
qc_plus.h(0)
qc_plus.draw(output='mpl')
```
To see what effect it has, let's first try the z measurement.
```
qc = qc_plus + measure_z
qc.draw()
print('Results for z measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
```
Here we see that it is the results of the z measurement that are random for this circuit.
Now let's see what happens for an x measurement.
```
qc = qc_plus + measure_x
print('Results for x measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
```
For the x measurement, it is certain that the output for this circuit is `0`. The results here are therefore very different to what we saw for the empty circuit. The Hadamard has lead to an entirely opposite set of outcomes.
#### Results for a y rotation
Using other circuits we can manipulate the results in different ways. Here is an example with an `ry` gate.
```
qc_y = QuantumCircuit(1)
qc_y.ry( -3.14159/4,0)
qc_y.draw(output='mpl')
```
We will learn more about `ry` in future sections. For now, just notice the effect it has for the z and x measurements.
```
qc = qc_y + measure_z
print('Results for z measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
```
Here we have a case that we have not seen before. The z measurement is most likely to output `0`, but it is not completely certain. A similar effect is seen below for the x measurement: it is most likely, but not certain, to output `1`.
```
qc = qc_y + measure_x
print('\nResults for x measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
```
These results hint at an important principle: Qubits have a limited amount of certainty that they can hold. This ensures that, despite the different ways we can extract outputs from a qubit, it can only be used to store a single bit of information. In the case of the blank circuit, this certainty was dedicated entirely to the outcomes of z measurements. For the circuit with a single Hadamard, it was dedicated entirely to x measurements. In this case, it is shared between the two.
### Einstein vs. Bell
We have now played with some of the features of qubits, but we haven't done anything that couldn't be reproduced by a few bits and a random number generator. You can therefore be forgiven for thinking that quantum variables are just classical variables with some randomness bundled in.
This is essentially the claim made by Einstein, Podolsky and Rosen back in 1935. They objected to the uncertainty seen in quantum mechanics, and thought it meant that the theory was incomplete. They thought that a qubit should always know what output it would give for both kinds of measurement, and that it only seems random because some information is hidden from us. As Einstein said: God does not play dice with the universe.
No one spoke of qubits back then, and people hardly spoke of computers. But if we translate their arguments into modern language, they essentially claimed that qubits can indeed be described by some form of classical variable. They didn’t know how to do it, but they were sure it could be done. Then quantum mechanics could be replaced by a much nicer and more sensible theory.
It took until 1964 to show that they were wrong. J. S. Bell proved that quantum variables behaved in a way that was fundamentally unique. Since then, many new ways have been found to prove this, and extensive experiments have been done to show that this is exactly the way the universe works. We'll now consider a simple demonstration, using a variant of _Hardy’s paradox_.
For this we need two qubits, set up in such a way that their results are correlated. Specifically, we want to set them up such that we see the following properties.
1. If z measurements are made on both qubits, they never both output `0`.
2. If an x measurement of one qubit outputs `1`, a z measurement of the other will output `0`.
If we have qubits that satisfy these properties, what can we infer about the remaining case: an x measurement of both?
For example, let's think about the case where both qubits output `1` for an x measurement. By applying property 2 we can deduce what the result would have been if we had made z measurements instead: We would have gotten an output of `0` for both. However, this result is impossible according to property 1. We can therefore conclude that an output of `1` for x measurements of both qubits must also be impossible.
The paragraph you just read contains all the math in this section. Don't feel bad if you need to read it a couple more times!
Now let's see what actually happens. Here is a circuit, composed of gates you will learn about in later sections. It prepares a pair of qubits that will satisfy the above properties.
```
qc_hardy = QuantumCircuit(2)
qc_hardy.ry(1.911,1)
qc_hardy.cx(1,0)
qc_hardy.ry(0.785,0)
qc_hardy.cx(1,0)
qc_hardy.ry(2.356,0)
qc_hardy.draw(output='mpl')
```
Let's see it in action. First a z measurement of both qubits.
```
measurements = QuantumCircuit(2,2)
# z measurement on both qubits
measurements.measure(0,0)
measurements.measure(1,1)
qc = qc_hardy + measurements
print('\nResults for two z measurements:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
```
The probability of `00` is zero, and so these qubits do indeed satisfy property 1.
Next, let's see the results of an x measurement of one and a z measurement of the other.
```
measurements = QuantumCircuit(2,2)
# x measurement on qubit 0
measurements.h(0)
measurements.measure(0,0)
# z measurement on qubit 1
measurements.measure(1,1)
qc = qc_hardy + measurements
print('\nResults for two x measurement on qubit 0 and z measurement on qubit 1:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
```
The probability of `11` is zero. You'll see the same if you swap around the measurements. These qubits therefore also satisfy property 2.
Finally, let's look at an x measurement of both.
```
measurements = QuantumCircuit(2,2)
measurements.h(0)
measurements.measure(0,0)
measurements.h(1)
measurements.measure(1,1)
qc = qc_hardy + measurements
print('\nResults for two x measurement on both qubits:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
```
We reasoned that, given properties 1 and 2, it would be impossible to get the output `11`. From the results above, we see that our reasoning was not correct: one in every dozen results will have this 'impossible' result.
So where did we go wrong? Our mistake was in the following piece of reasoning.
> By applying property 2 we can deduce what the result would have been if we had made z measurements instead
We used our knowledge of the x outputs to work out what the z outputs were. Once we’d done that, we assumed that we were certain about the value of both. More certain than the uncertainty principle allows us to be. And so we were wrong.
Our logic would be completely valid if we weren’t reasoning about quantum objects. If it was some non-quantum variable, that we initialized by some random process, the x and z outputs would indeed both be well defined. They would just be based on some pre-determined list of random numbers in our computer, or generated by some deterministic process. Then there would be no reason why we shouldn't use one to deduce the value of the other, and our reasoning would be perfectly valid. The restriction it predicts would apply, and it would be impossible for both x measurements to output `1`.
But our qubits behave differently. The uncertainty of quantum mechanics allows qubits to dodge restrictions placed on classical variables. It allows them to do things that would otherwise be impossible. Indeed, this is the main thing to take away from this section:
> A physical system in a definite state can still behave randomly.
This is the first of the key principles of the quantum world. It needs to become your new intuition, as it is what makes quantum systems different to classical systems. It's what makes quantum computers able to outperform classical computers. It leads to effects that allow programs made with quantum variables to solve problems in ways that those with normal variables cannot. But just because qubits don’t follow the same logic as normal computers, it doesn’t mean they defy logic entirely. They obey the definite rules laid out by quantum mechanics.
If you’d like to learn these rules, we’ll use the remainder of this chapter to guide you through them. We'll also show you how to express them using math. This will provide a foundation for later chapters, in which we'll explain various quantum algorithms and techniques.
```
import qiskit
qiskit.__qiskit_version__
```
| github_jupyter |
<table><tr>
<td><img src="logos/JPL-NASA-logo_583x110.png" alt="JPL/NASA logo" style="height: 75px"/></td>
<td><img src="logos/CEOS-LOGO.png" alt="CEOS logo" style="height: 75px"/></td>
<td><img src="logos/CoverageLogoFullClear.png" alt="COVERAGE logo" style="height: 100px"/></td>
</tr></table>
# _Analytics Examples for COVERAGE_
# Important Notes
When you first connected you should have seen two notebook folders, `coverage` and `work`. The original version of this notebook is in the `coverage` folder and is read-only. If you would like to modify the code samples in this notebook, please first click `File`->`Save as...` to save your own copy in the `work` folder instead, and make your modifications to that copy.
We don't yet have resources in place to support a true multi-user environment for notebooks. This means that all saved notebooks are visible to all users. Thus, it would help to include your own unique identifier in the notebook name to avoid conflicts with others.
Furthermore, we do not guarantee to preserve the saved notebooks for any period of time. If you would like to keep your notebook, please remember to click `File`->`Download as`->`Notebook (.ipynb)` to download your own copy of the notebook at the end of each editting session.
# Notebook Setup
In the cell below are a few functions that help with plotting data using matplotlib. You shouldn't need to modify or pay much attention to this cell. Just run the cell to define the functions so that they can be used in the rest of the notebook.
```
%matplotlib inline
#######################################################################################
# In some jupyter deployments you will get an error about PROJ_LIB not being defined.
# In that case, uncomment these lines and set the directory to the location of your
# proj folder.
# import os
# import sys
# # Find where we are on the computer and make sure it is the pyICM directory
# HomeDir = os.path.expanduser('~') # get the home directory
# ICMDir = HomeDir + "Desktop/AIST_Project/SDAP_Jupyter"
# # Navigate to the home directory
# os.chdir(ICMDir)
# print('Moved to Directory',ICMDir)
# module_path = os.path.join(ICMDir,'code')
# print('Code Directory is',module_path)
# print('Adding to the system path')
# if module_path not in sys.path:
# sys.path.append(module_path)
#######################################################################################
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.colors as mcolors
import matplotlib.ticker as mticker
# from mpl_toolkits.basemap import Basemap
import cartopy.crs as ccrs #added by B Clark because Basemap is deprecated
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import numpy as np
import types
import math
import sys
import time
import requests
from datetime import datetime
import itertools
from shapely.geometry import box
from pprint import pprint, pformat
import textwrap
import warnings
warnings.filterwarnings("ignore")
# ISO-8601 date format
dt_format = "%Y-%m-%dT%H:%M:%SZ"
def show_plot(x_data, y_data, x_label=None, y_label=None, title=None):
"""
Display a simple line plot.
:param x_data: Numpy array containing data for the X axis
:param y_data: Numpy array containing data for the Y axis
:param x_label: Label applied to X axis
:param y_label: Label applied to Y axis
"""
plt.figure(figsize=(6,3), dpi=100)
plt.plot([datetime.fromtimestamp(x_val) for x_val in x_data], y_data, 'b-', marker='|', markersize=2.0, mfc='b')
plt.grid(b=True, which='major', color='k', linestyle='-')
if title is not None:
plt.title(title)
if x_label is not None:
plt.xlabel(x_label)
if y_label is not None:
plt.ylabel (y_label)
plt.xticks(rotation=45)
ts_range = x_data[-1] - x_data[0]
# Define the time formatting
if ts_range > 189216000: # 6 years
dtFmt = mdates.DateFormatter('%Y')
elif ts_range > 15552000: # 6 months
dtFmt = mdates.DateFormatter('%b %Y')
else: # < 6 months
dtFmt = mdates.DateFormatter('%b %-d, %Y')
plt.gca().xaxis.set_major_formatter(dtFmt)
plt.show()
def plot_box(bbox):
"""
Display a Green bounding box on an image of the blue marble.
:param bbox: Shapely Polygon that defines the bounding box to display
"""
min_lon, min_lat, max_lon, max_lat = bbox.bounds
import matplotlib.pyplot as plt1
import cartopy.crs as ccrs #added by B Clark because Basemap is deprecated
# modified 11/30/2021 to use Cartopy toolbox B Clark NASA GSFC
# from matplotlib.patches import Polygon
# from mpl_toolkits.basemap import Basemap
from shapely.geometry.polygon import Polygon
# map = Basemap()
# map.bluemarble(scale=0.5)
# poly = Polygon([(min_lon,min_lat),(min_lon,max_lat),(max_lon,max_lat),(max_lon,min_lat)],
# facecolor=(0,0,0,0.0),edgecolor='green',linewidth=2)
# plt1.gca().add_patch(poly)
# plt1.gcf().set_size_inches(10,15)
ax = plt1.axes(projection=ccrs.PlateCarree())
ax.stock_img()
# plt.show()
poly = Polygon(((min_lon,min_lat),(min_lon,max_lat),(max_lon,max_lat),(max_lon,min_lat),(min_lon,min_lat)))
ax.add_geometries([poly],crs=ccrs.PlateCarree(),facecolor='b', edgecolor='red', alpha=0.8)
# ax.fill(x, y, color='coral', alpha=0.4)
# plt1.gca().add_patch(poly)
# plt1.gcf().set_size_inches(10,15)
plt1.show()
def show_plot_two_series(x_data_a, x_data_b, y_data_a, y_data_b, x_label,
y_label_a, y_label_b, series_a_label, series_b_label,
title=''):
"""
Display a line plot of two series
:param x_data_a: Numpy array containing data for the Series A X axis
:param x_data_b: Numpy array containing data for the Series B X axis
:param y_data_a: Numpy array containing data for the Series A Y axis
:param y_data_b: Numpy array containing data for the Series B Y axis
:param x_label: Label applied to X axis
:param y_label_a: Label applied to Y axis for Series A
:param y_label_b: Label applied to Y axis for Series B
:param series_a_label: Name of Series A
:param series_b_label: Name of Series B
"""
font_size=12
plt.rc('font', size=font_size) # controls default text sizes
plt.rc('axes', titlesize=font_size) # fontsize of the axes title
plt.rc('axes', labelsize=font_size) # fontsize of the x and y labels
plt.rc('xtick', labelsize=font_size) # fontsize of the tick labels
plt.rc('ytick', labelsize=font_size) # fontsize of the tick labels
plt.rc('legend', fontsize=font_size) # legend fontsize
plt.rc('figure', titlesize=font_size) # fontsize of the figure title
fig, ax1 = plt.subplots(figsize=(10,5), dpi=100)
series_a, = ax1.plot(x_data_a, y_data_a, 'b-', marker='|', markersize=2.0, mfc='b', label=series_a_label)
ax1.set_ylabel(y_label_a, color='b')
ax1.tick_params('y', colors='b')
ax1.set_ylim(min(0, *y_data_a), max(y_data_a)+.1*max(y_data_a))
ax1.set_xlabel(x_label)
ax2 = ax1.twinx()
series_b, = ax2.plot(x_data_b, y_data_b, 'r-', marker='|', markersize=2.0, mfc='r', label=series_b_label)
ax2.set_ylabel(y_label_b, color='r')
ax2.set_ylim(min(0, *y_data_b), max(y_data_b)+.1*max(y_data_b))
ax2.tick_params('y', colors='r')
plt.grid(b=True, which='major', color='k', linestyle='-')
plt.legend(handles=(series_a, series_b), bbox_to_anchor=(1.1, 1), loc=2, borderaxespad=0.)
plt.title(title)
plt.show()
def ts_plot_two(ts_json1, ts_json2, dataset1, dataset2, units1, units2,
title='', t_name='time', val_name='mean'):
t1 = np.array([ts[0][t_name] for ts in ts_json1["data"]])
t2 = np.array([ts[0][t_name] for ts in ts_json2["data"]])
vals1 = np.array([ts[0][val_name] for ts in ts_json1["data"]])
vals2 = np.array([ts[0][val_name] for ts in ts_json2["data"]])
show_plot_two_series(t1, t2, vals1, vals2, "time (sec since 1970-01-01T00:00:00)",
units1, units2, dataset1, dataset2, title=title)
def scatter_plot(ts_json1, ts_json2, t_name="time", val_name="mean",
title="", xlabel="", ylabel=""):
times1 = np.array([ts[0][t_name] for ts in ts_json1["data"]])
times2 = np.array([ts[0][t_name] for ts in ts_json2["data"]])
vals1 = np.array([ts[0][val_name] for ts in ts_json1["data"]])
vals2 = np.array([ts[0][val_name] for ts in ts_json2["data"]])
vals_x = []
vals_y = []
for i1,t1 in enumerate(times1):
i = (np.abs(times2-times1[i1])).argmin()
if np.abs(times1[i1]-times2[i]) < 86400: # 24 hrs
vals_x.append(vals1[i1])
vals_y.append(vals2[i])
plt.scatter(vals_x, vals_y)
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.show()
def roundBorders(borders, borderSlop=10.):
b0 = roundBorder(borders[0], 'down', borderSlop, 0.)
b1 = roundBorder(borders[1], 'down', borderSlop, -90.)
b2 = roundBorder(borders[2], 'up', borderSlop, 360.)
b3 = roundBorder(borders[3], 'up', borderSlop, 90.)
return [b0, b1, b2, b3]
def roundBorder(val, direction, step, end):
if direction == 'up':
rounder = math.ceil
slop = step
else:
rounder = math.floor
slop = -step
### v = rounder(val/step) * step + slop
v = rounder(val/step) * step
if abs(v - end) < step+1.: v = end
return v
def normalizeLon(lon):
if lon < 0.: return lon + 360.
if lon > 360.: return lon - 360.
return lon
def normalizeLons(lons):
return np.array([normalizeLon(lon) for lon in lons])
def ensureItems(d1, d2):
for key in d2.keys():
if key not in d1: d1[key] = d2[key]
CmdOptions = {'MCommand': ['title', 'xlabel', 'ylabel', 'xlim', 'ylim', 'show\
'],
'plot': ['label', 'linewidth', 'legend', 'axis'],
'map.plot': ['label', 'linewidth', 'axis'],
'map.scatter': ['norm', 'alpha', 'linewidths', 'faceted', 'hold'\
],
'savefig': ['dpi', 'orientation']
}
def die(*s): warn('Error,', *s); sys.exit()
def evalKeywordCmds(options, cmdOptions=CmdOptions):
for option in options:
if option in cmdOptions['MCommand']:
args = options[option]
if args:
if args is True:
args = ''
else:
args = "'" + args + "'"
if option in cmdOptions:
args += dict2kwargs( validCmdOptions(options, cmdOptions[option]) )
try:
eval('plt.' + option + '(%s)' % args)
except:
die('failed eval of keyword command option failed: %s=%s' % (option, args))
def validCmdOptions(options, cmd, possibleOptions=CmdOptions):
return dict([(option, options[option]) for option in options.keys()
if option in possibleOptions[cmd]])
def dict2kwargs(d):
args = [',%s=%s' % (kw, d[kw]) for kw in d]
return ', '.join(args)
def imageMap(lons, lats, vals, vmin=None, vmax=None,
imageWidth=None, imageHeight=None, outFile=None,
projection='cyl', cmap=plt.cm.jet, logColors=False, makeFigure=False,
borders=[0., -90., 360., 90.], autoBorders=True, borderSlop=10.,
meridians=[0, 360, 60], parallels=[-60, 90, 30], title='', normalizeLongs=True,
**options):
if normalizeLongs:
lons = normalizeLons(lons)
if vmin == 'auto': vmin = None
if vmax == 'auto': vmax = None
if imageWidth is not None: makeFigure = True
if projection is None or projection == '': projection = 'cyl'
if cmap is None or cmap == '': cmap = plt.cm.jet
#if isinstance(cmap, types.StringType) and cmap != '':
if isinstance(cmap, str) and cmap != '':
try:
cmap = eval('plt.cm.' + cmap)
except:
cmap = plt.cm.jet
ensureItems(options, { \
'title': title, 'dpi': 100,
'imageWidth': imageWidth or 1024, 'imageHeight': imageHeight or 768})
if autoBorders:
borders = [min(lons), min(lats), max(lons), max(lats)]
borders = roundBorders(borders, borderSlop)
#m = Basemap(borders[0], borders[1], borders[2], borders[3], \
# projection=projection, lon_0=np.average([lons[0], lons[-1]]))
if makeFigure:
dpi = float(options['dpi'])
width = float(imageWidth) / dpi
height = width
#if imageHeight is None:
# height = width * m.aspect
#else:
# height = float(imageHeight) / dpi
#plt.figure(figsize=(width,height)).add_axes([0.1,0.1,0.8,0.8], frameon=True)
plt.figure(figsize=(width,height))
m = plt.axes(projection=ccrs.PlateCarree())
#m.set_extent([meridians[0], meridians[1], parallels[0], parallels[1]],
# crs=ccrs.PlateCarree())
gl = m.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=2, color='gray', alpha=0.5, linestyle='--')
gl.xlabels_top = False
gl.ylabels_left = True
gl.ylabels_right = False
gl.xlines = True
gl.ylines = True
gl.xlocator = mticker.FixedLocator(np.arange(meridians[0], meridians[1]+meridians[2], meridians[2]))
gl.ylocator = mticker.FixedLocator(np.arange(parallels[0], parallels[1]+parallels[2], parallels[2]))
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style = {'size': 12, 'color': 'black'}
gl.ylabel_style = {'size': 12, 'color': 'black'}
if vmin is not None or vmax is not None:
if vmin is None:
vmin = np.min(vals)
else:
vmin = float(vmin)
if vmax is None:
vmax = np.max(vals)
else:
vmax = float(vmax)
#vrange = (vmax - vmin) / 255.
#levels = np.arange(vmin, vmax, vrange/30.)
levels = np.linspace(vmin, vmax, 256)
else:
levels = 30
if logColors:
norm = mcolors.LogNorm(vmin=vmin, vmax=vmax)
else:
norm = None
# x, y = m(*np.meshgrid(lons,lats))
x, y = np.meshgrid(lons,lats)
c = m.contourf(x, y, vals, levels, cmap=cmap, colors=None, norm=norm)
# m.drawcoastlines()
m.coastlines()
#m.drawmeridians(range(meridians[0], meridians[1], meridians[2]), labels=[0,0,0,1])
#m.drawparallels(range(parallels[0], parallels[1], parallels[2]), labels=[1,1,1,1])
plt.colorbar(c, ticks=np.linspace(vmin,vmax,7), shrink=0.6)
evalKeywordCmds(options)
if outFile:
plt.savefig(outFile, **validCmdOptions(options, 'savefig'))
def arr2d_from_json(js, var_name):
return np.array([[js[i][j][var_name] for j in range(len(js[0]))] for i in range(len(js))])
def arr1d_from_json(js, var_name):
return np.array([js[i][var_name] for i in range(len(js))])
def plot_map(map, val_key="mean", cnt_key="cnt", lon_key="lon", lat_key="lat", fill=-9999, grid_line_sep=10,
border_slop=1, log_colors=False, title='', vmin=None, vmax=None,
normalize_lons=False, image_width=1000, **options):
# Parse values, longitudes and latitudes from JSON response.
vals = arr2d_from_json(map, val_key)
cnts = arr2d_from_json(map, cnt_key)
lons = arr1d_from_json(map[0], lon_key)
lats = arr1d_from_json([map[i][0] for i in range(len(map))], lat_key)
# If cnt is 0, set value to fill
vals[cnts==0] = fill
# Plot time time-averaged map as an image.
print("Creating plot of the results.")
print("This will take a minute. Please wait...")
min_val = np.min(vals[vals != fill])
if vmin is None:
vmin = min_val
max_val = np.max(vals[vals != fill])
if vmax is None:
vmax = max_val
min_lon = math.floor(np.min(lons)) - grid_line_sep
max_lon = math.ceil(np.max(lons))
min_lat = math.floor(np.min(lats)) - grid_line_sep
max_lat = math.ceil(np.max(lats))
imageMap(lons, lats, vals, imageWidth=image_width, vmin=vmin, vmax=vmax, logColors=log_colors,
meridians=[min_lon, max_lon, grid_line_sep],
parallels=[min_lat, max_lat, grid_line_sep], borderSlop=border_slop,
title=title, normalizeLongs=normalize_lons, **options)
def ts_plot(ts_json, t_name='time', val_name='mean',
title='', units=''):
t = np.array([ts[0][t_name] for ts in ts_json["data"]])
vals = np.array([ts[0][val_name] for ts in ts_json["data"]])
show_plot(t, vals, title=textwrap.fill(title,64),
y_label=textwrap.fill(units,32))
def plot_hovmoller(hm, time_key="time", val_key="mean",
coord_series_key="lats", coord_point_key="latitude",
coord_axis_vert=True, fill=-9999.,
hovfig=None, subplot=111, add_color_bar=True,
title=""):
times = [d[time_key] for d in hm]
times = mdates.epoch2num(times)
coords = [[d[coord_point_key] for d in hvals[coord_series_key]]
for hvals in hm]
coords_flat = np.array(sorted(list(set(itertools.chain(*coords)))))
coords_delta = np.median(coords_flat[1:] - coords_flat[:-1])
coords_min = np.amin(coords_flat)
coords_max = np.amax(coords_flat)
vals_fill = np.full((len(hm),len(coords_flat)), fill, dtype=np.float64)
t_ind = 0
for hvals in hm:
cur_vals = np.array([d[val_key] for d in hvals[coord_series_key]])
coords = np.array([d[coord_point_key] for d in hvals[coord_series_key]])
coords_inds = np.round((coords - coords_min) /
coords_delta).astype(int)
vals_fill[t_ind, coords_inds] = cur_vals
t_ind += 1
vals = np.ma.array(data=vals_fill, mask=vals_fill == fill)
extent = [np.min(times), np.max(times), coords_min, coords_max]
dtFmt = mdates.DateFormatter('%b %Y') # define the formatting
if hovfig is None:
fig = plt.figure(figsize=(16,6))
else:
fig = hovfig
ax = fig.add_subplot(subplot)
ax.set_title(title)
if coord_axis_vert:
vals = np.transpose(vals)
ax.xaxis.set_major_formatter(dtFmt)
ax.set_ylabel(coord_point_key)
plt.xticks(rotation=45)
else:
extent = [extent[2], extent[3], extent[0], extent[1]]
ax.yaxis.set_major_formatter(dtFmt)
ax.set_xlabel(coord_point_key)
cax = ax.imshow(vals, origin='lower', extent=extent)
ax.set_aspect('auto')
if add_color_bar:
fig.colorbar(cax, ticks=np.linspace(np.min(vals), np.max(vals), 7),
orientation='vertical')
return fig
def compute_ts_and_tam_no_plot(dataset, bbox, start_time, end_time, base_url="localhost",
seasonal_filter="false"):
url_params = 'ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}'.\
format(dataset, *bbox.bounds,
start_time.strftime(dt_format), end_time.strftime(dt_format))
ts_url = '{}/timeSeriesSpark?{}&seasonalFilter={}'.format(base_url, url_params,
seasonal_filter)
tam_url = '{}/timeAvgMapSpark?{}'.format(base_url, url_params)
# Display some information about the job
print(ts_url); print()
print(tam_url); print()
# Query SDAP to compute the time series
print("Computing time series...")
start = time.perf_counter()
ts_json = requests.get(ts_url, verify=False).json()
print("Area-averaged time series took {} seconds".format(time.perf_counter() - start))
print()
# Query SDAP to compute the time averaged map
print("Computing time averaged map...")
start = time.perf_counter()
tam_json = requests.get(tam_url, verify=False).json()
print("Time averaged map took {} seconds".format(time.perf_counter() - start))
return ts_json, tam_json
def compute_ts_and_tam(dataset, bbox, start_time, end_time, base_url="localhost",
seasonal_filter="false", title='', grid_line_sep=5,
units=None, log_colors=False, normalize_lons=False, **options):
ts_json, tam_json = compute_ts_and_tam_no_plot(dataset, bbox, start_time, end_time,
base_url=base_url,
seasonal_filter=seasonal_filter)
print()
print("Plot of area-average time series:")
ts_plot(ts_json, val_name='mean', title=title, units=units)
if seasonal_filter == "true":
print("Plot of time series of difference with climatology:")
ts_plot(ts_json, val_name='meanSeasonal',
title=title, units=units)
print()
# Query SDAP to compute the time averaged map
tam = tam_json["data"]
plot_map(tam, log_colors=log_colors, grid_line_sep=grid_line_sep, title=title,
normalize_lons=normalize_lons, **options)
def show_sdap_json(j, nh=20, nt=10):
out_str = pformat(j)
for line in out_str.splitlines()[:nh]:
print(line)
print("\t\t.\n"*3)
for line in out_str.splitlines()[-nt:]:
print(line)
print('Done with plotting setup.')
```
# Science Data Analytics Platform (SDAP)
SDAP (https://sdap.apache.org/) provides advanced analytics capabilities to support NASA's New Observing Strategies (NOS) and Analytic Collaborative Frameworks (ACF) thrusts. In this demonstration we use SDAP with oceanographic datasets relevant to the CEOS Ocean Variables Enabling Research and Applications for GEO (COVERAGE) initiative.
In this demonstration, two geographically distributed SDAP cloud computing deployments are used, one on Amazon Web Services (AWS, https://aws.amazon.com/) for analytics with datasets curated in the USA (e.g., from NASA or NOAA), and one on WEkEO (https://www.wekeo.eu/) for analytics with European datasets (e.g., from CMEMS). In this way we follow the strategy of performing the computations close to the data host providers.
SDAP provides web service endpoints for each analytic algorithm, and can be accessed in a web browser or from a variety of programming languages. This notebook demonstrates the Python API to access SDAP.
## Demonstration Setup
In the cell below, we specify the location of the SDAP deployments to use, a dataset to be used, the
bounding box for an area of interest, and a time range for analysis.
```
# Base URLs for the USA (AWS) and European (WEkEO) SDAP deployments.
base_url_us = "https://coverage.ceos.org/nexus"
base_url_eu = "https://coverage.wekeo.eu"
# Define bounding box and time period for analysis
min_lon = -77; max_lon = -70
min_lat = 35; max_lat = 42
bbox = box(min_lon, min_lat, max_lon, max_lat)
# Specify the SDAP name of the datasets
dataset_us = "MUR25-JPL-L4-GLOB-v4.2_analysed_sst"
dataset_eu = "METOFFICE-GLO-SST-L4-NRT-OBS-GMPE-V3_analysed_sst"
start_time = datetime(2018, 1, 1)
end_time = datetime(2018, 12, 31)
print("dataset_us: {}".format(dataset_us))
print("dataset_eu: {}".format(dataset_eu))
print("spatial region {}, and time range {} to {}.".
format(bbox, start_time, end_time))
plot_box(bbox)
```
# Cloud Analytics
## Data Inventory
We begin by querying the SDAP `/list` endpoint at each of our SDAP deployments to examine what data are available in each instantiation of SDAP.
```
def get_sdap_inv(base_url):
url = '{}/list'.format(base_url)
print("Web Service Endpoint:"); print(url);
res = requests.get(url, verify=False).json()
pprint(res)
print("Response from AWS SDAP:")
get_sdap_inv(base_url_us)
print()
print("Response from WEkEO SDAP:")
get_sdap_inv(base_url_eu)
```
## Area-Averaged Time Series
Next we will make a simple web service call to the SDAP `/timeSeriesSpark` endpoint. This can also be done in a web browser or in a variety of programming languages.
```
# Compute time series using the SDAP/NEXUS web/HTTP interface
#
# Construct the URL
url = '{}/timeSeriesSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}&seasonalFilter={}'.\
format(base_url_us, dataset_us, *bbox.bounds,
start_time.strftime(dt_format), end_time.strftime(dt_format),
"false")
# Display some information about the job
print(url); print()
# Query SDAP to compute the time averaged map
print("Waiting for response from SDAP...")
start = time.perf_counter()
ts_json = requests.get(url, verify=False).json()
print("Time series took {} seconds".format(time.perf_counter() - start))
```
### JSON response
The SDAP web service calls return the result in `JSON`, a standard web services data
interchange format. This makes it easy for another web service component to "consume" the SDAP output.
Let's view the JSON response. It is long, so we'll show just the first few time values.
```
show_sdap_json(ts_json, nh=33, nt=10)
```
### Plot the result
Let's check our time series result with a plot. An SDAP dataset can also be associated with its climatology (long-term average for a given time period like monthly or daily). If this is the case, we can apply a "seasonal filter" to compute the spatial average of the difference between the dataset and its climatology as a time series.
```
# Plot the result
print("Plot of area-average time series:")
ts_plot(ts_json, val_name='mean', title=dataset_us, units='Degrees Celsius')
```
## Time Averaged Map
Next we will issue an SDAP web service call to compute a time averaged map. While the time series algorithm used above averages spatially to produce a single value for each time stamp, the time average map averages over time to produce a single value at each grid cell location. While the time series produces a 1D result indexed by time, the time averaged map produces a 2D map indexed by latitude and longitude.
```
# Compute time-averaged map using the SDAP/NEXUS web/HTTP interface
#
# Construct the URL
url = '{}/timeAvgMapSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}'.\
format(base_url_us, dataset_us, *bbox.bounds,
start_time.strftime(dt_format), end_time.strftime(dt_format))
# Display some information about the job
print(url); print()
# Query SDAP to compute the time averaged map
print("Waiting for response from SDAP...")
start = time.perf_counter()
tam_json = requests.get(url, verify=False).json()
print("Time averaged map took {} seconds".format(time.perf_counter() - start))
```
### JSON response
The SDAP web service calls return the result in `JSON`, a standard web services data
interchange format. This makes it easy for another web service component to "consume" the SDAP output.
Let's view the JSON response. It is long, so we'll show just the first few grid cells.
```
show_sdap_json(tam_json, nh=13, nt=10)
```
### Extract the actual data and plot the result
The actual time averaged map data is readily accessible for plotting.
```
# Extract the actual output data
tam = tam_json["data"]
# Create a plot of the Time Averaged Map results
plot_map(tam, title=dataset_us+" (deg C)", grid_line_sep=2)
```
## Hovmoller Maps
Next we will issue an SDAP web service call to compute latitude-time and longitude-time Hovmoller maps and plot the results.
```
# Construct the URLs
url_lat = '{}/latitudeTimeHofMoellerSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}'.\
format(base_url_us, dataset_us, *bbox.bounds,
start_time.strftime(dt_format), end_time.strftime(dt_format))
url_lon = '{}/longitudeTimeHofMoellerSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}'.\
format(base_url_us, dataset_us, *bbox.bounds,
start_time.strftime(dt_format), end_time.strftime(dt_format))
# Query SDAP to compute the latitude-time Hovmoller map
print(url_lat); print()
print("Waiting for response from SDAP...")
start = time.perf_counter()
hm_lat_json = requests.get(url_lat, verify=False).json()
print("Latitude-time Hovmoller map took {} seconds".format(time.perf_counter() - start)); print()
# Query SDAP to compute the longitude-time Hovmoller map
print(url_lon); print()
print("Waiting for response from SDAP...")
start = time.perf_counter()
hm_lon_json = requests.get(url_lon, verify=False).json()
print("Longitude-time Hovmoller map took {} seconds".format(time.perf_counter() - start))
```
### JSON response
Let's view the JSON response. It is long, so we'll show just the first few grid cells.
```
# Show snippet of JSON response for latitude-time Hovmoller
show_sdap_json(hm_lat_json, nh=19, nt=10)
# Show snippet of JSON response for longitude-time Hovmoller
show_sdap_json(hm_lon_json, nh=19, nt=10)
```
### Extract the actual data and plot the results
The actual map data is readily accessible for plotting.
```
# Extract the actual output data
hm_lat = hm_lat_json["data"]
hm_lon = hm_lon_json["data"]
# Plot the Hovmoller maps
hovfig = plot_hovmoller(hm_lat, coord_series_key="lats", coord_point_key="latitude",
coord_axis_vert=True, subplot=121,
title="Sea Surface Temperature (deg C)")
hovfig = plot_hovmoller(hm_lon, coord_series_key="lons", coord_point_key="longitude",
coord_axis_vert=False, hovfig=hovfig, subplot=122,
title="Sea Surface Temperature (deg C)")
```
## Joint Analytics Across AWS and WEkEO SDAP Deployments
Next we can take advantage of the two SDAP deployments and conduct joint analytics across the two platforms.
### Compare two SST datasets, one from AWS SDAP and one from WEkEO SDAP
```
# Previous time series result was computed on AWS with
# dataset "MUR25-JPL-L4-GLOB-v4.2_analysed_sst"
ts_mur25_json = ts_json
# Let's compute a 2nd SST time series, this time computed on WEkEO with
# dataset "METOFFICE-GLO-SST-L4-NRT-OBS-GMPE-V3_analysed_sst"
#
dataset_eu_gmpe_sst = "METOFFICE-GLO-SST-L4-NRT-OBS-GMPE-V3_analysed_sst"
url = '{}/timeSeriesSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}&seasonalFilter={}'.\
format(base_url_eu, dataset_eu_gmpe_sst, *bbox.bounds,
start_time.strftime(dt_format), end_time.strftime(dt_format),
"false")
# Display some information about the job
print(url); print()
# Query SDAP to compute the time averaged map
print("Waiting for response from SDAP...")
start = time.perf_counter()
ts_gmpe_json = requests.get(url, verify=False).json()
print("Time series took {} seconds".format(time.perf_counter() - start))
# Plot the result
ts_plot_two(ts_mur25_json, ts_gmpe_json, dataset_us, dataset_eu_gmpe_sst,
"Degrees Celsius", "Degrees Celsius",
title="SST Comparison", val_name="mean")
scatter_plot(ts_mur25_json, ts_gmpe_json, title="SST Comparison",
xlabel=dataset_us, ylabel=dataset_eu_gmpe_sst)
```
### Compare SST from AWS SDAP and ADT from WEkEO SDAP
```
dataset_eu_cmems_adt = "CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047_adt"
url = '{}/timeSeriesSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}&seasonalFilter={}'.\
format(base_url_eu, dataset_eu_cmems_adt, *bbox.bounds,
start_time.strftime(dt_format), end_time.strftime(dt_format),
"false")
# Display some information about the job
print(url); print()
# Query SDAP to compute the time averaged map
print("Waiting for response from SDAP...")
start = time.perf_counter()
ts_cmems_adt_json = requests.get(url, verify=False).json()
print("Time series took {} seconds".format(time.perf_counter() - start))
# Plot the result
ts_plot_two(ts_mur25_json, ts_cmems_adt_json, dataset_us, dataset_eu_cmems_adt,
"Degrees Celsius", "Meters Above Geoid",
title="SST vs ADT", val_name="mean")
```
# More SDAP Analytics
In the rest of this notebook we use a helper function defined in the first notebook cell above to use SDAP to compute time series and time averaged map for a variety of other relevant datasets. In these results, SDAP is used in the same way as we demonstrated above.
## Absolute Dynamic Topography (ADT) from CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047
```
dataset = "CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047_adt"
compute_ts_and_tam(dataset,
bbox, start_time, end_time, base_url=base_url_eu,
units="meters", title=dataset, grid_line_sep=2)
```
## Sea Level Anomaly (SLA) from CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047
```
dataset = "CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047_sla"
compute_ts_and_tam(dataset,
bbox, start_time, end_time, base_url=base_url_eu,
units="meters", title=dataset, grid_line_sep=2)
```
## Sea Surface Salinity (SSS) from Multi-Mission Optimally Interpolated Sea Surface Salinity 7-Day Global Dataset V1
```
start_time_oisss7d = datetime(2011, 8, 28)
end_time_oisss7d = datetime(2021, 9, 8)
dataset = "OISSS_L4_multimission_global_7d_v1.0_sss"
compute_ts_and_tam(dataset,
bbox, start_time_oisss7d, end_time_oisss7d, base_url=base_url_us,
units="1e-3", title=dataset, grid_line_sep=2)
```
## Sea Surface Salinity (SSS) Uncertainty from Multi-Mission Optimally Interpolated Sea Surface Salinity 7-Day Global Dataset V1
```
dataset = "OISSS_L4_multimission_global_7d_v1.0_sss_uncertainty"
start_time_oisss7d = datetime(2015, 7, 1)
end_time_oisss7d = datetime(2021, 9, 8)
compute_ts_and_tam(dataset,
bbox, start_time_oisss7d, end_time_oisss7d, base_url=base_url_us,
units="1e-3", title=dataset, grid_line_sep=2)
```
## Sea Surface Salinity (SSS) from Multi-Mission Optimally Interpolated Sea Surface Salinity Monthly Global Dataset V1
```
start_time_oisssmo = datetime(2011, 9, 16)
end_time_oisssmo = datetime(2021, 8, 16)
dataset = "OISSS_L4_multimission_global_monthly_v1.0_sss"
compute_ts_and_tam(dataset,
bbox, start_time_oisssmo, end_time_oisssmo, base_url=base_url_us,
units="1e-3", title=dataset, grid_line_sep=2)
```
## Sea Surface Salinity (SSS) Anomaly from Multi-Mission Optimally Interpolated Sea Surface Salinity Monthly Global Dataset V1
```
dataset = "OISSS_L4_multimission_global_monthly_v1.0_sss_anomaly"
compute_ts_and_tam(dataset,
bbox, start_time_oisssmo, end_time_oisssmo, base_url=base_url_us,
units="1e-3", title=dataset, grid_line_sep=2)
```
## Sea Surface Temperature (SST) from MUR25-JPL-L4-GLOB-v4.2
```
dataset = "MUR25-JPL-L4-GLOB-v4.2_analysed_sst"
compute_ts_and_tam(dataset,
bbox, start_time, end_time, base_url=base_url_us,
units="degrees celsius", title=dataset, grid_line_sep=2)
```
## Chlorophyll-A from MODIS_Aqua_L3m_8D
```
# Define dataset and bounding box for analysis
dataset = "MODIS_Aqua_L3m_8D_chlor_a"
compute_ts_and_tam(dataset,
bbox, start_time, end_time, base_url=base_url_us,
seasonal_filter="true",
units="milligram m-3", title=dataset,
log_colors=True, grid_line_sep=2)
```
## Chlorophyll-A from JPL-MRVA25-CHL-L4-GLOB-v3.0_CHLA
```
dataset = "JPL-MRVA25-CHL-L4-GLOB-v3.0_CHLA_analysis"
compute_ts_and_tam(dataset,
bbox, start_time, end_time, base_url=base_url_us,
units="milligram m-3", title=dataset, log_colors=True,
grid_line_sep=2)
```
## Chlorophyll-A from CMEMS_OCEANCOLOUR_GLO_CHL_L4_REP_OBSERVATIONS_009_082
```
dataset = "CMEMS_OCEANCOLOUR_GLO_CHL_L4_REP_OBSERVATIONS_009_082_CHL"
compute_ts_and_tam(dataset,
bbox, start_time, end_time, base_url=base_url_eu,
units="milligram m-3", title=dataset, log_colors=True,
grid_line_sep=2)
```
| github_jupyter |
# Introduction
You have learned how to select relevant data from `DataFrame` and `Series` objects. Plucking the right data out of our data representation is critical to getting work done.
However, the data does not always come in the format we want. Sometimes we have to do some more work ourselves to reformat it for our desired task.
The remainder of this tutorial will cover different operations we can apply to our data to get the input "just right". We'll start off in this section by looking at the most commonly looked built-in reshaping operations. Along the way we'll cover data `dtypes`, a concept essential to working with `pandas` effectively.
# Relevant Resources
* **[Summary functions and maps](https://www.kaggle.com/residentmario/summary-functions-and-maps-reference)**
* [Official pandas cheat sheet](https://github.com/pandas-dev/pandas/blob/master/doc/cheatsheet/Pandas_Cheat_Sheet.pdf)
# Set Up
Run the code cell below to load your data and the necessary utility functions.
```
import pandas as pd
pd.set_option('max_rows', 5)
import numpy as np
from learntools.advanced_pandas.summary_functions_maps import *
reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)
```
Look at an overview of your data by running the line below:
# Checking Answers
**Check your answers in each exercise using the `check_qN` function** (replacing `N` with the number of the exercise). For example here's how you would check an incorrect answer to exercise 1:
```
check_q1(pd.DataFrame())
```
If you get stuck, **use the `answer_qN` function to see the code with the correct answer.**
For the first set of questions, running the `check_qN` on the correct answer returns `True`.
For the second set of questions, using this function to check a correct answer will present an informative graph!
## Exercises
Look at your data by running the cell below:
```
reviews.head()
```
**Exercise 1**: What is the median of the `points` column?
```
reviews.describe()
# Your code here
median = reviews.points.median()
median
# check_q1(pd.DataFrame())
```
**Exercise 2**: What countries are represented in the dataset?
```
# Your code here
reviews.country.unique()
```
**Exercise 3**: What countries appear in the dataset most often?
```
# Your code here
reviews.country.mode()
check_q3(pd.DataFrame())
```
**Exercise 4**: Remap the `price` column by subtracting the median price. Use the `Series.map` method.
```
# Your code here
# reviews.price.map()
j = map(lambda x :x - median,reviews.price)
j = list(j)
```
**Exercise 5**: I"m an economical wine buyer. Which wine in is the "best bargain", e.g., which wine has the highest points-to-price ratio in the dataset?
Hint: use a map and the [`argmax` function](http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.Series.argmax.html).
```
reviews.index.values
# Your code here
j = reviews.apply(lambda x:x.points - x.price,axis = 'columns')
j.head()
```
Now it's time for some visual exercises. In the questions that follow, generate the data that we will need to have in order to produce the plots that follow. These exercises will use skills from this workbook as well as from previous ones. They look a lot like questions you will actually be asking when working with your own data!
<!--
**Exercise 6**: Sometimes the `province` and `region_1` provided in the dataset is the same value. Create a `Series` whose values counts how many times this occurs (`True`) and doesn't occur (`False`).
-->
**Exercise 6**: Is a wine more likely to be "tropical" or "fruity"? Create a `Series` counting how many times each of these two words appears in the `description` column in the dataset.
Hint: use a map to check each description for the string `tropical`, then count up the number of times this is `True`. Repeat this for `fruity`. Create a `Series` combining the two values at the end.
```
reviews["description"][2]
# Your code here
def func(ser):
count = {'tropical': 0,'fruity': 0}
if 'tropical' in ser:
count["tropical"] += 1
elif 'fruity' in ser:
count["fruity"] += 1
# if(count['tropical'] > count['fruity']):
# return count['tropical']
# elif(count['tropical'] < count['fruity']):
# return count['fruity']
# else:
return (count['tropical'],count['fruity'])
reviews["type"] = list(map(func,reviews.description))
reviews["type"]
reviews
```
**Exercise 7**: What combination of countries and varieties are most common?
Create a `Series` whose index consists of strings of the form `"<Country> - <Wine Variety>"`. For example, a pinot noir produced in the US should map to `"US - Pinot Noir"`. The values should be counts of how many times the given wine appears in the dataset. Drop any reviews with incomplete `country` or `variety` data.
Hint: you can do this in three steps. First, generate a `DataFrame` whose `country` and `variety` columns are non-null. Then use a map to create a series whose entries are a `str` concatenation of those two columns. Finally, generate a `Series` counting how many times each label appears in the dataset.
```
# Your code here
dataframe = reviews[(reviews.country.notnull()) & (reviews.variety.notnull())]
dataframe["country - variety"] = dataframe.apply(lambda x:x["country"] +" " + x["variety"],axis = 'columns')
dataframe_new = dataframe.iloc[0:5]
dataframe_new["country - variety"].value_counts()
type(dataframe["country - variety"].value_counts())
data = pd.Series(data = dataframe["country - variety"].value_counts().values ,index = dataframe["country - variety"].unique())
data.head()
```
# Keep Going
**[Continue to grouping and sorting](https://www.kaggle.com/kernels/fork/598715).**
| github_jupyter |
# Plan
1. Read through code (~5 minutes)
2. Get into groups and discuss code (~2 minutes)
3. Ask questions on the sheet (~5 minutes)
4. Work on "Questions to answer" (~10 minutes)
5. Work on "Things to explore" (~10 minutes)
6. Work on the "Challenge" (~20 minutes)
7. Work on "What's next?"
Getting started:
- I recommend cloning this repository (or pulling changes if you already have it cloned)
- Starting jupyter
- Then duplicating this file so that you can alter it without confusing `git`
Some tools to use:
- You can create a cell above the current cell by typing "esc" then "a"
- You can create a cell below the current cell by typing "esc" then "b"
- You should copy code into newly created cells, alter it, print out the results, etc.
- You can do this for single lines or you can copy, for example, the `for batch, (X, Y) in enumerate(dataloader):` loop out of `train_one_epoch` and make minor changes so that it works outside of the function
- I will frequently put a break a the end of the for-loop so that it only iterates one time (so that I don't have to wait for every iteration)
```
from contextlib import contextmanager
from timeit import default_timer as timer
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, SubsetRandomSampler
from torchvision.datasets import MNIST
from torchvision.transforms import Compose, Normalize, ToTensor
@contextmanager
def stopwatch(label: str):
start = timer()
try:
yield
finally:
print(f"{label}: {timer() - start:6.3f}s")
def get_mnist_data_loaders(path, batch_size, valid_batch_size):
# MNIST specific transforms
mnist_xforms = Compose([ToTensor(), Normalize((0.1307,), (0.3081,))])
# Training data loader
train_dataset = MNIST(root=path, train=True, download=True, transform=mnist_xforms)
tbs = len(train_dataset) if batch_size == 0 else batch_size
train_loader = DataLoader(train_dataset, batch_size=tbs, shuffle=True)
# Validation data loader
valid_dataset = MNIST(root=path, train=False, download=True, transform=mnist_xforms)
vbs = len(valid_dataset) if valid_batch_size == 0 else valid_batch_size
valid_loader = DataLoader(valid_dataset, batch_size=vbs, shuffle=True)
return train_loader, valid_loader
class NeuralNetwork(nn.Module):
def __init__(self, layer_sizes):
super(NeuralNetwork, self).__init__()
first_layer = nn.Flatten()
middle_layers = [
# nn.Sequential(nn.Linear(nlminus1, nl), nn.Tanh())
nn.Sequential(nn.Linear(nlminus1, nl), nn.ReLU())
# nn.Sequential(nn.Linear(nlminus1, nl), nn.Sigmoid())
for nl, nlminus1 in zip(layer_sizes[1:-1], layer_sizes)
]
last_layer = nn.Linear(layer_sizes[-2], layer_sizes[-1])
all_layers = [first_layer] + middle_layers + [last_layer]
self.layers = nn.Sequential(*all_layers)
def forward(self, X):
return self.layers(X)
def train_one_epoch(dataloader, model, loss_fn, optimizer, device):
model.train()
num_batches = len(train_loader)
batches_to_print = [0, num_batches // 3, 2 * num_batches // 3, num_batches - 1]
for batch, (X, Y) in enumerate(dataloader):
X, Y = X.to(device), Y.to(device)
output = model(X)
loss = loss_fn(output, Y)
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch in batches_to_print:
print(f"Batch {batch+1:>5} of {num_batches}: loss={loss.item():>6.3f}")
def compute_validation_accuracy(dataloader, model, loss_fn, device):
model.eval()
N = len(dataloader.dataset)
num_batches = len(dataloader)
valid_loss, num_correct = 0, 0
with torch.no_grad():
for X, Y in dataloader:
X, Y = X.to(device), Y.to(device)
output = model(X)
valid_loss += loss_fn(output, Y).item()
num_correct += (output.argmax(1) == Y).type(torch.float).sum().item()
valid_loss /= num_batches
valid_accuracy = num_correct / N
print(f"Validation accuracy : {(100*valid_accuracy):>6.3f}%")
print(f"Validation loss : {valid_loss:>6.3f}")
```
# Configuration
```
# Configuration parameters
data_path = "../data"
seed = 0
torch.manual_seed(seed)
# Hyperparameters
batch_size = 1024
valid_batch_size = 0
learning_rate = 1e-2
num_epochs = 50
# Training device
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using '{device}' device.")
```
# Data
```
# Get data loaders
train_loader, valid_loader = get_mnist_data_loaders(
data_path, batch_size, valid_batch_size
)
```
# Model
```
# Create neural network model
nx = train_loader.dataset.data.shape[1:].numel()
ny = len(train_loader.dataset.classes)
layer_sizes = (nx, 512, 50, ny)
model = NeuralNetwork(layer_sizes).to(device)
print(model)
```
# Training Loop
```
# Training utilities
loss_fn = nn.CrossEntropyLoss()
# optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
with stopwatch(f"\nDone! Total time for {num_epochs} epochs"):
for epoch in range(num_epochs):
print(f"\nEpoch {epoch+1}\n-------------------------------")
with stopwatch("Epoch time "):
train_one_epoch(train_loader, model, loss_fn, optimizer, device)
compute_validation_accuracy(valid_loader, model, loss_fn, device)
```
# Questions to answer
(Try to answer these in your group prior to running or altering any code.)
- What is the shape of `output` in the function `train_one_epoch`?
- Shape is `[1024, 10]` (`[batch_size , num_output_features]`)
- What values would you expect to see in `output`?
- Rows represent predictions, columns represent possible outputs, data would be floats representing predictions where highest in a row represents the prediction by the network
- What is the shape of `Y` in the function `train_one_epoch`?
- Shape is `[1024, 1]` (`[batch_size , 1]`)
- Describe each part of `(output.argmax(1) == Y).type(torch.float).sum().item()`
- `output.argmax(1)` selects the max value in the first (zero-indexed) dimension of the `output` tensor. Analagous to selecting prediction!
- `... == Y` compares predictions to valid data from `Y`, returns `[1024, 1]` tensor of bools representing correct/incorrect prediction
- `.type(torch.float)` converts `False` to 0 and `True` to 1 in the tensor of bools
- `.sum().item()` calculates the number of correctly predicted inputs. Can be divided by 1024 for accuracy!
- What happens when you rerun the training cell for additional epoch (without rerunning any other cells)?
- Picks up training where the last epoch left off!
- What happens to if force device to be `"cpu"`?
- Slows down on the server!
# Things to explore
- change the hidden layer activation functions to sigmoid
- change the hidden layer activation functions to [something else](https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity)
- change the optimizer from `SGD` to `Adam` and try to train the network again
You can also try these if you feel like you have plenty of time. You can also choose to come back to them after working on the Challenge below
- (optional) try adding a [dropout](https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html#torch.nn.Dropout) layer somewhere in your network
- (optional) try switching the dataset to either [KMNIST](https://pytorch.org/vision/0.8/datasets.html#kmnist) or [FashionMNIST](https://pytorch.org/vision/0.8/datasets.html#fashion-mnist)
# Challenge
Train a model and get the highest accuracy possible by adjusting hyperparameters and the model architecture (i.e., the number of layers, the number of neurons per layer, etc.).
# What's next?
Move the inference cells below to a new file, and then try to make them work.
# Inference
```
model_filename = "l14-model.pth"
torch.save(model.state_dict(), model_filename)
print("Saved PyTorch Model State to", model_filename)
model = NeuralNetwork(layer_sizes)
model.load_state_dict(torch.load(model_filename))
model.eval()
# Index of example
i = 0
# Example input and output
x, y = valid_loader.dataset[i][0], valid_loader.dataset[i][1]
with torch.no_grad():
output = model(x)
prediction = output[0].argmax(0)
print(f"Prediction : {prediction}")
print(f"Target : {y}")
```
| github_jupyter |
```
!pip install campy
"""
File: my_drawing
Name: Kai Cheng
----------------------
TODO:
"""
from campy.graphics.gobjects import GOval, GRect, GLabel, GArc
from campy.graphics.gwindow import GWindow
def main():
"""
This program is to create a drawing of Pokemon first generation.
Last Saturday I went to Adidas with Alan, and spotted their new Pokemon pixel t-shirt.
I decided to create a drawing of Pokemon, because I'm poor and have no money to purchase the t-shirt.
Therefore, I like to paint a drawing which is full of my favorite cartoon in my childhood.
"""
window = GWindow(width=700, height=400, title="Pokemon")
# Create a white background.
cover = GRect(700, 400)
cover.color = "white"
cover.fill_color = "white"
cover.filled = True
window.add(cover)
# Draw pixels to create Bulbasaur.
# Column 1
b = GRect(5, 5, x=150, y=220)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=150, y=225)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=150, y=230)
b.filled = True
b.fill_color = "black"
window.add(b)
b4 = GRect(5, 5, x=150, y=235)
b4.filled = True
b4.fill_color = "lightgreen"
window.add(b4)
b4 = GRect(5, 5, x=150, y=240)
b4.filled = True
b4.fill_color = "limegreen"
window.add(b4)
bb = GRect(5, 5, x=150, y=245)
bb.filled = True
bb.fill_color = "black"
window.add(bb)
# Column 2
b = GRect(5, 5, x=155, y=205)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=155, y=210)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=155, y=215)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=155, y=220)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=155, y=225)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=155, y=230)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=155, y=235)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=155, y=240)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=155, y=245)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=155, y=250)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 3
b = GRect(5, 5, x=160, y=200)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=160, y=205)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=160, y=210)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=160, y=215)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=160, y=220)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=160, y=225)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=160, y=230)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=160, y=235)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=160, y=240)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=160, y=245)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=160, y=250)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 4
b = GRect(5, 5, x=165, y=205)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=165, y=210)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=165, y=215)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=165, y=220)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=165, y=225)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=165, y=230)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=165, y=235)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=165, y=240)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=165, y=245)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=165, y=250)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=165, y=255)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 5
b = GRect(5, 5, x=170, y=205)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=170, y=210)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=170, y=215)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=170, y=220)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=170, y=225)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=170, y=230)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=170, y=235)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=170, y=240)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=170, y=245)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=170, y=250)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=170, y=255)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 6
b = GRect(5, 5, x=175, y=200)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=175, y=205)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=175, y=210)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=175, y=215)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=175, y=220)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=175, y=225)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=175, y=230)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=175, y=235)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=175, y=240)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=175, y=245)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=175, y=250)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=175, y=255)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 7
b = GRect(5, 5, x=180, y=195)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=180, y=200)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=180, y=205)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=180, y=210)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=180, y=215)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=180, y=220)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=180, y=225)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=180, y=230)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=180, y=235)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=180, y=240)
b.filled = True
b.fill_color = "tomato"
window.add(b)
b = GRect(5, 5, x=180, y=245)
b.filled = True
b.fill_color = "tomato"
window.add(b)
b = GRect(5, 5, x=180, y=250)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=180, y=255)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 8
b = GRect(5, 5, x=185, y=195)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=185, y=200)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=185, y=205)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=185, y=210)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=185, y=215)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=185, y=220)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=185, y=225)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=185, y=230)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=185, y=235)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=185, y=240)
b.filled = True
b.fill_color = "white"
window.add(b)
b = GRect(5, 5, x=185, y=245)
b.filled = True
b.fill_color = "white"
window.add(b)
b = GRect(5, 5, x=185, y=250)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=185, y=255)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 9
b = GRect(5, 5, x=190, y=190)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=190, y=195)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=190, y=200)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=190, y=205)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=190, y=210)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=190, y=215)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=190, y=220)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=190, y=225)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=190, y=230)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=190, y=235)
b.filled = True
b.fill_color = "lightgreen"
window.add(b)
b = GRect(5, 5, x=190, y=240)
b.filled = True
b.fill_color = "white"
window.add(b)
b = GRect(5, 5, x=190, y=245)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=190, y=250)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=190, y=255)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 10
b = GRect(5, 5, x=195, y=190)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=195, y=195)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=195, y=200)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=195, y=205)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=195, y=210)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=195, y=215)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=195, y=220)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=195, y=225)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=195, y=230)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=195, y=235)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=195, y=240)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=195, y=245)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=195, y=250)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=195, y=255)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 11
b = GRect(5, 5, x=200, y=185)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=200, y=190)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=200, y=195)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=200, y=200)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=200, y=205)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=200, y=210)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=200, y=215)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=200, y=220)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=200, y=225)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=200, y=230)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=200, y=235)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=200, y=240)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=200, y=245)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=200, y=250)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=200, y=255)
b.filled = True
b.fill_color = "white"
window.add(b)
b = GRect(5, 5, x=200, y=260)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 12
b = GRect(5, 5, x=205, y=180)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=205, y=185)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=205, y=190)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=205, y=195)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=205, y=200)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=205, y=205)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=205, y=210)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=205, y=215)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=205, y=220)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=205, y=225)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=205, y=230)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=205, y=235)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=205, y=240)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=205, y=245)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=205, y=250)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=205, y=255)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=205, y=260)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 13
b = GRect(5, 5, x=210, y=180)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=210, y=185)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=210, y=190)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=210, y=195)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=210, y=200)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=210, y=205)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=210, y=210)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=210, y=215)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=210, y=220)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=210, y=225)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=210, y=230)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=210, y=235)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=210, y=240)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=210, y=245)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=210, y=250)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=210, y=255)
b.filled = True
b.fill_color = "white"
window.add(b)
b = GRect(5, 5, x=210, y=260)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 14'
b = GRect(5, 5, x=215, y=180)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=215, y=185)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=215, y=190)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=215, y=195)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=215, y=200)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=215, y=205)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=215, y=210)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=215, y=215)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=215, y=220)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=215, y=225)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=215, y=230)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=215, y=235)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=215, y=240)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=215, y=245)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=215, y=250)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=215, y=255)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 15
b = GRect(5, 5, x=220, y=185)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=220, y=190)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=220, y=195)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=220, y=200)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=220, y=205)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=220, y=210)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=220, y=215)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=220, y=220)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=220, y=225)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=220, y=230)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=220, y=235)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=220, y=240)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 16
b = GRect(5, 5, x=225, y=195)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=225, y=200)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=225, y=205)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=225, y=210)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=225, y=215)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=225, y=220)
b.filled = True
b.fill_color = "green"
window.add(b)
b = GRect(5, 5, x=225, y=225)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=225, y=230)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=225, y=235)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=225, y=240)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 17
b = GRect(5, 5, x=230, y=195)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=230, y=200)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=230, y=205)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=230, y=210)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=230, y=215)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=230, y=220)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=230, y=225)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=230, y=230)
b.filled = True
b.fill_color = "limegreen"
window.add(b)
b = GRect(5, 5, x=230, y=235)
b.filled = True
b.fill_color = "white"
window.add(b)
b = GRect(5, 5, x=230, y=240)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 18
b = GRect(5, 5, x=235, y=200)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=235, y=205)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=235, y=210)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=235, y=215)
b.filled = True
b.fill_color = "lawngreen"
window.add(b)
b = GRect(5, 5, x=235, y=220)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=235, y=225)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=235, y=230)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=235, y=235)
b.filled = True
b.fill_color = "black"
window.add(b)
# Column 19
b = GRect(5, 5, x=240, y=205)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=240, y=210)
b.filled = True
b.fill_color = "black"
window.add(b)
b = GRect(5, 5, x=240, y=215)
b.filled = True
b.fill_color = "black"
window.add(b)
# # Draw pixels to create Charmander.
# Column 1
"""
c = GRect(5, 5, x=300, y=260)
c.filled = True
c.fill_color = "orange"
window.add(c)
"""
c = GRect(5, 5, x=300, y=200)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=300, y=205)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=300, y=210)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 2
c = GRect(5, 5, x=305, y=195)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=305, y=200)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=305, y=205)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=305, y=210)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=305, y=215)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 3
c = GRect(5, 5, x=310, y=185)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=310, y=190)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=310, y=195)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=310, y=200)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=310, y=205)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=310, y=210)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=310, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=310, y=220)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 4
c = GRect(5, 5, x=315, y=180)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=315, y=185)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=315, y=190)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=315, y=195)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=315, y=200)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=315, y=205)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=315, y=210)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=315, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=315, y=220)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 5
c = GRect(5, 5, x=320, y=175)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=320, y=180)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=320, y=185)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=320, y=190)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=320, y=195)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=320, y=200)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=320, y=205)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=320, y=210)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=320, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=320, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=320, y=225)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=320, y=240)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 6
c = GRect(5, 5, x=325, y=175)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=325, y=180)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=325, y=185)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=325, y=190)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=325, y=195)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=325, y=200)
c.filled = True
c.fill_color = "white"
window.add(c)
c = GRect(5, 5, x=325, y=205)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=325, y=210)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=325, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=325, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=325, y=225)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=325, y=230)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=325, y=235)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=325, y=240)
c.filled = True
c.fill_color = "white"
window.add(c)
c = GRect(5, 5, x=325, y=245)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 7
c = GRect(5, 5, x=330, y=175)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=330, y=180)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=330, y=185)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=330, y=190)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=330, y=195)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=330, y=200)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=330, y=205)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=330, y=210)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=330, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=330, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=330, y=225)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=330, y=230)
c.filled = True
c.fill_color = "honeydew"
window.add(c)
c = GRect(5, 5, x=330, y=235)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=330, y=240)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=330, y=245)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 8
c = GRect(5, 5, x=335, y=175)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=335, y=180)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=185)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=190)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=195)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=200)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=205)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=210)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=225)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=335, y=230)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=335, y=235)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=335, y=240)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=335, y=245)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 9
c = GRect(5, 5, x=340, y=180)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=340, y=185)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=340, y=190)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=340, y=195)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=340, y=200)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=340, y=205)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=340, y=210)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=340, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=340, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=340, y=225)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=340, y=230)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=340, y=235)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=340, y=240)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=340, y=245)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=340, y=250)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 10
c = GRect(5, 5, x=345, y=185)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=345, y=190)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=345, y=195)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=345, y=200)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=345, y=205)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=345, y=210)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=345, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=345, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=345, y=225)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=345, y=230)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=345, y=235)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=345, y=240)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=345, y=245)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=345, y=250)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=345, y=255)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 11
c = GRect(5, 5, x=350, y=195)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=350, y=200)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=350, y=205)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=350, y=210)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=350, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=350, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=350, y=225)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=350, y=230)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=350, y=235)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=350, y=240)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=350, y=245)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=350, y=250)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=350, y=255)
c.filled = True
c.fill_color = "white"
window.add(c)
c = GRect(5, 5, x=350, y=260)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 12
c = GRect(5, 5, x=355, y=205)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=355, y=210)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=355, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=355, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=355, y=225)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=355, y=230)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=355, y=235)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=355, y=240)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=355, y=245)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=355, y=250)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=355, y=255)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=355, y=260)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 13
c = GRect(5, 5, x=360, y=215)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=360, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=360, y=225)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=360, y=230)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=360, y=235)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=360, y=240)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=360, y=245)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=360, y=250)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=360, y=255)
c.filled = True
c.fill_color = "white"
window.add(c)
c = GRect(5, 5, x=360, y=260)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 14
c = GRect(5, 5, x=365, y=220)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=365, y=225)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=365, y=230)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=365, y=235)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=365, y=240)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=365, y=245)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=365, y=250)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=365, y=255)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 15
c = GRect(5, 5, x=370, y=220)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=370, y=225)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=370, y=230)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=370, y=235)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=370, y=240)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=370, y=245)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 16
c = GRect(5, 5, x=375, y=195)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=375, y=200)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=375, y=215)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=375, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=375, y=225)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=375, y=230)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=375, y=235)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=375, y=240)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 17
c = GRect(5, 5, x=380, y=180)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=380, y=185)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=380, y=190)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=380, y=195)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=380, y=200)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=380, y=205)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=380, y=210)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=380, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=380, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=380, y=225)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=380, y=230)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=380, y=235)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 18
c = GRect(5, 5, x=385, y=175)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=385, y=180)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=385, y=185)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=385, y=190)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=385, y=195)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=385, y=200)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=385, y=205)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=385, y=210)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=385, y=215)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=385, y=220)
c.filled = True
c.fill_color = "orange"
window.add(c)
c = GRect(5, 5, x=385, y=225)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=385, y=230)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 19
c = GRect(5, 5, x=390, y=180)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=390, y=185)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=390, y=190)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=390, y=195)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=390, y=200)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=390, y=205)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=390, y=210)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=390, y=215)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=390, y=220)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 20
c = GRect(5, 5, x=395, y=185)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=395, y=190)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=395, y=195)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=395, y=200)
c.filled = True
c.fill_color = "yellow"
window.add(c)
c = GRect(5, 5, x=395, y=205)
c.filled = True
c.fill_color = "tomato"
window.add(c)
c = GRect(5, 5, x=395, y=210)
c.filled = True
c.fill_color = "black"
window.add(c)
# Column 21
c = GRect(5, 5, x=400, y=195)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=400, y=200)
c.filled = True
c.fill_color = "black"
window.add(c)
c = GRect(5, 5, x=400, y=205)
c.filled = True
c.fill_color = "black"
window.add(c)
# Draw pixels to create Squirtle.
# Column 1
s = GRect(5, 5, x=460, y=200)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=460, y=205)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=460, y=210)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 2
s = GRect(5, 5, x=465, y=190)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=465, y=195)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=465, y=200)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=465, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=465, y=210)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=465, y=215)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 3
s = GRect(5, 5, x=470, y=185)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=470, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=470, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=470, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=470, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=470, y=210)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=470, y=215)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=470, y=220)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=470, y=225)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 4
s = GRect(5, 5, x=475, y=180)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=475, y=185)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=475, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=475, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=475, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=475, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=475, y=210)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=475, y=215)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=475, y=220)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=475, y=225)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=475, y=230)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 5
s = GRect(5, 5, x=480, y=180)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=480, y=185)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=480, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=480, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=480, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=480, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=480, y=210)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=480, y=215)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=480, y=220)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=480, y=225)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=480, y=230)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=480, y=240)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 6
s = GRect(5, 5, x=485, y=180)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=485, y=185)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=485, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=485, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=485, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=485, y=205)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=485, y=210)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=485, y=215)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=485, y=220)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=485, y=225)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=485, y=230)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=485, y=235)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=485, y=240)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=485, y=245)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 7
s = GRect(5, 5, x=490, y=180)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=490, y=185)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=490, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=490, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=490, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=490, y=205)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=490, y=210)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=490, y=215)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=490, y=220)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=490, y=225)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=490, y=230)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=490, y=235)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=490, y=240)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=490, y=245)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 8
s = GRect(5, 5, x=495, y=185)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=495, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=495, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=495, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=495, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=495, y=210)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=495, y=215)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=495, y=220)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=495, y=225)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=495, y=230)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=495, y=235)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=495, y=240)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=495, y=245)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 9
s = GRect(5, 5, x=500, y=185)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=500, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=500, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=500, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=500, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=500, y=210)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=500, y=215)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=500, y=220)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=500, y=225)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=500, y=230)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=500, y=235)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=500, y=240)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=500, y=245)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=500, y=250)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 10
s = GRect(5, 5, x=505, y=190)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=505, y=195)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=505, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=505, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=505, y=210)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=505, y=215)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=505, y=220)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=505, y=225)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=505, y=230)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=505, y=235)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=505, y=240)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=505, y=245)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=505, y=250)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=505, y=255)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 11
s = GRect(5, 5, x=510, y=190)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=510, y=195)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=510, y=200)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=510, y=205)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=510, y=210)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=510, y=215)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=510, y=220)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=510, y=225)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=510, y=230)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=510, y=235)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=510, y=240)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=510, y=245)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=510, y=250)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=510, y=255)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=510, y=260)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 12
s = GRect(5, 5, x=515, y=195)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=515, y=200)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=515, y=205)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=515, y=210)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=515, y=215)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=515, y=220)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=515, y=225)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=515, y=230)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=515, y=235)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=515, y=240)
s.filled = True
s.fill_color = "#F0E68C"
window.add(s)
s = GRect(5, 5, x=515, y=245)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=515, y=250)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=515, y=255)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=515, y=260)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 13
s = GRect(5, 5, x=520, y=195)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=520, y=200)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=520, y=205)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=520, y=210)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=520, y=215)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=520, y=220)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=520, y=225)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=520, y=230)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=520, y=235)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=520, y=240)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=520, y=245)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=520, y=250)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=520, y=255)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=520, y=260)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 14
s = GRect(5, 5, x=525, y=200)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=525, y=205)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=525, y=210)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=525, y=215)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=525, y=220)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=525, y=225)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=525, y=230)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=525, y=235)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=525, y=240)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=525, y=245)
s.filled = True
s.fill_color = "white"
window.add(s)
s = GRect(5, 5, x=525, y=250)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=525, y=255)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 15
s = GRect(5, 5, x=530, y=190)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=530, y=195)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=530, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=530, y=205)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=530, y=210)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=530, y=215)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=530, y=220)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=530, y=225)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=530, y=230)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=530, y=235)
s.filled = True
s.fill_color = "peru"
window.add(s)
s = GRect(5, 5, x=530, y=240)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=530, y=245)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 16
s = GRect(5, 5, x=535, y=185)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=535, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=535, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=535, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=535, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=535, y=210)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=535, y=215)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=535, y=220)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=535, y=225)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=535, y=230)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=535, y=235)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 16
s = GRect(5, 5, x=540, y=180)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=540, y=185)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=540, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=540, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=540, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=540, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=540, y=210)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=540, y=215)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 17
s = GRect(5, 5, x=545, y=180)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=545, y=185)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=545, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=545, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=545, y=200)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=545, y=205)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=545, y=210)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 18
s = GRect(5, 5, x=550, y=180)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=550, y=185)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=550, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=550, y=195)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=550, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=550, y=205)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=550, y=210)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 18
s = GRect(5, 5, x=555, y=185)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=555, y=190)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=555, y=195)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=555, y=200)
s.filled = True
s.fill_color = "sky blue"
window.add(s)
s = GRect(5, 5, x=555, y=205)
s.filled = True
s.fill_color = "black"
window.add(s)
# Column 19
s = GRect(5, 5, x=560, y=190)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=560, y=195)
s.filled = True
s.fill_color = "black"
window.add(s)
s = GRect(5, 5, x=560, y=200)
s.filled = True
s.fill_color = "black"
window.add(s)
label = GLabel("Pokémon", x=200, y=80) # Create the name of Pokémon.
label.font = "Helvetica-50-italic-bold"
window.add(label)
label = GLabel("Bulbasaur", x=120, y=130) # Create the name of Bulbasaur.
label.font = "Helvetica-20-bold"
window.add(label)
label = GLabel("Charmander", x=275, y=130) # Create the name of Charmander.
label.font = "Helvetica-20-bold"
window.add(label)
label = GLabel("Squirtle", x=465, y=130) # Create the name of Squirtle.
label.font = "Helvetica-20-bold"
window.add(label)
choose_sign1 = GLabel("▲", x=170, y=330) # Create the sign of "▲".
choose_sign1.font = "-20"
window.add(choose_sign1)
choose_sign2 = GLabel("▲", x=337, y=330) # Create the sign of "▲".
choose_sign2.font = "-20"
window.add(choose_sign2)
choose_sign2 = GLabel("▲", x=500, y=330) # Create the sign of "▲".
choose_sign2.font = "-20"
window.add(choose_sign2)
if __name__ == '__main__':
main()
```
| github_jupyter |
```
import cv2
import os
import torch,torchvision
import torch.nn as nn
import numpy as np
import os
from tqdm import tqdm
import matplotlib.pyplot as plt
import torch.optim as optim
from torch.nn import *
from torch.utils.tensorboard import SummaryWriter
import matplotlib.pyplot as plt
import wandb
from ray import tune
import os
torch.cuda.empty_cache()
device = 'cuda'
PROJECT_NAME = 'Landscape-Pictures-GAN'
IMG_SIZE = 224
def load_data(directory='./data/',img_size=IMG_SIZE,num_of_samples=500):
idx = -1
data = []
for file in tqdm(os.listdir(directory)):
idx += 1
file = directory + file
img = cv2.imread(file)
img = cv2.resize(img,(img_size,img_size))
data.append(img)
print(idx)
data = data[:num_of_samples]
return torch.from_numpy(np.array(data))
# data = load_data()
# torch.save(data,'./data.pt')
# torch.save(data,'./data.pth')
data = torch.load('./data.pth')
data.shape
plt.imshow(torch.tensor(data[0]).view(IMG_SIZE,IMG_SIZE,3))
class Desc(nn.Module):
def __init__(self,linearactivation=nn.LeakyReLU()):
super().__init__()
self.linearactivation = linearactivation
self.linear1 = nn.Linear(IMG_SIZE*IMG_SIZE*3,2)
self.linear1batchnorm = nn.BatchNorm1d(2)
self.linear2 = nn.Linear(2,4)
self.linear2batchnorm = nn.BatchNorm1d(4)
self.linear3 = nn.Linear(4,2)
self.linear3batchnorm = nn.BatchNorm1d(2)
self.output = nn.Linear(2,1)
self.outputactivation = nn.Sigmoid()
def forward(self,X,shape=True):
preds = self.linearactivation(self.linear1batchnorm(self.linear1(X)))
preds = self.linearactivation(self.linear2batchnorm(self.linear2(preds)))
preds = self.linearactivation(self.linear3batchnorm(self.linear3(preds)))
preds = self.outputactivation(self.output(preds))
return preds
class Gen(nn.Module):
def __init__(self,z_dim,linearactivation=nn.LeakyReLU()):
super().__init__()
self.linearactivation = linearactivation
self.linear1 = nn.Linear(z_dim,256)
self.linear1batchnorm = nn.BatchNorm1d(256)
self.linear2 = nn.Linear(256,512)
self.linear2batchnorm = nn.BatchNorm1d(512)
self.linear3 = nn.Linear(512,256)
self.linear3batchnorm = nn.BatchNorm1d(256)
self.output = nn.Linear(256,IMG_SIZE*IMG_SIZE*3)
self.outputactivation = nn.Tanh()
def forward(self,X):
preds = self.linearactivation(self.linear1batchnorm(self.linear1(X)))
preds = self.linearactivation(self.linear2batchnorm(self.linear2(preds)))
preds = self.linearactivation(self.linear3batchnorm(self.linear3(preds)))
preds = self.outputactivation(self.output(preds))
return preds
z_dim = 64
BATCH_SIZE = 32
lr = 3e-4
criterion = nn.BCELoss()
epochs = 125
fixed_noise = torch.randn((BATCH_SIZE,z_dim)).to(device)
gen = Gen(z_dim=z_dim).to(device)
optimizer_gen = optim.Adam(gen.parameters(),lr=lr)
desc = Desc().to(device)
optimizer_desc = optim.Adam(desc.parameters(),lr=lr)
def accuracy_fake(desc_fake):
correct = 0
total = 0
preds = np.round(np.array(desc_fake.cpu().detach().numpy()))
for pred in preds:
if pred == 0:
correct += 1
total += 1
return round(correct/total,3)
def accuracy_real(desc_real):
correct = 0
total = 0
preds = np.round(np.array(desc_real.cpu().detach().numpy()))
for pred in preds:
if pred == 1:
correct += 1
total += 1
return round(correct/total,3)
torch.cuda.empty_cache()
msg = input('Msg : ') # 0.1-leaky-relu-desc
wandb.init(project=PROJECT_NAME,name=f'baseline-{msg}')
for epoch in tqdm(range(epochs)):
torch.cuda.empty_cache()
for idx in range(0,len(data),BATCH_SIZE):
torch.cuda.empty_cache()
X_batch = torch.tensor(np.array(data[idx:idx+BATCH_SIZE])).view(-1,IMG_SIZE*IMG_SIZE*3).to(device).float()
batch_size = X_batch.shape[0]
noise = torch.randn(batch_size, z_dim).to(device)
fake = gen(noise).float()
desc_real = desc(X_batch).view(-1)
lossD_real = criterion(desc_real,torch.ones_like(desc_real))
desc_fake = desc(fake).view(-1)
lossD_fake = criterion(desc_fake,torch.zeros_like(desc_fake))
lossD = (lossD_real+lossD_fake)/2
desc.zero_grad()
lossD.backward(retain_graph=True)
wandb.log({'lossD':lossD.item()})
optimizer_desc.step()
output = desc(fake).view(-1)
lossG = criterion(output, torch.ones_like(output))
gen.zero_grad()
wandb.log({'lossG':lossG.item()})
lossG.backward()
wandb.log({'lossG':lossG.item()})
optimizer_gen.step()
wandb.log({'accuracy_fake':accuracy_fake(desc_fake)})
wandb.log({'accuracy_real':accuracy_real(desc_real)})
with torch.no_grad():
imgs = gen(fixed_noise).view(-1,3,IMG_SIZE,IMG_SIZE)
imgs_all_grid = torchvision.utils.make_grid(imgs,normalize=True)
wandb.log({'img':wandb.Image(imgs[0].cpu())})
wandb.log({'imgs':wandb.Image(imgs_all_grid)})
```
| github_jupyter |
Definition of **DTLZ2 problem** with 3 objective functions:
$f_1(X) = (1 + g(x_3)) \cdot cos(x_1 \cdot \frac{\pi}{2}) \cdot cos(x_2 \cdot \frac{\pi}{2})$
$f_2(X) = (1 + g(x_3)) \cdot cos(x_1 \cdot \frac{\pi}{2}) \cdot sin(x_2 \cdot \frac{\pi}{2})$
$f_3(x) = (1 + g(x_3)) \cdot sin(x_1 \cdot \frac{\pi}{2})$
with
$-10 \leq x_1 \leq 10$
$-10 \leq x_2 \leq 10$
$-10 \leq x_3 \leq 10$
$g(x_3) = \sum_{x_i \in X_M} (x_i - 0.5)^2$
adapted from "*Scalable Test Problems for Evolutionary Multi-Objective Optimization*" section 8.2.
```
import sys
sys.path.append('../..')
import numpy as np
import matplotlib.pyplot as plt
import beagle as be
np.random.seed(1997)
# Problem definition
def func_1(values):
const = np.pi / 2
return (1 + g(values)) * np.cos(values[0]*const) * np.cos(values[1]*const)
def func_2(values):
const = np.pi / 2
return (1 + g(values)) * np.cos(values[0]*const) * np.sin(values[1]*const)
def func_3(values):
const = np.pi / 2
return (1 + g(values)) * np.sin(values[0]*const)
def g(values):
result = 0.0
for val in values:
result += (val - 0.5)**2
return result
x_1 = x_2 = x_3 = (-10.0, 10.0)
representation = 'real'
# Algorithm definition
nsga2 = be.use_algorithm(
'experimental.NSGA2',
fitness=be.Fitness(func_1, func_2, func_3),
population_size=100,
individual_representation='real',
bounds = [x_1, x_2, x_3],
alg_id='nsga2',
evaluate_in_parallel=False
)
spea2 = be.use_algorithm(
'experimental.SPEA2',
fitness=be.Fitness(func_1, func_2, func_3),
population_size=50,
individual_representation='real',
bounds = [x_1, x_2, x_3],
spea2_archive=100,
alg_id='spea2',
evaluate_in_parallel=False
)
wrapper = be.parallel(nsga2, spea2, generations=50)
wrapper.algorithms
# NSGA2
be.display(wrapper.algorithms[0], only_show=True)
# SPEA2
be.display(wrapper.algorithms[1], only_show=True)
# Obtain the solutions that make up the non-dominated front of each algorithm
indices, values = be.pareto_front(wrapper.algorithms[0])
nsga2_sols = np.array([
wrapper.algorithms[0].population[idx].values for idx in indices['population']
])
indices, values = be.pareto_front(wrapper.algorithms[0])
spea2_sols = np.array([
wrapper.algorithms[1].population['archive'][idx].values for idx in indices['population']
])
fig = plt.figure(2, figsize=(15, 15))
ax1 = fig.add_subplot(221, projection='3d')
ax2 = fig.add_subplot(222, projection='3d')
ax3 = fig.add_subplot(223, projection='3d')
ax4 = fig.add_subplot(224, projection='3d')
# Problem definition
def f_1_vec(x, y, z):
const = np.pi / 2
values = np.array((x, y, z))
return (1 + g_vec(values)) * np.cos(x*const) * np.cos(y*const)
def f_2_vec(x, y, z):
const = np.pi / 2
values = np.array((x, y, z))
return (1 + g_vec(values)) * np.cos(x*const) * np.sin(y*const)
def f_3_vec(x, y, z):
const = np.pi / 2
values = np.array((x, y, z))
return (1 + g_vec(values)) * np.sin(x*const)
def g_vec(values):
result = np.power(values - 0.5, 2)
return np.sum(result, axis=0)
for ax in [ax1, ax2, ax3, ax4]:
# Plot the obtained Pareto's front
ax.scatter(
f_1_vec(spea2_sols[:, 0], nsga2_sols[:, 1], nsga2_sols[:, 2]),
f_2_vec(nsga2_sols[:, 0], nsga2_sols[:, 1], nsga2_sols[:, 2]),
f_3_vec(nsga2_sols[:, 0], nsga2_sols[:, 1], nsga2_sols[:, 2]),
color='red', alpha=0.7, linewidth=0, antialiased=False, label='SPEA2')
ax.scatter(
f_1_vec(spea2_sols[:, 0], spea2_sols[:, 1], spea2_sols[:, 2]),
f_2_vec(spea2_sols[:, 0], spea2_sols[:, 1], spea2_sols[:, 2]),
f_3_vec(spea2_sols[:, 0], spea2_sols[:, 1], spea2_sols[:, 2]),
color='green', alpha=0.7, linewidth=0, antialiased=False, label='NSGA2')
ax.set_xlabel('f1(x)', size=15)
ax.set_ylabel('f2(x)', size=15)
ax.set_zlabel('f3(x)', size=15)
ax2.view_init(40, -20)
ax3.view_init(40, 0)
ax4.view_init(40, 30)
handles, labels = ax1.get_legend_handles_labels()
fig.legend(handles, labels, loc='lower center', fontsize=20, markerscale=2)
plt.show()
```
| github_jupyter |
```
from nlpkf.models.seq2seq import preprocess_catalan, Translator
all_english, all_catalan = preprocess_catalan("cat.txt")
eng_prefixes = (
"i am ", "i m ",
"he is", "he s ",
"she is", "she s ",
"you are", "you re ",
"we are", "we re ",
"they are", "they re "
)
def filter_prefixes(lang_1, lang_2, prefixes):
filtered_1 = []
filtered_2 = []
for sent_1, sent_2 in zip(lang_1, lang_2):
if sent_1[5:].strip().lower().startswith(prefixes):
filtered_1.append(sent_1)
filtered_2.append(sent_2)
return filtered_1, filtered_2
english, catalan = filter_prefixes(all_english, all_catalan, eng_prefixes)
#english, catalan = all_english, all_catalan
tok_kwargs = dict(remove_stopwords=False, use_stems=False,
to_lowercase=False, use_lemma=False, remove_punctuation=True, normalize_strings=True)
import time
start = time.time()
trans = Translator(16, 32, tokenizer_kwargs=tok_kwargs, vectorizer_kwargs={"lowercase":False}, pretrained=False)
end = time.time()
print(end - start)
trans.target_proc.build_vocabulary(catalan)
trans.target_proc.clean_text(catalan)
trans.target_proc.vocabulary
%%time
x_corpus, y_corpus = trans.fit(english, catalan)
trans.encoder
trans.decoder
trans.train(x_corpus, y_corpus, print_every=1, n_iters=100, preprocess=False, plot_every=5)
%%time
tensors_catalan = trans.sentences_to_tensors(catalan, trans.target_proc)
%%time
tensors_english = trans.sentences_to_tensors(english, trans.src_proc)
%matplotlib inline
import matplotlib.pyplot as plt
trans.plot_loss()
trans
trans.evaluate_attention(english[10])
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def plot_loss(self):
#plt.switch_backend('agg')
plt.figure()
fig, ax = plt.subplots()
# this locator puts ticks at regular intervals
loc = ticker.MultipleLocator(base=0.2)
ax.yaxis.set_major_locator(loc)
return plt.plot(self.plot_losses)
plot_loss(trans)
plt.show()
def show_attention(input_sentence, output_words, attentions):
# Set up figure with colorbar
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.numpy(), cmap='bone')
fig.colorbar(cax)
# xticks = [''] + input_sentence.split(' ') + ['<EOS>']
# yticks = [''] + output_words
xticks = [''] + input_sentence.split(' ')
yticks = [''] + output_words
# Set up axes
ax.set_xticklabels(xticks, rotation=90)
ax.set_yticklabels(yticks)
# Show label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
plt.show()
def evaluate_attention(input_sentence, trans, *args, **kwargs):
output_words, attentions = trans.predict(input_sentence, *args, **kwargs)
print('input =', input_sentence)
print('output =', ' '.join(output_words))
show_attention(input_sentence, output_words, attentions)
return input_sentence, output_words
evaluate_attention(english[10], trans)
trans.target_proc.clean_text(catalan)
input_sentence, output_words = evaluate_attention(english[12], trans)
evaluate_attention(english[10], trans)
output_words, attentions = trans.predict(english[0])
attentions.numpy()
output_words
english[0].split(" ")
input_sentence.split(' ')[1:-1]
n = 2
trans.evaluate(english[n], catalan[n])
def evaluateRandomly(pairs, trans, n=1):
for i in range(n):
pair = random.choice(pairs)
print('>', pair[0])
print('=', pair[1])
output_words, attentions = trans.evaluate(pair[0])
output_sentence = ' '.join(output_words)
print('<', output_sentence)
print('')
import random
evaluateRandomly([(english[10], catalan[10])], trans)
%%time
max_seq_len(tensors_catalan, tensors_english)
import torch
import numpy as np
torch.from_numpy(np.arange(10)).to("cuda")
from nlpkf.tokenizer import EOS_TOKEN, SOS_TOKEN
def add_tokens_to_sentence(text, sos_token: str=SOS_TOKEN, eos_token: str=EOS_TOKEN):
return " {} {} {} ".format(sos_token, text, eos_token)
def preprocess_translator(text, proc_func, sos_token: str=SOS_TOKEN, eos_token: str=EOS_TOKEN):
source = []
target = []
for src, dst in proc_func(text):
src, dst = add_tokens_to_sentence(src), add_tokens_to_sentence(dst)
source.append(src)
target.append(dst)
return source, target
[tuple(x.split("\t")) for x in str(data).split("\n")][0]
src, dst = preprocess_translator(data, lambda x: [tuple(x.split("\t")) for x in str(data).split("\n")[:-1]])
src
import torch
torch.tensor([[0]], device="cpu")
torch.cuda.is_available()
for sent in doc.sents:
print(sent)
```
| github_jupyter |
```
from subprocess import call
from glob import glob
from nltk.corpus import stopwords
import os, struct
from tensorflow.core.example import example_pb2
import pyrouge
import shutil
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from nltk.stem.porter import *
ratio = 1
duc_num = 7
max_len = 250
#cmd = '/root/miniconda2/bin/python ../pointer-generator-master/run_summarization.py --mode=decode --single_pass=1 --coverage=True --vocab_path=finished_files/vocab --log_root=log --exp_name=myexperiment --data_path=test/temp_file'
#cmd = '/root/miniconda2/bin/python run_summarization.py --mode=decode --single_pass=1 --coverage=True --vocab_path=finished_files/vocab --log_root=log --exp_name=myexperiment --data_path=test/temp_file --max_enc_steps=4000'
#cmd = cmd.split()
#generated_path = '/gttp/pointer-generator-master/log/myexperiment/decode_test_4000maxenc_4beam_35mindec_120maxdec_ckpt-238410/'
#generated_path = '/gttp/pointer-generator-tal/log/myexperiment/decode_test_4000maxenc_4beam_35mindec_100maxdec_ckpt-238410/'
vocab_path = '../data/DMQA/finished_files/vocab'
log_root = 'log'
exp_name = 'myexperiment'
data_path= 'test/temp_file'
max_enc_steps = 4000
cmd = ['python',
'run_summarization.py',
'--mode=decode',
'--single_pass=1',
'--coverage=True',
'--vocab_path=' + vocab_path,
'--log_root=' + log_root,
'--exp_name=' + exp_name,
'--data_path=' + data_path,
'--max_enc_steps=' + str(max_enc_steps)]
generated_path = 'log/myexperiment/decode_test_4000maxenc_4beam_35mindec_100maxdec_ckpt-238410/'
stopwords = set(stopwords.words('english'))
stemmer = PorterStemmer()
def pp(string):
return ' '.join([stemmer.stem(word.decode('utf8')) for word in string.lower().split() if not word in stopwords])
def write_to_file(article, abstract, rel, writer):
abstract = '<s> '+' '.join(abstract)+' </s>'
#abstract = abstract.encode('utf8', 'ignore')
#rel = rel.encode('utf8', 'ignore')
#article = article.encode('utf8', 'ignore')
tf_example = example_pb2.Example()
tf_example.features.feature['abstract'].bytes_list.value.extend([bytes(abstract)])
tf_example.features.feature['relevancy'].bytes_list.value.extend([bytes(rel)])
tf_example.features.feature['article'].bytes_list.value.extend([bytes(article)])
tf_example_str = tf_example.SerializeToString()
str_len = len(tf_example_str)
writer.write(struct.pack('q', str_len))
writer.write(struct.pack('%ds' % str_len, tf_example_str))
def duck_iterator(i):
duc_folder = 'duc0' + str(i) + 'tokenized/'
for topic in os.listdir(duc_folder + 'testdata/docs/'):
topic_folder = duc_folder + 'testdata/docs/' + topic
if not os.path.isdir(topic_folder):
continue
query = ' '.join(open(duc_folder + 'queries/' + topic).readlines())
model_files = glob(duc_folder + 'models/' + topic[:-1].upper() + '.*')
topic_texts = [' '.join(open(topic_folder + '/' + file).readlines()).replace('\n', '') for file in
os.listdir(topic_folder)]
abstracts = [' '.join(open(f).readlines()) for f in model_files]
yield topic_texts, abstracts, query
def ones(sent, ref): return 1.
def count_score(sent, ref):
ref = pp(ref).split()
sent = ' '.join(pp(w) for w in sent.lower().split() if not w in stopwords)
return sum([1. if w in ref else 0. for w in sent.split()])
def get_w2v_score_func(magic = 10):
import gensim
google = gensim.models.KeyedVectors.load_word2vec_format(
'GoogleNews-vectors-negative300.bin', binary=True)
def w2v_score(sent, ref):
ref = ref.lower()
sent = sent.lower()
sent = [w for w in sent.split() if w in google]
ref = [w for w in ref.split() if w in google]
try:
score = google.n_similarity(sent, ref)
except:
score = 0.
return score * magic
return w2v_score
def get_tfidf_score_func_glob(magic = 1):
corpus = []
for i in range(5, 8):
for topic_texts, _, _ in duck_iterator(i):
corpus += [pp(t) for t in topic_texts]
vectorizer = TfidfVectorizer()
vectorizer.fit_transform(corpus)
def tfidf_score_func(sent, ref):
#ref = [pp(s) for s in ref.split(' . ')]
sent = pp(sent)
v1 = vectorizer.transform([sent])
#v2s = [vectorizer.transform([r]) for r in ref]
#return max([cosine_similarity(v1, v2)[0][0] for v2 in v2s])
v2 = vectorizer.transform([ref])
return cosine_similarity(v1, v2)[0][0]
return tfidf_score_func
tfidf_score = get_tfidf_score_func_glob()
def get_tfidf_score_func(magic = 10):
corpus = []
for i in range(5, 8):
for topic_texts, _, _ in duck_iterator(i):
corpus += [t.lower() for t in topic_texts]
vectorizer = TfidfVectorizer()
vectorizer.fit_transform(corpus)
def tfidf_score_func(sent, ref):
ref = ref.lower()
sent = sent.lower()
v1 = vectorizer.transform([sent])
v2 = vectorizer.transform([ref])
return cosine_similarity(v1, v2)[0][0]*magic
return tfidf_score_func
def just_relevant(text, query):
text = text.split(' . ')
score_per_sent = [count_score(sent, query) for sent in text]
sents_gold = list(zip(*sorted(zip(score_per_sent, text), reverse=True)))[1]
sents_gold = sents_gold[:int(len(sents_gold)*ratio)]
filtered_sents = []
for s in text:
if not s: continue
if s in sents_gold: filtered_sents.append(s)
return ' . '.join(filtered_sents)
class Summary:
def __init__(self, texts, abstracts, query):
#texts = sorted([(tfidf_score(query, text), text) for text in texts], reverse=True)
#texts = sorted([(tfidf_score(text, ' '.join(abstracts)), text) for text in texts], reverse=True)
#texts = [text[1] for text in texts]
self.texts = texts
self.abstracts = abstracts
self.query = query
self.summary = []
self.words = set()
self.length = 0
def add_sum(self, summ):
for sent in summ:
self.summary.append(sent)
def get(self):
text = max([(len(t.split()), t) for t in self.texts])[1]
#text = texts[0]
if ratio < 1: text = just_relevant(text, self.query)
sents = text.split(' . ')
score_per_sent = [(score_func(sent, self.query), sent) for sent in sents]
#score_per_sent = [(count_score(sent, ' '.join(self.abstracts)), sent) for sent in sents]
scores = []
for score, sent in score_per_sent:
scores += [score] * (len(sent.split()) + 1)
scores = str(scores[:-1])
return text, 'a', scores
def get_summaries(path):
path = path+'decoded/'
out = {}
for file_name in os.listdir(path):
index = int(file_name.split('_')[0])
out[index] = open(path+file_name).readlines()
return out
def rouge_eval(ref_dir, dec_dir):
"""Evaluate the files in ref_dir and dec_dir with pyrouge, returning results_dict"""
r = pyrouge.Rouge155()
r.model_filename_pattern = '#ID#_reference_(\d+).txt'
r.system_filename_pattern = '(\d+)_decoded.txt'
r.model_dir = ref_dir
r.system_dir = dec_dir
return r.convert_and_evaluate()
def evaluate(summaries):
for path in ['eval/ref', 'eval/dec']:
if os.path.exists(path): shutil.rmtree(path, True)
os.mkdir(path)
for i, summ in enumerate(summaries):
for j,abs in enumerate(summ.abstracts):
with open('eval/ref/'+str(i)+'_reference_'+str(j)+'.txt', 'w') as f:
f.write(abs)
with open('eval/dec/'+str(i)+'_decoded.txt', 'w') as f:
f.write(' '.join(summ.summary))
print rouge_eval('eval/ref/', 'eval/dec/')
#count_score
#score_func = ones#get_w2v_score_func()#get_tfidf_score_func()#count_score
score_func = get_tfidf_score_func()
summaries = [Summary(texts, abstracts, query) for texts, abstracts, query in duck_iterator(duc_num)]
with open('test/temp_file', 'wb') as writer:
for summ in summaries:
article, abstract, scores = summ.get()
write_to_file(article, abstracts, scores, writer)
call(['rm', '-r', generated_path])
call(cmd)
generated_summaries = get_summaries(generated_path)
for i in range(len(summaries)):
summaries[i].add_sum(generated_summaries[i])
evaluate(summaries)
print duc_num
print score_func
```
| github_jupyter |
```
import itertools
import numpy as np
import os
import seaborn as sns
from tqdm import tqdm
from dataclasses import asdict, dataclass, field
import vsketch
import shapely.geometry as sg
from shapely.geometry import box, MultiLineString, Point, MultiPoint, Polygon, MultiPolygon, LineString
import shapely.affinity as sa
import shapely.ops as so
import matplotlib.pyplot as plt
import pandas as pd
import vpype_cli
from typing import List, Generic
from genpen import genpen as gp, utils as utils
from scipy import stats as ss
import geopandas
from shapely.errors import TopologicalError
import functools
%load_ext autoreload
%autoreload 2
import vpype
from skimage import io
from pathlib import Path
import bezier
from sklearn.preprocessing import minmax_scale
from skimage import feature
from genpen.utils import Paper
from scipy import spatial, stats
from scipy.ndimage import gaussian_filter
from scipy.integrate import odeint
import fn
# make page
paper_size = '14x11 inches'
border:float=10
paper = Paper(paper_size)
drawbox = paper.get_drawbox(border)
lines = []
node_sets = []
n_lines = 500
n_nodes_per_line = 40
y_start = 0
y_end = 14
x_start = 0
x_end = 10
node_x_centers = np.linspace(x_start, x_end, n_lines)
std_scale = 0.09
n_eval_points = 80
### initialize vals
node_ys = np.linspace(y_start, y_end, n_nodes_per_line)
centered_node_xs = np.zeros(node_ys.shape)
bez_eval_end_center = 1
bez_eval_end_noise = 0
bez_eval_end_limit = 1.
bez_eval_end_std_scale = 0.01
for i, node_x_center in enumerate(node_x_centers):
new_x_noise = np.random.randn(n_nodes_per_line) * std_scale
centered_node_xs = centered_node_xs + new_x_noise
node_xs = node_x_center + centered_node_xs
node_xs[:3] = node_x_center
node_xs[-3:] = node_x_center
nodes = np.asfortranarray([
node_xs,
node_ys,
])
curve = bezier.Curve(nodes, degree=(nodes.shape[1]-1))
eval_start = np.random.uniform(0, 0.03)
eval_end = np.random.uniform(0.97, 1.)
eval_points = np.linspace(eval_start, eval_end, n_eval_points)
x, y = curve.evaluate_multi(eval_points)
if i % 2:
x = np.flipud(x)
y = np.flipud(y)
lines.append(np.stack([x, y]).T)
node_sets.append(np.stack([node_xs, node_ys]).T)
ls = [LineString(l) for l in lines]
mls = gp.make_like(gp.merge_LineStrings(ls), drawbox)
mask = drawbox
in_mask = mls.intersection(mask)
in_mask = sa.rotate(in_mask, -90)
split_point = 500
layer1 = in_mask[:split_point]
layer2 = in_mask[split_point:]
layers = []
layers.append(LineString(np.concatenate([np.array(l) for l in layer1])))
layers.append(LineString(np.concatenate([np.array(l) for l in layer2])))
# layers = [in_mask]
sk = vsketch.Vsketch()
sk.size(paper.page_format_mm)
sk.scale('1mm')
sk.penWidth('0.3mm')
for i, layer in enumerate(layers):
sk.stroke(i+1)
sk.geometry(layer)
sk.penWidth('0.3')
sk.vpype('linesort')
sk.display(color_mode='none')
sk.save('/mnt/c/code/side/plotter_images/oned_outputs/246_500_lines.svg')
# make page
paper_size = '17x23.5 inches'
border:float=55
paper = Paper(paper_size)
drawbox = paper.get_drawbox(border)
def oscillator(y, t, a, b, c, d):
v, u = y
dvdt = np.sin(v) + (a * v) + (b * u)
dudt = np.cos(u) + (c * v) + (d * u)
dydt = [dvdt, dudt]
return dydt
def oscillator2(y, t, a, b, c, d):
v, u = y
dvdt = np.sin(v) + np.sin(u) + (a * v) + (b * u)
dudt = np.cos(u) + np.cos(u) ** 2 + (c * v) + (d * u)
dydt = [dvdt, dudt]
return dydt
def ode(y, t, a, b, c, d):
v, u = y
dvdt = np.sin(v) + np.cos(u * v) + (a * v) + (b * u)
dudt = np.cos(u) + np.sin(u * v) + (c * v) + (d * u)
dydt = [dvdt, dudt]
return dydt
center = drawbox.centroid
n_lines = 500
thetas = np.linspace(0, np.pi*10, n_lines)
radii = np.linspace(.5, 4.5, n_lines)
pts = []
for theta, radius in zip(thetas, radii):
x = np.cos(theta) * radius
y = np.sin(theta) * radius
pts.append(Point(x, y))
lfs = []
t_max = 3.7
t = np.linspace(0, t_max, 1801)
a = -0.4
b = 0.3
c = 0.75
d = -0.2
for pt in tqdm(pts):
sol = odeint(ode, [pt.x, pt.y], t, args=(a, b, c, d))
lfs.append(LineString(sol))
lines = gp.make_like(MultiLineString(lfs), drawbox)
sk = vsketch.Vsketch()
sk.size(paper.page_format_mm)
sk.scale('1mm')
sk.penWidth('0.3mm')
sk.geometry(lines)
sk.penWidth('0.3')
sk.vpype('linesimplify linesort ')
sk.display(color_mode='none')
sk.save('/mnt/c/code/side/plotter_images/oned_outputs/247_500_lines.svg')
```
# Try 2
```
# make page
paper_size = '17x23.5 inches'
border:float=55
paper = Paper(paper_size)
drawbox = paper.get_drawbox(border)
center = drawbox.centroid
n_lines = 500
thetas = np.linspace(0, np.pi*10, n_lines)
radii = np.linspace(.75, 3.45, n_lines)
pts = []
for theta, radius in zip(thetas, radii):
x = np.cos(theta) * radius - 3.3
y = np.sin(theta) * radius + 0.5
pts.append(Point(x, y))
def ode2(y, t, a, b, c, d):
v, u = y
dvdt = np.sin(u * v + (a * v) + (b * u))
dudt = np.cos(u) + np.sin(u * v) + (c * v) + (d * u)
dydt = [dvdt, dudt]
return dydt
lfs = []
t_max = 2.7
t = np.linspace(0, t_max, 1801)
a = -0.2
b = -0.2
c = 0.04
d = -0.25
for pt in tqdm(pts):
sol = odeint(ode2, [pt.x, pt.y], t, args=(a, b, c, d))
lfs.append(LineString(sol))
lines = gp.make_like(MultiLineString(lfs), drawbox)
layers = []
layers.append(lines[:250])
layers.append(lines[250:])
sk = vsketch.Vsketch()
sk.size(paper.page_format_mm)
sk.scale('1mm')
sk.penWidth('0.3mm')
for i, layer in enumerate(layers):
sk.stroke(i+1)
sk.geometry(layer)
sk.penWidth('0.3')
sk.vpype('linesimplify')
sk.display(color_mode='layer')
sk.save('/mnt/c/code/side/plotter_images/oned_outputs/249_500_lines.svg')
```
# Try 3
```
# make page
paper_size = '17x23.5 inches'
border:float=35
paper = Paper(paper_size)
drawbox = paper.get_drawbox(border)
center = drawbox.centroid
n_lines = 3500
thetas = np.linspace(0, np.pi*14, n_lines)
radii = np.linspace(.5, 5.45, n_lines)
pts = []
for theta, radius in zip(thetas, radii):
x = np.cos(theta) * radius - 3.3
y = np.sin(theta) * radius + 0.5
pts.append(Point(x, y))
def ode2(y, t, a, b, c, d):
v, u = y
dvdt = np.sin(u * v + (a * v) + (b * u))
dudt = np.cos(u) + np.sin(u * v) + np.cos(c * v) + (d * u)
dydt = [dvdt, dudt]
return dydt
lfs = []
t_max = 2.7
t = np.linspace(0, t_max, 701)
a = -0.2
b = -0.25
c = 0.04
d = -0.25
for pt in tqdm(pts):
sol = odeint(ode2, [pt.x, pt.y], t, args=(a, b, c, d))
lfs.append(LineString(sol))
lines = gp.make_like(MultiLineString(lfs), drawbox)
lbs = lines.buffer(0.07, cap_style=2, join_style=2).boundary
lbs = gp.merge_LineStrings([l for l in lbs if l.length > 0.9])
n_layers = 1
layer_inds = np.split(np.arange(len(lbs)), n_layers)
layers = []
for ind_set in layer_inds:
layer = [lbs[i] for i in ind_set]
layers.append(gp.merge_LineStrings(layer))
sk = vsketch.Vsketch()
sk.size(paper.page_format_mm)
sk.scale('1mm')
sk.penWidth('0.3mm')
for i, layer in enumerate(layers):
sk.stroke(i+1)
sk.geometry(layer)
sk.penWidth('0.3')
sk.vpype('linesimplify')
sk.display(color_mode='layer')
sk.save('/mnt/c/code/side/plotter_images/oned_outputs/251_3500_lines.svg')
```
# Try 4
```
# make page
paper_size = '11x14 inches'
border:float=25
paper = Paper(paper_size)
drawbox = paper.get_drawbox(border)
center = drawbox.centroid
n_lines = 500
thetas = np.linspace(0, np.pi*14, n_lines)
radii = np.linspace(.5, 5.45, n_lines)
pts = []
for theta, radius in zip(thetas, radii):
x = np.cos(theta) * radius - 3.3
y = np.sin(theta) * radius + 0.5
pts.append(Point(x, y))
def ode2(y, t, a, b, c, d):
v, u = y
dvdt = np.sin(u * v + (a * v) + (b * u))
dudt = np.cos(u) + np.sin(u * v) + np.cos(c * v) + (d * u)
dydt = [dvdt, dudt]
return dydt
lfs = []
t_max = 2.7
t = np.linspace(0, t_max, 701)
a = -0.2
b = -0.25
c = 0.04
d = -0.25
for pt in tqdm(pts):
sol = odeint(ode2, [pt.x, pt.y], t, args=(a, b, c, d))
lfs.append(LineString(sol))
lines = gp.make_like(MultiLineString(lfs), drawbox)
lbs = lines.buffer(0.07, cap_style=2, join_style=2).boundary
lbs = gp.merge_LineStrings([l for l in lbs if l.length > 0.9])
n_layers = 1
layer_inds = np.split(np.arange(len(lbs)), n_layers)
layers = []
for ind_set in layer_inds:
layer = [lbs[i] for i in ind_set]
layers.append(gp.merge_LineStrings(layer))
sk = vsketch.Vsketch()
sk.size(paper.page_format_mm)
sk.scale('1mm')
sk.penWidth('0.3mm')
for i, layer in enumerate(layers):
sk.stroke(i+1)
sk.geometry(layer)
sk.penWidth('0.3')
sk.vpype('linesimplify')
sk.display(color_mode='layer')
plot_id = fn.new_plot_id()
savedir='/home/naka/art/plotter_svgs'
savepath = Path(savedir).joinpath(f'{plot_id}.svg').as_posix()
sk.save(savepath)
```
| github_jupyter |
Based On the Canadian Marijuana Index these are the primary players in the Canadian Market.
```
from pandas_datareader import data as pdr
import fix_yahoo_finance as fyf
import matplotlib.pyplot as plt
import datetime
import numpy as np
import pandas as pd
import scipy
# import statsmodels.api as sm
from sklearn import mixture as mix
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
import bt
import ffn
import jhtalib as jhta
import datetime
# import matplotlib as plt
import seaborn as sns
sns.set()
fyf.pdr_override()
# If want Futures data call Quandl
# # Dates
start = datetime.datetime(2005, 1, 1)
end = datetime.datetime(2019, 1, 27)
pd.core.common.is_list_like = pd.api.types.is_list_like
# import pandas_datareader as pdr
%pylab
# params = {'legend.fontsize': 'x-large',
# 'figure.figsize': (15, 5),
# 'axes.labelsize': 'x-large',
# 'axes.titlesize':'x-large',
# 'xtick.labelsize':'x-large',
# 'ytick.labelsize':'x-large'}
# pylab.rcParams.update(params)
%matplotlib inline
# stocks = ['WEED.TO','ACB.TO','TLRY',
# 'CRON.TO', 'HEXO.TO', 'TRST.TO',
# 'OGI.V', 'TGOD.TO', 'RIV.V', 'TER.CN',
# 'XLY.V', 'FIRE.V', 'EMH.V',
# 'N.V', 'VIVO.V', 'WAYL.CN',
# 'HIP.V', 'APHA.TO', 'SNN.CN', 'ISOL.CN']
# Maijuana_Index = pdr.get_data_yahoo(stocks,start= start)
# #
# (Maijuana_Index['Adj Close']['2017':]).plot(figsize=(15,9), title='Canadain Cannibis Index Components')
# Maijuana_Index = Maijuana_Index['Adj Close']
# Maijuana_Index = ffn.rebase(Maijuana_Index)
# Real_Es_Sector = ['IIPR', 'MJNE', 'PRRE',
# 'GRWC', 'ZDPY', 'TURV',
# 'AGTK', 'DPWW', 'CGRA',
# 'DPWW', 'FUTL', 'FTPM']
Real_Es_Sector = ['PRRE']
# list(dict.values(client.get_ticker_metadata(('HYYDF'))))
# # def get_names(list):
# try:
# for i in range(len(Real_Es_Sector)):
# # df = pd.DataFrame(len(Real_Es_Sector))
# x = print(list(dict.values(client.get_ticker_metadata((Real_Es_Sector[i]))))[5])
# except:
# pass
# # print(list(dict.values(client.get_ticker_metadata((Real_Es_Sector[i]))))[5])
# Canada_Index_Names = ['Canaopy Growth Corporation', 'Aurora Canabis Inc.',
# 'Tilray Inc.', 'Cronos Group Inc.', 'Aphria Inc', 'HEXO Corp.'
# 'CannTrust Holdings Inc.', 'OrganiGram Holdings Inc',
# 'The Green Organic Dutchman','Canopy Rivers Inc.',
# 'TerrAscend Corp.', 'Auxly Cannabis Group Inc.',
# 'The Supreme Cannabis Company Inc.','Emerald Health Therapeutics Inc.',
# 'Namaste Technologies Inc.', 'Vivo Cannabis Inc.','Newstrike Brands Ltd',
# 'Wayland Group','Sunniva Inc - Ordinary Shares',
# 'Isodiol International Inc.']
# list(dict.values(client.get_ticker_metadata(('CGRA'))))
# %%html
# <iframe src="https://www.bloomberg.com/quote/HEXO:CN" width="1400" height="1300"></iframe>
```
###### source : http://marijuanaindex.com/stock-quotes/canadian-marijuana-index/
###### source : https://www.bloomberg.com/quote/WEED:CN
## 1. Canopy Growth Corporation : ticker WEED
### - Mkt cap $13,126,000,000 CAD as of January 2019
##### Canopy Growth Corporation, through its subsidiaries, is a producer of medical marijuana. The Company's group of brands represents distinct voices and market positions designed to appeal to an array of customers, doctors and strategic industry partners.
Bloomberg Description:
https://www.bloomberg.com/quote/WEED:CN
CEO: Bruce Linton
https://www.linkedin.com/in/bruce-linton-152137/
CFO: Tim Saunders
https://www.linkedin.com/in/tsaunders/
```
WEED = pdr.get_data_yahoo('WEED.TO',start= start)
```
# Canopy Growth Corporation
### Price Action
```
WEED['Adj Close']['2017':].plot(figsize=(15,9), title='Canopy Growth Corporation', fontsize=25)
```
## 2. Aurora Cannabis Inc. : ticker ACB.TO
### - Mkt cap $6,970,000,000 CAD as of January 2019
##### Overview
source :https://www.linkedin.com/company/aurora-cannabis-inc-/about/
Aurora Cannabis Inc. is a world-renowned integrated cannabis company with an industry-leading reputation for continuously elevating and setting the global cannabis industry standard.
Through our wholly owned subsidiaries, strategic investments, and global partnerships, Aurora provides a wide range of premium quality cannabis and hemp products and services, develops innovative technologies, promotes cannabis consumer health and wellness, and delivers an exceptional customer experience across all its brands.
Aurora’s operations span multiple continents and focuses on both the medical and recreational cannabis production and sales, patient education and clinic counselling services, home hydroponic cultivation, extraction technologies and delivery systems, and hemp-based food health products.
We operate around the globe pursuing new and emerging cannabis markets where possible through our owned network of import, export and wholesale distributors, and our e-commerce and mobile applications.
Bloomberg Description:
https://www.bloomberg.com/quote/ACB:CN
CEO: Terry Booth
https://www.linkedin.com/in/terry-booth-681806131/
CFO: Glen Ibbott
https://www.linkedin.com/in/glenibbott/
```
ACB = pdr.get_data_yahoo('ACB.TO',start= start)
```
# Aurora Cannabis Inc
### Price Action
```
ACB['Adj Close']['2017':].plot(figsize=(15,9), title='Aurora Cannabis Inc', fontsize=25)
```
## 3. Tilray Inc. : ticker TLRY
### - Mkt cap $6,699,000,000 CAD as of January 2019
##### Overview
source :https://www.linkedin.com/company/tilray/about/
Tilray is a global leader in medical cannabis research and production dedicated to providing safe, consistent and reliable therapy to patients. We are the only GMP certified medical cannabis producer currently supplying products to thousands of patients, physicians, pharmacies, hospitals, governments and researchers in Australia, Canada, the European Union and the Americas.
Bloomberg Description:
https://www.bloomberg.com/quote/TLRY:US
CEO: Brendan Kennedy
https://www.linkedin.com/in/kennedybrendan/
CFO: Mark Castaneda
https://www.linkedin.com/in/mark-castaneda-ba8315/
```
TLRY = pdr.get_data_yahoo('TLRY',start= start)
```
# Tilray Inc
### Price Action
```
TLRY['Adj Close']['2017':].plot(figsize=(15,9), title='Tilray Inc', fontsize=25)
top_three = pd.DataFrame(bt.merge(WEED['Adj Close'], ACB['Adj Close'], TLRY['Adj Close']))
top_three.columns = [['Canopy Growth Corporation', ' Aurora Cannabis Inc.', 'Tilray Inc.']]
top_three = top_three.dropna()
ffn.rebase(top_three).plot(figsize=(15,9), title='Top Cannibis Firms % Returns', fontsize=25)
```
## 4. Cronos Group Inc. : ticker CRON.TO
### - Mkt cap $2,950,000,000 CAD as of January 2019
##### Overview
source :https://www.linkedin.com/company/cronos-group-mjn-/about/
Cronos Group is a globally diversified and vertically integrated cannabis company with a presence across four continents. The Company operates two wholly-owned Canadian Licensed Producers regulated under Health Canada’s Access to Cannabis for Medical Purposes Regulations: Peace Naturals Project Inc. (Ontario), which was the first non-incumbent medical cannabis license granted by Health Canada, and Original BC Ltd. (British Columbia), which is based in the Okanagan Valley. The Company has multiple international production and distribution platforms: Cronos Israel and Cronos Australia. Through an exclusive distribution agreement, Cronos also has access to over 12,000 pharmacies in Germany as the Company focuses on building an international iconic brand portfolio and developing disruptive intellectual property.
Bloomberg Description:
https://www.bloomberg.com/quote/CRON:CN
CEO: Michael Gorenstein
https://www.linkedin.com/in/michaelgorenstein/
CFO: Nauman Siddiqui
https://www.linkedin.com/in/nauman-siddiqui-cpa-cma-bba-b068aa32/
```
CRON = pdr.get_data_yahoo('CRON.TO',start= start)
```
# Cronos Group Inc
### Price Action
```
CRON['Adj Close']['2017':].plot(figsize=(15,9), title='Cronos Group Inc', fontsize=25)
```
## 5. HEXO Corp : ticker HEXO.TO
### - Mkt cap $1,260,000,000 CAD as of January 2019
##### Overview
source : https://www.linkedin.com/company/hexo-corp/about/
HEXO Corp is one of Canada's lowest cost producers of easy-to-use and easy-to-understand products to serve the Canadian medical and adult-use cannabis markets. HEXO Corp's brands include Hydropothecary, an award-winning medical cannabis brand and HEXO, for the adult-use market.
Bloomberg Description:
https://www.bloomberg.com/quote/HEXO:CN
CEO: Adam Miron
https://www.linkedin.com/in/adammiron/
CFO: Ed Chaplin
https://www.linkedin.com/in/echaplin/
```
HEXO = pdr.get_data_yahoo('HEXO.TO',start= start)
```
# HEXO Inc
### Price Action
```
HEXO['Adj Close']['2017':].plot(figsize=(15,9), title='HEXO Corp', fontsize=25)
bottom_30 = pd.read_csv('./bottom30.csv')
```
# Summary Information on the bottom 30% of the Canadian Marijuana Index
```
bottom_30.fillna('-')
```
| github_jupyter |
<div style="text-align:right"><b>Peter Norvig</b> 22 October 2015, revised 28 October 2015, 4 July 2017</div>
# Beal's Conjecture Revisited
In 1637, Pierre de Fermat wrote in the margin of a book that he had a proof of his famous "[Last Theorem](https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem)":
> If $A^n + B^n = C^n$,
> <br>where $A, B, C, n$ are positive integers
> <br>then $n \le 2$.
Centuries passed before [Andrew Beal](https://en.wikipedia.org/wiki/Andrew_Beal), a businessman and amateur mathematician,
made his conjecture in 1993:
> If $A^x + B^y = C^z$,
> <br>where $A, B, C, x, y, z$ are positive integers and $x, y, z$ are all greater than $2$,
> <br>then $A, B$ and $C$ must have a common prime factor.
[Andrew Wiles](https://en.wikipedia.org/wiki/Andrew_Wiles) proved Fermat's theorem in 1995, but Beal's conjecture remains unproved, and Beal has offered [\$1,000,000](http://abcnews.go.com/blogs/headlines/2013/06/billionaire-offers-1-million-to-solve-math-problem/) for a proof or disproof. I don't have the mathematical skills of Wiles, so I could never find a proof, but I can write a program to search for counterexamples. I first wrote [that program in 2000](http://norvig.com/beal2000.html), and [my name got associated](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=beal%20conjecture) with Beal's Conjecture, which means I get a lot of emails with purported proofs or counterexamples (many asking how they can collect their prize money). So far, all the emails have been wrong. This page catalogs some of the more common errors and updates my 2000 program.
# How to Not Win A Million Dollars
* A proof must show that there are no examples that satisfy the conditions. A common error is to show how a certain pattern generates an infinite collection of numbers that satisfy $A^x + B^y = C^z$ and then show that in all of these, $A, B, C$ have a common factor. But that's not good enough, unless you can also prove that no other pattern exists.
<p>
* It is valid to use proof by contradiction: assume the conjecture is true, and show that that leads to a contradiction. It is not valid to use proof by circular reasoning: assume the conjecture is true, put in some irrelevant steps, and show that it follows that the conjecture is true.
<p>
* A valid counterexample needs to satisfy all four conditions—don't leave one out:
> $A, B, C, x, y, z$ are positive integers <br>
$x, y, z > 2$ <br>
$A^x + B^y = C^z$ <br>
$A, B, C$ have no common prime factor.
(If you think you might have a valid counterexample, before you share it with Andrew Beal or anyone else, you can check it with my [Online Beal Counterexample Checker](http://norvig.com/bealcheck.html).)
<p>
* One correspondent claimed that $27^4 + 162 ^ 3 = 9 ^ 7$ was a solution, because the first three conditions hold, and the common factor is 9, which isn't a prime. But of course, if $A, B, C$ have 9 as a common factor, then they also have 3, and 3 is prime. The phrase "no common prime factor" means the same thing as "no common factor greater than 1."
<p>
* Another claimed that $2^3+2^3=2^4$ was a counterexample, because all the bases are 2, which is prime, and prime numbers have no prime factors. But that's not true; a prime number has itself as a factor.
<p>
* A creative person offered $1359072^4 - 940896^4 = 137998080^3$, which fails both because $3^3 2^5 11^2$ is a common factor, and because it has a subtraction rather than an addition (although, as Julius Jacobsen pointed out, that can be rectified by adding $940896^4$ to both sides).
<p>
* Mustafa Pehlivan came up with an example involving 76-million-digit numbers, which took some work to prove wrong (by using modulo arithmetic).
<p>
* Another Beal fan started by saying "Let $C = 43$ and $z = 3$. Since $43 = 21 + 22$, we have $43^3 = (21^3 + 22^3).$" But of course $(a + b)^3 \ne (a^3 + b^3)$. This fallacy is called [the freshman's dream](https://en.wikipedia.org/wiki/Freshman%27s_dream) (although I remember having different dreams as a freshman).
<p>
* Multiple people proposed answers similar to this one:
```
from math import gcd #### In Python versions < 3.5, use "from fractions import gcd"
A, B, C = 60000000000000000000, 70000000000000000000, 82376613842809255677
x = y = z = 3.
A ** x + B ** y == C ** z and gcd(gcd(A, B), C) == 1
```
**WOW! The result is `True`!** Is this a real counterexample to Beal? And also a disproof of Fermat?
Alas, it is not. Notice the decimal point in "`3.`", indicating a floating point number, with inexact, limited precision. Change the inexact "`3.`" to an exact "`3`" and the result changes to "`False`". Below we see that the two sides of the equation are the same for the first 18 digits, but differ starting with the 19th:
```
(A ** 3 + B ** 3,
C ** 3)
```
They say "close" only counts in horseshoes and hand grenades, and if you threw two horseshoes at a stake on the planet [Kapteyn-b](https://en.wikipedia.org/wiki/Kapteyn_b) (a possibly habitable and thus possibly horseshoe-playing exoplanet 12.8 light years from Earth) and the two paths differed in the 19th digit, the horseshoes would end up [less than an inch](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=12.8%20light%20years%20*%201e-19%20in%20inches) apart. That's really, really close, but close doesn't count in number theory.
# *The Simpsons* and Fermat
In two different [episodes of *The Simpsons*](http://www.npr.org/sections/krulwich/2014/05/08/310818693/did-homer-simpson-actually-solve-fermat-s-last-theorem-take-a-look), close counterexamples to Fermat's Last Theorem are shown:
$1782^{12} + 1841^{12} = 1922^{12}$ and $3987^{12} + 4365^{12} = 4472^{12}$. These were designed by *Simpsons* writer David X. Cohen to be correct up to the precision found in most handheld calculators. Cohen found the equations with a program that must have been something like this:
```
from itertools import combinations
def simpsons(bases, powers):
"""Find the integers (A, B, C, n) that come closest to solving
Fermat's equation, A ** n + B ** n == C ** n.
Let A, B range over all pairs of bases and n over all powers."""
equations = ((A, B, iroot(A ** n + B ** n, n), n)
for A, B in combinations(bases, 2)
for n in powers)
return min(equations, key=relative_error)
def iroot(i, n):
"The integer closest to the nth root of i."
return int(round(i ** (1./n)))
def relative_error(equation):
"Error between LHS and RHS of equation, relative to RHS."
(A, B, C, n) = equation
LHS = A ** n + B ** n
RHS = C ** n
return abs(LHS - RHS) / RHS
simpsons(range(1000, 2000), [11, 12, 13])
simpsons(range(3000, 5000), [12])
```
# Back to Beal
In October 2015 I looked back at my original [program from 2000](http://norvig.com/beal2000.html).
I ported it from Python 1.5 to 3.5 (by putting parens around the argument to `print` and adding `long = int`). The program runs 250 times faster today than it did in 2000, a tribute to both computer hardware engineers and the developers of the Python interpreter.
I found that I was a bit confused about the definition of [the problem in 2000](https://web.archive.org/web/19991127081319/http://bealconjecture.com/). I thought then that, *by definition*, $A$ and $B$ could not have a common factor, but actually, the definition of the conjecture only rules out examples where all three of $A, B, C$ share a common factor. Mark Tiefenbruck (and later Edward P. Berlin and Shen Lixing) wrote to point out that my thought was actually correct, not by definition, but by derivation: if $A$ and $B$ have a commmon prime factor $p$, then the sum of $A^x + B^y$ must also have that factor $p$, and since $A^x + B^y = C^z$, then $C^z$ and hence $C$ must have the factor $p$. So I was wrong twice, and in this case two wrongs did make a right.
Mark Tiefenbruck also suggested an optimization: only consider exponents that are odd primes, or 4. The idea is that a number like 512 can be expressed as either $2^9$ or $8^3$, and my program doesn't need to consider both. In general, any time we have a composite exponent, such as $b^{qp}$, where $p$ is prime, we should ignore $b^{(qp)}$, and instead consider only $(b^q)^p$. There's one complication to this scheme: 2 is a prime, but 2 is not a valid exponent for a Beal counterexample. So we will allow 4 as an exponent, as well as all odd primes up to `max_x`.
Here is the complete, updated, refactored, optimized program:
```
from math import gcd, log
from itertools import combinations, product
def beal(max_A, max_x):
"""See if any A ** x + B ** y equals some C ** z, with gcd(A, B) == 1.
Consider any 1 <= A,B <= max_A and x,y <= max_x, with x,y prime or 4."""
Apowers = make_Apowers(max_A, max_x)
Czroots = make_Czroots(Apowers)
for (A, B) in combinations(Apowers, 2):
if gcd(A, B) == 1:
for (Ax, By) in product(Apowers[A], Apowers[B]):
Cz = Ax + By
if Cz in Czroots:
C = Czroots[Cz]
x, y, z = exponent(Ax, A), exponent(By, B), exponent(Cz, C)
print('{} ** {} + {} ** {} == {} ** {} == {}'
.format(A, x, B, y, C, z, C ** z))
def make_Apowers(max_A, max_x):
"A dict of {A: [A**3, A**4, ...], ...}."
exponents = exponents_upto(max_x)
return {A: [A ** x for x in (exponents if (A != 1) else [3])]
for A in range(1, max_A+1)}
def make_Czroots(Apowers): return {Cz: C for C in Apowers for Cz in Apowers[C]}
def exponents_upto(max_x):
"Return all odd primes up to max_x, as well as 4."
exponents = [3, 4] if max_x >= 4 else [3] if max_x == 3 else []
for x in range(5, max_x, 2):
if not any(x % p == 0 for p in exponents):
exponents.append(x)
return exponents
def exponent(Cz, C):
"""Recover z such that C ** z == Cz (or equivalently z = log Cz base C).
For exponent(1, 1), arbitrarily choose to return 3."""
return 3 if (Cz == C == 1) else int(round(log(Cz, C)))
```
It takes less than a second to verify that there are no counterexamples for combinations up to $100^{100}$, a computation that took Andrew Beal thousands of hours on his 1990s-era computers:
```
%time beal(100, 100)
```
The execution time goes up roughly with the square of `max_A`, so the following should take about 100 times longer:
```
%time beal(1000, 100)
```
# How `beal` Works
The function `beal` first does some precomputation, creating two data structures:
* `Apowers`: a dict of the form `{A: [A**3, A**4, ...]}` giving the
nonredundant powers (prime and 4th powers) of each base, `A`, from 3 to `max_x`.
* `Czroots`: a dict of `{C**z : C}` pairs, giving the zth root of each power in `Apowers`.
Here is a very small example Apowers table:
```
Apowers = make_Apowers(6, 10)
Apowers
```
Then we enumerate all combinations of two bases, `A` and `B`, from `Apowers`. Consider the combination where `A` is `3` and `B` is `6`. Of course `gcd(3, 6) == 3`, so the program would not consider them further, but imagine if they did not share a common factor. Then we would look at all possible `Ax + By` sums, for `Ax` in `[27, 81, 243, 2187]` and `By` in `[216, 1296, 7776, 279936].` One of these would be `27 + 216`, which sums to `243`. We look up `243` in `Czroots`:
```
Czroots = make_Czroots(Apowers)
Czroots
Czroots[243]
```
We see that `243` is in `Czroots`, with value `3`, so this would be a counterexample (except for the common factor). The program uses the `exponent` function to recover the values of `x, y, z`, and prints the results.
# Is the Program Correct?
Can we gain confidence in the program? It is difficult to test `beal`, because the expected output is nothing, for all known inputs.
One thing we can do is verify that `beal` finds cases like `3 ** 3 + 6 ** 3 == 3 ** 5 == 243` that would be a counterexample except for the common factor `3`. We can test this by temporarily replacing the `gcd` function with a mock function that always reports no common factors:
```
def gcd(a, b): return 1
beal(100, 100)
```
Let's make sure all those expressions are true:
```
{3 ** 3 + 6 ** 3 == 3 ** 5 == 243,
7 ** 7 + 49 ** 3 == 98 ** 3 == 941192,
8 ** 4 + 16 ** 3 == 2 ** 13 == 8192,
8 ** 5 + 32 ** 3 == 16 ** 4 == 65536,
9 ** 3 + 18 ** 3 == 9 ** 4 == 6561,
16 ** 5 + 32 ** 4 == 8 ** 7 == 2097152,
17 ** 4 + 34 ** 4 == 17 ** 5 == 1419857,
19 ** 4 + 38 ** 3 == 57 ** 3 == 185193,
27 ** 3 + 54 ** 3 == 3 ** 11 == 177147,
28 ** 3 + 84 ** 3 == 28 ** 4 == 614656,
34 ** 5 + 51 ** 4 == 85 ** 4 == 52200625}
```
I get nervous having an incorrect version of `gcd` around; let's change it back, quick!
```
from math import gcd
beal(100, 100)
```
We can also provide some test cases for the subfunctions of `beal`:
```
def tests():
assert make_Apowers(6, 10) == {
1: [1],
2: [8, 16, 32, 128],
3: [27, 81, 243, 2187],
4: [64, 256, 1024, 16384],
5: [125, 625, 3125, 78125],
6: [216, 1296, 7776, 279936]}
assert make_Czroots(make_Apowers(5, 8)) == {
1: 1, 8: 2, 16: 2, 27: 3, 32: 2, 64: 4, 81: 3,
125: 5, 128: 2, 243: 3, 256: 4, 625: 5, 1024: 4,
2187: 3, 3125: 5, 16384: 4, 78125: 5}
Czroots = make_Czroots(make_Apowers(100, 100))
assert 3 ** 3 + 6 ** 3 in Czroots
assert 99 ** 97 in Czroots
assert 101 ** 100 not in Czroots
assert Czroots[99 ** 97] == 99
assert exponent(10 ** 5, 10) == 5
assert exponent(7 ** 3, 7) == 3
assert exponent(1234 ** 999, 1234) == 999
assert exponent(12345 ** 6789, 12345) == 6789
assert exponent(3 ** 10000, 3) == 10000
assert exponent(1, 1) == 3
assert exponents_upto(2) == []
assert exponents_upto(3) == [3]
assert exponents_upto(4) == [3, 4]
assert exponents_upto(40) == [3, 4, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
assert exponents_upto(100) == [
3, 4, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97]
assert gcd(3, 6) == 3
assert gcd(3, 7) == 1
assert gcd(861591083269373931, 94815872265407) == 97
assert gcd(2*3*5*(7**10)*(11**12), 3*(7**5)*(11**13)*17) == 3*(7**5)*(11**12)
return 'tests pass'
tests()
```
The program is mostly straightforward, but relies on the correctness of these arguments:
* Are we justified in taking `combinations` without replacements from the `Apowers` table? In other words, are we sure there are no solutions of the form $A^x + A^x = C^z$? Yes, we can be sure, because then $2\;A^x = C^z$, and all the factors of $A$ would also be factors of $C$.
<p>
* Are we justified in having a single value for each key in the `Czroots` table? Consider that $81 = 3^4 = 9^2$. We put `{81: 3}` in the table and discard `{81: 9}`, because any number that has 9 as a factor will always have 3 as a factor as well, so 3 is all we need to know. But what if a number could be formed with two bases where neither was a multiple of the other? For example, what if $2^7 = 5^3 = s$; then wouldn't we have to have both 2 and 5 as values for $s$ in the table? Fortunately, that can never happen, because of the [fundamental theorem of arithmetic](https://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic).
<p>
* Could there be a rounding error involving the `exponent` function that was not caught by the tests? Possibly; but `exponent` is not used to find counterexamples, only to print them, so any such error wouldn't cause us to miss a counterexample.
<p>
* Are we justified in only considering exponents that are odd primes, or the number 4? In one sense, yes, because when we consider the two terms $A^{(qp)}$ and $(A^q)^p$, we find they are always equal, and always have the same prime factors (the factors of $A$), so for the purposes of the Beal problem, they are equivalent, and we only need consider one of them. In another sense, there is a difference. With this optimization, when we run `beal(6, 10)`, we are no longer testing $512$ as a value of $A$ or $B$, even though $512 = 2^9$ and both $2$ and $9$ are within range, because the program chooses to express $512$ as $8^3$, and $8$ is not in the specified range. So the program is still correctly searching for counterexamples, but the space that it searches for given `max_A` and `max_x` is different with this optimization.
<p>
* Are we really sure that when $A$ and $B$ have a common factor greater than 1, then
$C$ also shares that common factor? Yes, because if $p$ is a factor of both $A$ and $B$, then it is a factor of $A^x + B^y$, and since we know this is equal to $C^z$, then $p$ must also be a factor of $C^z$, and thus a factor of $C$.
# Faster Arithmetic (mod *p*)
Arithmetic is slow with integers that have thousands of digits. If we want to explore much further, we'll have to make the program more efficient. An obvious improvement would be to do all the arithmetic module some number $m$. Then we know:
$$\mbox{if} ~~
A^x + B^y = C^z
~~ \mbox{then} ~~
(A^x (\mbox{mod} ~ m) + B^y (\mbox{mod} ~ m)) (\mbox{mod} ~ m) = C^z \;(\mbox{mod} ~ m)$$
So we can do efficient tests modulo $m$, and then do the full arithmetic only for combinations that work modulo $m$. Unfortunately there will be collisions (two numbers that are distinct, but are equal mod $m$), so the tables will have to have lists of values. Here is a simple, unoptimized implementation:
```
from math import gcd
from itertools import combinations, product
from collections import defaultdict
def beal_modm(max_A, max_x, m=2**31-1):
"""See if any A ** x + B ** y equals some C ** z (mod p), with gcd(A, B) == 1.
If so, verify that the equation works without the (mod m).
Consider any 1 <= A,B <= max_A and x,y <= max_x, with x,y prime or 4."""
assert m >= max_A
Apowers = make_Apowers_modm(max_A, max_x, m)
Czroots = make_Czroots_modm(Apowers)
for (A, B) in combinations(Apowers, 2):
if gcd(A, B) == 1:
for (Axm, x), (Bym, y) in product(Apowers[A], Apowers[B]):
Czm = (Axm + Bym) % m
if Czm in Czroots:
lhs = A ** x + B ** y
for (C, z) in Czroots[Czm]:
if lhs == C ** z:
print('{} ** {} + {} ** {} == {} ** {} == {}'
.format(A, x, B, y, C, z, C ** z))
def make_Apowers_modm(max_A, max_x, m):
"A dict of {A: [(A**3 (mod m), 3), (A**4 (mod m), 4), ...]}."
exponents = exponents_upto(max_x)
return {A: [(pow(A, x, m), x) for x in (exponents if (A != 1) else [3])]
for A in range(1, max_A+1)}
def make_Czroots_modm(Apowers):
"A dict of {C**z (mod m): [(C, z),...]}"
Czroots = defaultdict(list)
for A in Apowers:
for (Axm, x) in Apowers[A]:
Czroots[Axm].append((A, x))
return Czroots
```
Here we see that each entry in the `Apowers` table is a list of `(A**x (mod p), x)` pairs.
For example, $6^7 = 279,936$, so in our (mod 1000) table we have the pair `(936, 7)` under `6`.
```
Apowers = make_Apowers_modm(6, 10, 1000)
Apowers
```
And each item in the `Czroots` table is of the form `{C**z (mod m): [(C, z), ...]}`.
For example, `936: [(6, 7)]`.
```
make_Czroots_modm(Apowers)
```
Let's run the program:
```
%time beal_modm(1000, 100)
```
We don't see a speedup here, but the idea is that as we start dealing with much larger integers, this version should be faster. I could improve this version by caching certain computations, managing the memory layout better, moving some computations out of loops, considering using multiple different numbers as the modulus (as in a Bloom filter), finding a way to parallelize the program, and re-coding in a faster compiled language (such as C++ or Go or Julia). Then I could invest thousands (or millions) of CPU hours searching for counterexamples.
But [Witold Jarnicki](https://plus.sandbox.google.com/+WitoldJarnicki/posts) and [David Konerding](http://www.konerding.com/~dek/) already did that: they wrote a C++ program that, in parallel across thousands of machines, searched for $A, B$ up to 200,000 and $x, y$ up to 5,000, but found no counterexamples. So I don't think it is worthwhile to continue on that path.
# Conclusion
This was fun, but I can't recommend anyone spend a serious amount of computer time looking for counterexamples to the Beal Conjecture—the money you would have to spend in computer time would be more than the expected value of your prize winnings. I suggest you work on a proof rather than a counterexample, or work on some other interesting problem instead!
| github_jupyter |
```
from hyppo.ksample import KSample
from hyppo.independence import Dcorr
from combat import combat
import pandas as pd
import glob
import os
import graspy as gp
import numpy as np
from dask.distributed import Client, progress
import dask.dataframe as ddf
from scipy.stats import zscore, rankdata, mannwhitneyu
import copy
import math
import networkx as nx
from graspy.models import SIEMEstimator as siem
def get_sub(fname):
stext = os.path.basename(fname).split('_')
return('{}_{}_{}'.format(stext[0], stext[1], stext[3]))
def get_sub_pheno_dat(subid, scan, pheno_dat):
matches = pheno_dat.index[pheno_dat["SUBID"] == int(subid)].tolist()
match = np.min(matches)
return(int(pheno_dat.iloc[match]["SEX"]))
def get_age_pheno_dat(subid, scan, pheno_dat):
matches = pheno_dat.index[pheno_dat["SUBID"] == int(subid)].tolist()
match = np.min(matches)
return(int(pheno_dat.iloc[match]["AGE_AT_SCAN_1"]))
def apply_along_dataset(scs, dsets, fn):
scs_xfmd = np.zeros(scs.shape)
for dset in np.unique(dsets):
scs_xfmd[dsets == dset,:] = np.apply_along_axis(fn, 0, scs[dsets == dset,:])
return(scs_xfmd)
def apply_along_individual(scs, fn):
scs_xfmd = np.zeros(scs.shape)
def zsc(x):
x_ch = copy.deepcopy(x)
if (np.var(x_ch) > 0):
x_ch = (x_ch - np.mean(x_ch))/np.std(x_ch)
return x_ch
else:
return np.zeros(x_ch.shape)
def ptr(x):
x_ch = copy.deepcopy(x)
nz = x[x != 0]
x_rank = rankdata(nz)*2/(len(nz) + 1)
x_ch[x_ch != 0] = x_rank
if (np.min(x_ch) != np.max(x_ch)):
x_ch = (x_ch - np.min(x_ch))/(np.max(x_ch) - np.min(x_ch))
return(x_ch)
basepath = '/mnt/nfs2/MR/cpac_3-9-2/'
pheno_basepath = '/mnt/nfs2/MR/all_mr/phenotypic/'
datasets = os.listdir(basepath)
try:
datasets.remove("phenotypic")
except:
print("No phenotypic folder in `datasets`.")
print(datasets)
fmri_dict = {}
pheno_dat = {}
for i, dataset in enumerate(datasets):
try:
try:
pheno_dat[dataset] = pd.read_csv('{}{}_phenotypic_data.csv'.format(pheno_basepath, dataset))
except:
raise ValueError("Dataset: {} does not have a phenotypic file.".format(dataset))
scan_dict = {}
sex_dict = []
age_dict = []
dset_dir = os.path.join('{}{}/graphs/FSL_nff_nsc_gsr_des'.format(basepath, dataset), '*.ssv')
files_ds = glob.glob(dset_dir)
successes = len(files_ds)
for f in files_ds:
try:
gr_dat = gp.utils.import_edgelist(f)
sub = get_sub(f)
scansub = sub.split('_')
sex = get_sub_pheno_dat(scansub[1], scansub[2], pheno_dat[dataset])
age = get_age_pheno_dat(scansub[1], scansub[2], pheno_dat[dataset])
scan_dict[sub] = gr_dat.flatten()
sex_dict.append(sex)
age_dict.append(age)
except Exception as e:
successes -= 1
print("Dataset: {} has {}/{} successes.".format(dataset, successes, len(files_ds)))
if (successes < 5):
raise ValueError("Dataset: {} does not have enough successes.".format(dataset))
fmri_dict[dataset] = {}
fmri_dict[dataset]["scans"] = np.vstack(list(scan_dict.values()))
fmri_dict[dataset]["subs"] = list(scan_dict.keys())
fmri_dict[dataset]["sex"] = sex_dict
fmri_dict[dataset]["age"] = age_dict
fmri_dict[dataset]["dataset"] = [i + 1 for j in range(0, fmri_dict[dataset]["scans"].shape[0])]
except Exception as e:
print("Error in {} Dataset.".format(dataset))
print(e)
def run_experiment(row):
try:
ds1 = row[0]; ds2 = row[1]; sxfm=row[2]; dxfm = row[3]
scans = np.vstack((fmri_dict[ds1]["scans"], fmri_dict[ds2]["scans"]))
scans = scans[:,~np.all(scans == 0, axis=0)]
sex = np.array(fmri_dict[ds1]["sex"] + fmri_dict[ds2]["sex"])
age = np.array(fmri_dict[ds1]["age"] + fmri_dict[ds2]["age"])
datasets = np.array([1 for i in range(0, fmri_dict[ds1]["scans"].shape[0])] + [2 for i in range(0, fmri_dict[ds2]["scans"].shape[0])])
# apply per-individual transform
if sxfm == "ptr":
scans = np.apply_along_axis(ptr, 1, scans)
# apply per-dataset edgewise transform
if dxfm == "raw":
scans = scans
elif dxfm == "zscore":
scans = apply_along_dataset(scans, datasets, zsc)
elif dxfm == "ptr":
scans = apply_along_dataset(scans, datasets, ptr)
elif dxfm == "combat":
scans = np.array(combat(pd.DataFrame(scans.T), datasets, model=None, numerical_covariates=None)).T
try:
eff_batch = KSample("DCorr").test(scans[datasets == 1,:], scans[datasets == 2,:])
except:
eff_batch = (None, None)
try:
eff_sex = KSample("DCorr").test(scans[sex == 1,:], scans[sex == 2,:])
except:
eff_sex = (None, None)
try:
eff_age = Dcorr().test(scans, age)
except:
eff_age = (None, None)
except:
eff_batch = (None, None)
eff_sex = (None, None)
eff_age = (None, None)
return (row[0], row[1], row[2], row[3], eff_batch[0], eff_batch[1], eff_sex[0], eff_sex[1], eff_age[0], eff_age[1])
```
# Experiments
## Effects
```
ncores = 99
client = Client(threads_per_worker=1, n_workers=ncores)
exps = []
datasets = list(fmri_dict.keys())
for sxfm in ["raw", "ptr"]:
for i, ds1 in enumerate(datasets):
for j in range(i+1, len(datasets)):
for dxfm in ["raw", "ptr", "zscore", "combat"]:
exps.append([ds1, datasets[j], sxfm, dxfm])
sim_exps = pd.DataFrame(exps, columns=["Dataset1", "Dataset2", "Sxfm", "Dxfm"])
print(sim_exps.head(n=30))
sim_exps = ddf.from_pandas(sim_exps, npartitions=ncores)
sim_results = sim_exps.apply(lambda x: run_experiment(x), axis=1, result_type='expand',
meta={0: str, 1: str, 2: str, 3: str, 4: float, 5: float, 6: float, 7: float,
8: float, 9: float})
sim_results
sim_results = sim_results.compute(scheduler="multiprocessing")
sim_results = sim_results.rename(columns={0: "Dataset1", 1: "Dataset2", 2: "Sxfm", 3: "Dxfm", 4: "Effect.Batch",
5: "pvalue.Batch", 6: "Effect.Sex", 7: "pvalue.Sex",
8: "Effect.Age", 9: "pvalue.Age"})
sim_results.to_csv('../data/dcorr/batch_results.csv')
sim_results.head(n=20)
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
from plotnine import *
from datetime import datetime
import pytz
%matplotlib inline
memory_free = pd.read_parquet("path to machine metric dataset/node_memory_MemFree/")
memory_free = memory_free / (1024 * 1024 * 1024)
memory_total = pd.read_parquet("path to machine metric dataset/node_memory_MemTotal/")
memory_total = memory_total / (1024 * 1024 * 1024)
# print(memory_total.values.max())
# print(len(memory_total.columns))
for c in memory_total.columns:
if memory_total[c].max() >= 257:
print(c)
mem_used_df = pd.read_parquet("path to machine metric dataset/node_memory_MemTotal%20-%20node_memory_MemFree%20-%20node_memory_Buffers%20-%20node_memory_Cached%20-%20node_memory_Slab%20-%20node_memory_PageTables%20-%20node_memory_SwapCached/")
mem_used_df = mem_used_df / (1024 * 1024 * 1024)
print(mem_used_df.max().max())
# memory_used_fraction_df = 1 - (df / mem_total_df)
mean_memory_per_node = mem_used_df.mean() * 100
# TODO: rewrite this. Devide based on index and the column names to get the true utilization levels.
fig = plt.figure(figsize=(40,12))
ax = mean_memory_per_node.plot.hist(bins=math.ceil(mean_memory_per_node.max()))
ax.set_xlim(0,)
ax.set_xlabel("Mean Memory Utilization (%)", fontsize=40)
ax.set_ylabel("Frequency", fontsize=40)
ax.tick_params(axis='both', which='major', labelsize=40)
ax.tick_params(axis='both', which='minor', labelsize=32)
ax.set_title("Histogram of Mean Memory Utilization in LISA", fontsize=50)
plt.savefig("mean_memory_utilization_percentage.pdf")
def normalize(df):
df = df.value_counts(sort=False, normalize=True).rename_axis('target').reset_index(name='pdf')
df["cdf"] = df["pdf"].cumsum()
return df
all_values_df = pd.DataFrame({"target": mem_used_df.values.ravel()})
count_df = normalize(all_values_df)
del all_values_df
# Add a row at the start so that the CDF starts at 0 and ends at 1 (in case we only have one datapoint in the DF)
plot_df = count_df.copy()
plot_df.index = plot_df.index + 1 # shifting index
plot_df.reset_index(inplace=True)
plot_df['index'] = plot_df['index'] + 1
plot_df.loc[0] = [0, -math.inf, 0, 0] # add a row at the start (index, count, pdf, cdf)
plot_df.loc[len(plot_df)] = [len(plot_df), math.inf, 1, 1]
plot_df.sort_index(inplace=True)
ggplt = ggplot(plot_df) + \
theme_light(base_size=18) + \
theme(figure_size = (8,3)) + \
geom_step(aes(x="target", y="cdf"), size=1) +\
xlab("Node RAM Usage [GB]") + \
ylab("ECDF")
marker_x = [96, 192, 256, 1024, 2048]
marker_y = []
for i in marker_x:
marker_y.append(count_df[count_df['target'].le(i) | np.isclose(count_df['target'], i, rtol=1e-10, atol=1e-12)].tail(1)['cdf'].iloc[0])
marker_labels = ["96GB", "192GB", "256GB", "1TB", "2TB"]
markers = ['o', 'v', 'p', 's', 'd']
fig = ggplt.draw(return_ggplot=False)
ax = plt.gca()
for x_pos, y_pos, marker_symbol, marker_label in zip(marker_x, marker_y, markers, marker_labels):
ax.scatter(x_pos, y_pos, marker=marker_symbol, label=marker_label, facecolors="None", edgecolors="black")
ax.legend(ncol=len(marker_x), loc=4, prop={'size': 10})
date_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
fig.tight_layout()
fig.savefig("memory_usage_cdf_nodes_{}.pdf".format(date_time))
count_df
t = '''\\begin{{table}}[]
\\caption{{RAM usage (GB) per percentage within Lisa.}}
\\label{{surfing:tbl:ram-usage-percentiles}}
\\begin{{tabular}}{{@{{}}lrrrrrrr@{{}}}}
\\toprule
& 1\\% & 25\\% & 50\\% & 75\\% & 90\\% & 99\\% & 100\\% \\\\ \\midrule
RAM & {0} & {1} & {2} & {3} & {4} & {5} & {6} \\\\ \\bottomrule
\\end{{tabular}}
\\end{{table}}'''
# print(count_df[-1:]['cdf'] - 1.0)
# print(count_df[-1:]['cdf'] >= 1.0)
# print(count_df[-1:]['cdf'].ge(1.0))
# print(np.isclose(count_df[-5:]['cdf'], 1.0, rtol=1e-10, atol=1e-12))
# print(count_df[count_df['cdf'].ge(0.25) | np.isclose(count_df['cdf'], .25, rtol=1e-10, atol=1e-12)].iloc[0])
percentages = [0.01, 0.25, 0.50, 0.75, 0.90, 0.99, 1]
values = []
for p in percentages:
values.append(count_df[count_df['cdf'].ge(p) | np.isclose(count_df['cdf'], p, rtol=1e-8, atol=1e-12)].iloc[0]['target'])
print(t.format(*["{:.2f}".format(v) for v in values]))
t = '''\\begin{{table}}[]
\\caption{{Fraction of RAM usage below or at specified level.}}
\\label{{surfing:tbl:ram-usage-fraction}}
\\begin{{tabular}}{{@{{}}lrrrrrr@{{}}}}
\\toprule
& 96GB & 192GB & 256GB & 1TB & 2TB \\\\ \\midrule
Percentage & {0} & {1} & {2} & {3} & {4} \\\\ \\bottomrule
\\end{{tabular}}
\\end{{table}}'''
RAMs = [96, 192, 256, 1024, 2048]
values = []
for r in RAMs:
values.append(count_df[count_df['target'].le(r) | np.isclose(count_df['target'], r, rtol=1e-10, atol=1e-12)].tail(1)['cdf'].iloc[0])
print(t.format(*["{:.2f}".format(v) for v in values]))
# This cell outputs the special node 1128 in rack 1128, the 2TB RAM node
# Unobfuscated it is r23n23
memory_free_1128 = memory_free['r23n23']
memory_total_1128 = memory_total['r23n23']
df_1128 = memory_free_1128.to_frame(name = 'free').join(memory_total_1128.to_frame(name='total')).replace(-1, np.NaN)
df_1128['util'] = 1 - (df_1128['free'] / df_1128['total'])
df_1128["dt"] = pd.to_datetime(df_1128.index, utc=True, unit="s")
df_1128["dt"] = df_1128["dt"].dt.tz_convert(pytz.timezone('Europe/Amsterdam')).dt.tz_localize(None)
df_1128 = df_1128.set_index("dt")
df_1128['util']
def get_converted_xticks(ax):
"""
:param ax:
:return list of day and month strings
"""
return [pd.to_datetime(tick.get_text()).date().strftime("%d\n%b") for tick in ax.get_xticklabels()]
median = df_1128['util'].median() * 100
median_zeroes_filtered = df_1128['util'][df_1128['util'] > 0].median() * 100
avg = df_1128['util'].mean() * 100
print(median, avg)
# print(df_1128['util'])
fig, ax = plt.subplots(figsize=(11, 5))
ax.plot(df_1128['util'] * 100, color="lightcoral")
ax.set_ylabel("RAM Utilization [%]", fontsize=18)
ax.set_xlabel("", fontsize=14)
ax.tick_params(axis='both', which='major', labelsize=16)
ax.tick_params(axis='both', which='minor', labelsize=16)
ax.axhline(avg, label="Average ({:.3f})".format(avg), color="steelblue", linestyle="solid")
ax.axhline(median, label="Median ({:.3f})".format(median), color="yellowgreen", linestyle="dashed")
ax.axhline(median_zeroes_filtered, label="Median zeros filtered ({:.3f})".format(median_zeroes_filtered), color="black", linestyle="dotted")
ax.legend(ncol=3, prop={"size": 14}, bbox_to_anchor=(0.5, 1.15), loc=9)
fig.tight_layout()
# This call needs to be after the tight_layout call so that the labels have been set!
ax.set_xticklabels(get_converted_xticks(ax))
date_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
fig.savefig("ram_utilization_node1128_{}.pdf".format(date_time), bbox_inches='tight')
```
| github_jupyter |
# Settings
```
%env TF_KERAS = 1
import os
sep_local = os.path.sep
import sys
sys.path.append('..'+sep_local+'..')
print(sep_local)
os.chdir('..'+sep_local+'..'+sep_local+'..'+sep_local+'..'+sep_local+'..')
print(os.getcwd())
import tensorflow as tf
print(tf.__version__)
```
# Dataset loading
```
dataset_name='Dstripes'
import tensorflow as tf
train_ds = tf.data.Dataset.from_generator(
lambda: training_generator,
output_types=tf.float32 ,
output_shapes=tf.TensorShape((batch_size, ) + image_size)
)
test_ds = tf.data.Dataset.from_generator(
lambda: testing_generator,
output_types=tf.float32 ,
output_shapes=tf.TensorShape((batch_size, ) + image_size)
)
_instance_scale=1.0
for data in train_ds:
_instance_scale = float(data[0].numpy().max())
break
_instance_scale
import numpy as np
from collections.abc import Iterable
if isinstance(inputs_shape, Iterable):
_outputs_shape = np.prod(inputs_shape)
_outputs_shape
```
# Model's Layers definition
```
units=20
c=50
menc_lays = [
tf.keras.layers.Conv2D(filters=units//2, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Conv2D(filters=units*9//2, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Flatten(),
# No activation
tf.keras.layers.Dense(latents_dim)
]
venc_lays = [
tf.keras.layers.Conv2D(filters=units//2, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Conv2D(filters=units*9//2, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Flatten(),
# No activation
tf.keras.layers.Dense(latents_dim)
]
dec_lays = [
tf.keras.layers.Dense(units=units*c*c, activation=tf.nn.relu),
tf.keras.layers.Reshape(target_shape=(c , c, units)),
tf.keras.layers.Conv2DTranspose(filters=units, kernel_size=3, strides=(2, 2), padding="SAME", activation='relu'),
tf.keras.layers.Conv2DTranspose(filters=units*3, kernel_size=3, strides=(2, 2), padding="SAME", activation='relu'),
# No activation
tf.keras.layers.Conv2DTranspose(filters=3, kernel_size=3, strides=(1, 1), padding="SAME")
]
```
# Model definition
```
model_name = dataset_name+'VAE_Convolutional_reconst_1ell_01psnr'
experiments_dir='experiments'+sep_local+model_name
from training.autoencoding_basic.autoencoders.VAE import VAE as AE
inputs_shape=image_size
variables_params = \
[
{
'name': 'inference_mean',
'inputs_shape':inputs_shape,
'outputs_shape':latents_dim,
'layers': menc_lays
}
,
{
'name': 'inference_logvariance',
'inputs_shape':inputs_shape,
'outputs_shape':latents_dim,
'layers': venc_lays
}
,
{
'name': 'generative',
'inputs_shape':latents_dim,
'outputs_shape':inputs_shape,
'layers':dec_lays
}
]
from utils.data_and_files.file_utils import create_if_not_exist
_restore = os.path.join(experiments_dir, 'var_save_dir')
create_if_not_exist(_restore)
_restore
#to restore trained model, set filepath=_restore
ae = AE(
name=model_name,
latents_dim=latents_dim,
batch_size=batch_size,
variables_params=variables_params,
filepath=None
)
from evaluation.quantitive_metrics.peak_signal_to_noise_ratio import prepare_psnr
from statistical.losses_utilities import similarty_to_distance
from statistical.ae_losses import expected_loglikelihood_with_lower_bound as ellwlb
ae.compile(loss={'x_logits': lambda x_true, x_logits: ellwlb(x_true, x_logits)+ 0.1*similarity_to_distance(prepare_psnr([ae.batch_size]+ae.get_inputs_shape()))(x_true, x_logits)})
```
# Callbacks
```
from training.callbacks.sample_generation import SampleGeneration
from training.callbacks.save_model import ModelSaver
es = tf.keras.callbacks.EarlyStopping(
monitor='loss',
min_delta=1e-12,
patience=12,
verbose=1,
restore_best_weights=False
)
ms = ModelSaver(filepath=_restore)
csv_dir = os.path.join(experiments_dir, 'csv_dir')
create_if_not_exist(csv_dir)
csv_dir = os.path.join(csv_dir, ae.name+'.csv')
csv_log = tf.keras.callbacks.CSVLogger(csv_dir, append=True)
csv_dir
image_gen_dir = os.path.join(experiments_dir, 'image_gen_dir')
create_if_not_exist(image_gen_dir)
sg = SampleGeneration(latents_shape=latents_dim, filepath=image_gen_dir, gen_freq=5, save_img=True, gray_plot=False)
```
# Model Training
```
ae.fit(
x=train_ds,
input_kw=None,
steps_per_epoch=int(1e4),
epochs=int(1e6),
verbose=2,
callbacks=[ es, ms, csv_log, sg],
workers=-1,
use_multiprocessing=True,
validation_data=test_ds,
validation_steps=int(1e4)
)
```
# Model Evaluation
## inception_score
```
from evaluation.generativity_metrics.inception_metrics import inception_score
is_mean, is_sigma = inception_score(ae, tolerance_threshold=1e-6, max_iteration=200)
print(f'inception_score mean: {is_mean}, sigma: {is_sigma}')
```
## Frechet_inception_distance
```
from evaluation.generativity_metrics.inception_metrics import frechet_inception_distance
fis_score = frechet_inception_distance(ae, training_generator, tolerance_threshold=1e-6, max_iteration=10, batch_size=32)
print(f'frechet inception distance: {fis_score}')
```
## perceptual_path_length_score
```
from evaluation.generativity_metrics.perceptual_path_length import perceptual_path_length_score
ppl_mean_score = perceptual_path_length_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200, batch_size=32)
print(f'perceptual path length score: {ppl_mean_score}')
```
## precision score
```
from evaluation.generativity_metrics.precision_recall import precision_score
_precision_score = precision_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)
print(f'precision score: {_precision_score}')
```
## recall score
```
from evaluation.generativity_metrics.precision_recall import recall_score
_recall_score = recall_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)
print(f'recall score: {_recall_score}')
```
# Image Generation
## image reconstruction
### Training dataset
```
%load_ext autoreload
%autoreload 2
from training.generators.image_generation_testing import reconstruct_from_a_batch
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'reconstruct_training_images_like_a_batch_dir')
create_if_not_exist(save_dir)
reconstruct_from_a_batch(ae, training_generator, save_dir)
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'reconstruct_testing_images_like_a_batch_dir')
create_if_not_exist(save_dir)
reconstruct_from_a_batch(ae, testing_generator, save_dir)
```
## with Randomness
```
from training.generators.image_generation_testing import generate_images_like_a_batch
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'generate_training_images_like_a_batch_dir')
create_if_not_exist(save_dir)
generate_images_like_a_batch(ae, training_generator, save_dir)
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'generate_testing_images_like_a_batch_dir')
create_if_not_exist(save_dir)
generate_images_like_a_batch(ae, testing_generator, save_dir)
```
### Complete Randomness
```
from training.generators.image_generation_testing import generate_images_randomly
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'random_synthetic_dir')
create_if_not_exist(save_dir)
generate_images_randomly(ae, save_dir)
from training.generators.image_generation_testing import interpolate_a_batch
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'interpolate_dir')
create_if_not_exist(save_dir)
interpolate_a_batch(ae, testing_generator, save_dir)
```
| github_jupyter |
# Inspecting ModelSelectorResult
When we go down from multiple time-series to single time-series, the best way how to get access to all relevant information to use/access `ModelSelectorResult` objects
```
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn')
plt.rcParams['figure.figsize'] = [12, 6]
from hcrystalball.model_selection import ModelSelector
from hcrystalball.utils import get_sales_data
from hcrystalball.wrappers import get_sklearn_wrapper
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
df = get_sales_data(n_dates=365*2,
n_assortments=1,
n_states=1,
n_stores=2)
df.head()
# let's start simple
df_minimal = df[['Sales']]
ms_minimal = ModelSelector(frequency='D', horizon=10)
ms_minimal.create_gridsearch(
n_splits=2,
between_split_lag=None,
sklearn_models=False,
sklearn_models_optimize_for_horizon=False,
autosarimax_models=False,
prophet_models=False,
tbats_models=False,
exp_smooth_models=False,
average_ensembles=False,
stacking_ensembles=False)
ms_minimal.add_model_to_gridsearch(get_sklearn_wrapper(LinearRegression, hcb_verbose=False))
ms_minimal.add_model_to_gridsearch(get_sklearn_wrapper(RandomForestRegressor, random_state=42, hcb_verbose=False))
ms_minimal.select_model(df=df_minimal, target_col_name='Sales')
```
## Ways to access ModelSelectorResult
There are three ways how you can get to single time-series result level.
- First is over `.results[i]`, which is fast, but does not ensure, that results are loaded in the same order as when they were created (reason for that is hash used in the name of each result, that are later read in alphabetic order)
- Second and third uses `.get_result_for_partition()` through `dict` based partition
- Forth does that using `partition_hash` (also in results file name if persisted)
```
result = ms_minimal.results[0]
result = ms_minimal.get_result_for_partition({'no_partition_label': ''})
result = ms_minimal.get_result_for_partition(ms_minimal.partitions[0])
result = ms_minimal.get_result_for_partition('fb452abd91f5c3bcb8afa4162c6452c2')
```
## ModelSelectorResult is rich
As you can see below, we try to store all relevant information to enable easy access to data, that is otherwise very lenghty.
```
result
```
### Traning data
```
result.X_train
result.y_train
```
### Data behind plots
Ready to be plotted or adjusted to your needs
```
result.df_plot
result.df_plot.tail(50).plot();
result
```
## Best Model Metadata
That can help to filter for example `cv_data` or to get a glimpse on which parameters the best model has
```
result.best_model_hash
result.best_model_name
result.best_model_repr
```
### CV Results
Get information about how our model behaved in cross validation
```
result.best_model_cv_results['mean_fit_time']
```
Or how all the models behaved
```
result.cv_results.sort_values('rank_test_score').head()
```
### CV Data
Access predictions made during cross validation with possible cv splits and true target values
```
result.cv_data.head()
result.cv_data.drop(['split'], axis=1).plot();
result.best_model_cv_data.head()
result.best_model_cv_data.plot();
```
## Plotting Functions
With `**plot_params` that you can pass depending on your plotting backend
```
result.plot_result(plot_from='2015-06', title='Performance', color=['blue','green']);
result.plot_error(title='Error');
```
## Convenient Persist Method
```
result.persist?
```
| github_jupyter |
# NumPy
this notebook is based on the SciPy NumPy tutorial
<div class="alert alert-block alert-warning">
Note that the traditional way to import numpy is to rename it np. This saves on typing and makes your code a little more compact.</div>
```
import numpy as np
```
NumPy provides a multidimensional array class as well as a _large_ number of functions that operate on arrays.
NumPy arrays allow you to write fast (optimized) code that works on arrays of data. To do this, there are some restrictions on arrays:
* all elements are of the same data type (e.g. float)
* the size of the array is fixed in memory, and specified when you create the array (e.g., you cannot grow the array like you do with lists)
The nice part is that arithmetic operations work on entire arrays—this means that you can avoid writing loops in python (which tend to be slow). Instead the "looping" is done in the underlying compiled code
## Array Creation and Properties
There are a lot of ways to create arrays. Let's look at a few
Here we create an array using `arange` and then change its shape to be 3 rows and 5 columns. Note the _row-major ordering_—you'll see that the rows are together in the inner `[]` (more on this in a bit)
```
a = np.arange(15)
a
a = np.arange(15).reshape(3,5)
print(a)
```
an array is an object of the `ndarray` class, and it has methods that know how to work on the array data. Here, `.reshape()` is one of the many methods.
A NumPy array has a lot of meta-data associated with it describing its shape, datatype, etc.
```
print(a.ndim)
print(a.shape)
print(a.size)
print(a.dtype)
print(a.itemsize)
print(type(a))
help(a)
```
we can also create an array from a list
```
b = np.array( [1.0, 2.0, 3.0, 4.0] )
print(b)
print(b.dtype)
print(type(b))
```
we can create a multi-dimensional array of a specified size initialized all to 0 easily, using the `zeros()` function.
```
b = np.zeros((10,8))
b
```
There is also an analogous ones() and empty() array routine. Note that here we can explicitly set the datatype for the array in this function if we wish.
Unlike lists in python, all of the elements of a numpy array are of the same datatype
```
c = np.eye(10, dtype=np.float64)
c
```
`linspace` creates an array with evenly space numbers. The `endpoint` optional argument specifies whether the upper range is in the array or not
```
d = np.linspace(0, 1, 10, endpoint=False)
print(d)
```
<div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3>
Analogous to `linspace()`, there is a `logspace()` function that creates an array with elements equally spaced in log. Use `help(np.logspace)` to see the arguments, and create an array with 10 elements from $10^{-6}$ to $10^3$.
</div>
we can also initialize an array based on a function
```
f = np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
f
```
## Array Operations
most operations (`+`, `-`, `*`, `/`) will work on an entire array at once, element-by-element.
Note that that the multiplication operator is not a matrix multiply (there is a new operator in python 3.5+, `@`, to do matrix multiplicaiton.
Let's create a simply array to start with
```
a = np.arange(12).reshape(3,4)
print(a)
```
Multiplication by a scalar multiplies every element
```
a*2
```
adding two arrays adds element-by-element
```
a + a
```
multiplying two arrays multiplies element-by-element
```
a*a
```
<div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3>
What do you think `1./a` will do? Try it and see
</div>
We can think of our 2-d array as a 3 x 4 matrix (3 rows, 4 columns). We can take the transpose to geta 4 x 3 matrix, and then we can do a matrix multiplication
```
b = a.transpose()
b
a @ b
```
We can sum the elements of an array:
```
a.sum()
```
<div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3>
`sum()` takes an optional argument, `axis=N`, where `N` is the axis to sum over. Sum the elements of `a` across rows to create an array with just the sum along each column of `a`.
</div>
We can also easily get the extrema
```
print(a.min(), a.max())
```
## Universal functions
universal functions work element-by-element. Let's create a new array scaled by `pi`
```
b = a*np.pi/12.0
print(b)
c = np.cos(b)
print(c)
d = b + c
print(d)
```
<div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3>
We will often want to write our own function that operates on an array and returns a new array. We can do this just like we did with functions previously—the key is to use the methods from the `np` module to do any operations, since they work on, and return, arrays.
Write a simple function that returns $\sin(2\pi x)$ for an input array `x`. Then test it
by passing in an array `x` that you create via `linspace()`
</div>
## Slicing
slicing works very similarly to how we saw with strings. Remember, python uses 0-based indexing

Let's create this array from the image:
```
a = np.arange(9)
a
```
Now look at accessing a single element vs. a range (using slicing)
Giving a single (0-based) index just references a single value
```
a[2]
```
Giving a range uses the range of the edges to return the values
```
print(a[2:3])
a[2:4]
```
The `:` can be used to specify all of the elements in that dimension
```
a[:]
```
## Multidimensional Arrays
Multidimensional arrays are stored in a contiguous space in memory -- this means that the columns / rows need to be unraveled (flattened) so that it can be thought of as a single one-dimensional array. Different programming languages do this via different conventions:

Storage order:
* Python/C use *row-major* storage: rows are stored one after the other
* Fortran/matlab use *column-major* storage: columns are stored one after another
The ordering matters when
* passing arrays between languages (we'll talk about this later this semester)
* looping over arrays -- you want to access elements that are next to one-another in memory
* e.g, in Fortran:
```
double precision :: A(M,N)
do j = 1, N
do i = 1, M
A(i,j) = …
enddo
enddo
```
* in C
```
double A[M][N];
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
A[i][j] = …
}
}
```
In python, using NumPy, we'll try to avoid explicit loops over elements as much as possible
Let's look at multidimensional arrays:
```
a = np.arange(15).reshape(3,5)
a
```
Notice that the output of `a` shows the row-major storage. The rows are grouped together in the inner `[...]`
Giving a single index (0-based) for each dimension just references a single value in the array
```
a[1,1]
```
Doing slices will access a range of elements. Think of the start and stop in the slice as referencing the left-edge of the slots in the array.
```
a[0:2,0:2]
```
Access a specific column
```
a[:,1]
```
Sometimes we want a one-dimensional view into the array -- here we see the memory layout (row-major) more explicitly
```
a.flatten()
```
we can also iterate -- this is done over the first axis (rows)
```
for row in a:
print(row)
```
or element by element
```
for e in a.flat:
print(e)
```
Generally speaking, we want to avoid looping over the elements of an array in python—this is slow. Instead we want to write and use functions that operate on the entire array at once.
<div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3>
Consider the array defined as:
```
q = np.array([[1, 2, 3, 2, 1],
[2, 4, 4, 4, 2],
[3, 4, 4, 4, 3],
[2, 4, 4, 4, 2],
[1, 2, 3, 2, 1]])
```
* using slice notation, create an array that consists of only the `4`'s in `q` (this will be called a _view_, as we'll see shortly)
* zero out all of the elements in your view
* how does `q` change?
</div>
| github_jupyter |
# Introduction to Spark
## Basic initialization
`SparkSession` is used to connect to the Spark Cluster.
```
from pyspark.sql import SparkSession
```
We will use Pandas to operate on the reduced data in the *driver program*.
```
import pandas as pd
```
Numpy will be always useful.
```
import numpy as np
```
Create a new session (or reuse an existing one).
```
spark = SparkSession.builder.getOrCreate()
spark
```
We can see that the session is established.
## Creating Spark Data Frames from Pandas
We can list the tables in our Spark Session, currently empty.
```
print(spark.catalog.listTables())
```
We can create a Pandas `DataFrame` with random values.
```
pd_temp = pd.DataFrame(np.random.random(100))
```
We can see on the plot that it is really random:
```
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
pd_temp.plot()
```
Now we can convert it into Spark DataFrame:
```
spark_temp = spark.createDataFrame(pd_temp)
```
`createOrReplaceTempView` creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a table in Spark SQL.
It does not persist to memory unless you cache (persist) the dataset that underpins the view.
```
spark_temp.createOrReplaceTempView("temp")
```
The created view is `TEMPORARY` which means it is not persistent.
```
print(spark.catalog.listTables())
spark_temp.show()
```
We can now use transformations on this DataFrame. The transformations are translated (compiled) to RDD transformations.
```
from pyspark.sql.functions import col, asc
spark_temp.filter((col('0') > 0.9)).show()
```
## Creating Spark Data Frames from input files
```
file_path = "airports.csv"
# Read in the airports data
airports = spark.read.csv(file_path,header=True)
# Show the data
print(airports.show())
```
It may be useful to convert them to Pandas for quick browsing.
**Warning!** This is not efficient for large datasets, as it requires performing actions on the dataset.
```
airports.toPandas()
```
### Running SQL queries on dataframes
```
airports.createOrReplaceTempView("airports")
# Get the first 10 rows of flights
query = "FROM airports SELECT * LIMIT 10"
airports10 = spark.sql(query)
# Show the results
airports10.show()
```
### More complex examples
Read data from CSV file:
* `inferSchema` - to detect which columns are numbers (not strigs!) - useful e.g. for sorting.
* `header` - to read the firs line as column names
```
countries = spark.read.csv("countries of the world.csv",inferSchema=True,header=True)
countries.toPandas()
```
We can inspect the schema of the DataFrame.
```
countries.printSchema()
```
### Examples of SQL Queries
```
countries.createOrReplaceTempView("countries")
spark.sql("SELECT * FROM countries WHERE Region LIKE '%OCEANIA%'").toPandas()
```
### Queries using PySpark DSL
DSL = Domain Specific Language - API similar to natural or other language, implemented as library in another language.
List all the countries with the population > 38 million
```
countries.filter((col("Population") > 38000000)).orderBy("Population").toPandas()
```
Select all the countries from Europe
```
countries.select("Country", "Population").where(col("Region").like("%EUROPE%")).show()
```
Conditions in `where` clause can contain logical expressions.
```
countries.select("Country", "Population")\
.where((col("Region").like("%EUROPE%")) & (col("Population")> 10000000)).show()
```
### Aggregation
We can run aggregations with predefined functions (faster!):
```
from pyspark.sql.functions import sum
pd_countries = countries.select("Region", "Population").groupBy("Region").agg(sum("Population")).toPandas()
pd_countries
```
We can make the column name look better, by using `alias`:
```
pd_countries = countries.select("Region", "Population").groupBy("Region").agg(sum("Population").alias('Total')).toPandas()
pd_countries
```
### Plot examples
Pandas DataFrames are useful for plotting using MatPlotLib:
```
pd_countries.plot(x='Region', y='Total',kind='bar', figsize=(10, 6))
```
## User defined functions for data manipulation
Our `countries` DataFrame has some problems:
* missing values
* some numbers use comma instead of point as floating point separator (e.g. Literacy = 99,4)
We can clean the data using User Defined Functions (UDF)
```
from pyspark.sql.types import FloatType
from pyspark.sql.functions import udf
```
Define a Python function which coverts numbers with commas to `float`
```
def to_float (s) :
return float(s.replace(',','.'))
```
Test that it works:
```
to_float('0,99')
```
Now define a Spark UDF:
```
float_udf = udf(to_float , FloatType())
```
Test it on a Data Frame
```
countries.withColumn("Literacy", float_udf("Literacy (%)"))
```
OK, we can see that the `Literacy` is now `float`
```
countries.show(50)
countries.where((col("Literacy") < 50) & (col("GDP ($ per capita)") > 700)).show()
```
Oops, what does it mean???
- some rows have empty values!
Before we can use the table, we need to remove empty rows. Otherwise our UDF will fail.
```
full_countries = countries.select('Country', 'Population', 'Literacy (%)', 'GDP ($ per capita)').na.drop()
```
We can now apply the new UDF to the Data Frame:
```
full_countries = full_countries.withColumn("Literacy", float_udf("Literacy (%)"))
full_countries.show(50)
full_countries.where((col("Literacy") < 50) & (col("GDP ($ per capita)") > 700)).show()
full_countries.toPandas().plot(x="Literacy",y="GDP ($ per capita)",kind="scatter",figsize=(10, 6))
```
# Useful information
* https://spark.apache.org/docs/latest/quick-start.html
* https://spark.apache.org/docs/latest/sql-programming-guide.html
* https://pandas.pydata.org/pandas-docs/stable/visualization.html
| github_jupyter |
# 机器学习工程师纳米学位
## 模型评价与验证
## 项目 1: 预测波士顿房价
欢迎来到机器学习工程师纳米学位的第一个项目!在此文件中,有些示例代码已经提供给你,但你还需要实现更多的功能来让项目成功运行。除非有明确要求,你无须修改任何已给出的代码。以**'练习'**开始的标题表示接下来的内容中有需要你必须实现的功能。每一部分都会有详细的指导,需要实现的部分也会在注释中以**'TODO'**标出。请仔细阅读所有的提示!
除了实现代码外,你还**必须**回答一些与项目和实现有关的问题。每一个需要你回答的问题都会以**'问题 X'**为标题。请仔细阅读每个问题,并且在问题后的**'回答'**文字框中写出完整的答案。你的项目将会根据你对问题的回答和撰写代码所实现的功能来进行评分。
>**提示:**Code 和 Markdown 区域可通过 **Shift + Enter** 快捷键运行。此外,Markdown可以通过双击进入编辑模式。
## 开始
在这个项目中,你将利用马萨诸塞州波士顿郊区的房屋信息数据训练和测试一个模型,并对模型的性能和预测能力进行测试。通过该数据训练后的好的模型可以被用来对房屋做特定预测---尤其是对房屋的价值。对于房地产经纪等人的日常工作来说,这样的预测模型被证明非常有价值。
此项目的数据集来自[UCI机器学习知识库](https://archive.ics.uci.edu/ml/datasets/Housing)。波士顿房屋这些数据于1978年开始统计,共506个数据点,涵盖了麻省波士顿不同郊区房屋14种特征的信息。本项目对原始数据集做了以下处理:
- 有16个`'MEDV'` 值为50.0的数据点被移除。 这很可能是由于这些数据点包含**遗失**或**看不到的值**。
- 有1个数据点的 `'RM'` 值为8.78. 这是一个异常值,已经被移除。
- 对于本项目,房屋的`'RM'`, `'LSTAT'`,`'PTRATIO'`以及`'MEDV'`特征是必要的,其余不相关特征已经被移除。
- `'MEDV'`特征的值已经过必要的数学转换,可以反映35年来市场的通货膨胀效应。
运行下面区域的代码以载入波士顿房屋数据集,以及一些此项目所需的Python库。如果成功返回数据集的大小,表示数据集已载入成功。
```
# Import libraries necessary for this project
# 载入此项目所需要的库
import numpy as np
import pandas as pd
import visuals as vs # Supplementary code
from sklearn.model_selection import ShuffleSplit
# Pretty display for notebooks
# 让结果在notebook中显示
%matplotlib inline
# Load the Boston housing dataset
# 载入波士顿房屋的数据集
data = pd.read_csv('housing.csv')
prices = data['MEDV']
features = data.drop('MEDV', axis = 1)
# Success
# 完成
print "Boston housing dataset has {} data points with {} variables each.".format(*data.shape)
```
## 分析数据
在项目的第一个部分,你会对波士顿房地产数据进行初步的观察并给出你的分析。通过对数据的探索来熟悉数据可以让你更好地理解和解释你的结果。
由于这个项目的最终目标是建立一个预测房屋价值的模型,我们需要将数据集分为**特征(features)**和**目标变量(target variable)**。**特征** `'RM'`, `'LSTAT'`,和 `'PTRATIO'`,给我们提供了每个数据点的数量相关的信息。**目标变量**:` 'MEDV'`,是我们希望预测的变量。他们分别被存在`features`和`prices`两个变量名中。
## 练习:基础统计运算
你的第一个编程练习是计算有关波士顿房价的描述统计数据。我们已为你导入了` numpy `,你需要使用这个库来执行必要的计算。这些统计数据对于分析模型的预测结果非常重要的。
在下面的代码中,你要做的是:
- 计算`prices`中的`'MEDV'`的最小值、最大值、均值、中值和标准差;
- 将运算结果储存在相应的变量中。
```
# TODO: Minimum price of the data
#目标:计算价值的最小值
minimum_price = np.min(data['MEDV'])
# TODO: Maximum price of the data
#目标:计算价值的最大值
maximum_price = np.max(data['MEDV'])
# TODO: Mean price of the data
#目标:计算价值的平均值
mean_price = np.average(data['MEDV'])
# TODO: Median price of the data
#目标:计算价值的中值
median_price = np.median(data['MEDV'])
# TODO: Standard deviation of prices of the data
#目标:计算价值的标准差
std_price = np.std(data['MEDV'])
# Show the calculated statistics
#目标:输出计算的结果
print "Statistics for Boston housing dataset:\n"
print "Minimum price: ${:,.2f}".format(minimum_price)
print "Maximum price: ${:,.2f}".format(maximum_price)
print "Mean price: ${:,.2f}".format(mean_price)
print "Median price ${:,.2f}".format(median_price)
print "Standard deviation of prices: ${:,.2f}".format(std_price)
```
### 问题1 - 特征观察
如前文所述,本项目中我们关注的是其中三个值:`'RM'`、`'LSTAT'` 和`'PTRATIO'`,对每一个数据点:
- `'RM'` 是该地区中每个房屋的平均房间数量;
- `'LSTAT'` 是指该地区有多少百分比的房东属于是低收入阶层(有工作但收入微薄);
- `'PTRATIO'` 是该地区的中学和小学里,学生和老师的数目比(`学生/老师`)。
_凭直觉,上述三个特征中对每一个来说,你认为增大该特征的数值,`'MEDV'`的值会是**增大**还是**减小**呢?每一个答案都需要你给出理由。_
**提示:**你预期一个`'RM'` 值是6的房屋跟`'RM'` 值是7的房屋相比,价值更高还是更低呢?
**回答: **
- 'RM'增大'MEDV'会增大,因为某地区房间平均数量高的话,就意味着这个地方的房子比较好比较大,比如别墅式。而平均房间数量小的话可能是因为该地方比较贫穷,买不起较大的房子,房价自然就会低。
- 'LSTAT' 增大'MEDV'会减小,如果一个地区的房东是高收入阶层,那么这个地区应该是个富人聚集地,房价也会高,反之房价会比较低。
- 'PTRATIO'增大'MEDV'会减小,如果学生老师比较小的话,说明当地教育资源比较好,生活水平比较好,房价会高,反之说明教育资源比较少,房价比较低。
## 建模
在项目的第二部分中,你需要了解必要的工具和技巧来让你的模型进行预测。用这些工具和技巧对每一个模型的表现做精确的衡量可以极大地增强你预测的信心。
### 练习:定义衡量标准
如果不能对模型的训练和测试的表现进行量化地评估,我们就很难衡量模型的好坏。通常我们会定义一些衡量标准,这些标准可以通过对某些误差或者拟合程度的计算来得到。在这个项目中,你将通过运算[*决定系数*](http://stattrek.com/statistics/dictionary.aspx?definition=coefficient_of_determination) R<sup>2</sup> 来量化模型的表现。模型的决定系数是回归分析中十分常用的统计信息,经常被当作衡量模型预测能力好坏的标准。
R<sup>2</sup>的数值范围从0至1,表示**目标变量**的预测值和实际值之间的相关程度平方的百分比。一个模型的R<sup>2</sup> 值为0还不如直接用**平均值**来预测效果好;而一个R<sup>2</sup> 值为1的模型则可以对目标变量进行完美的预测。从0至1之间的数值,则表示该模型中目标变量中有百分之多少能够用**特征**来解释。_模型也可能出现负值的R<sup>2</sup>,这种情况下模型所做预测有时会比直接计算目标变量的平均值差很多。_
在下方代码的 `performance_metric` 函数中,你要实现:
- 使用 `sklearn.metrics` 中的 `r2_score` 来计算 `y_true` 和 `y_predict`的R<sup>2</sup>值,作为对其表现的评判。
- 将他们的表现评分储存到`score`变量中。
```
# TODO: Import 'r2_score'
from sklearn.metrics import r2_score
def performance_metric(y_true, y_predict):
""" Calculates and returns the performance score between
true and predicted values based on the metric chosen. """
# TODO: Calculate the performance score between 'y_true' and 'y_predict'
score = r2_score(y_true,y_predict)
# Return the score
return score
```
### 问题2 - 拟合程度
假设一个数据集有五个数据且一个模型做出下列目标变量的预测:
| 真实数值 | 预测数值 |
| :-------------: | :--------: |
| 3.0 | 2.5 |
| -0.5 | 0.0 |
| 2.0 | 2.1 |
| 7.0 | 7.8 |
| 4.2 | 5.3 |
*你会觉得这个模型已成功地描述了目标变量的变化吗?如果成功,请解释为什么,如果没有,也请给出原因。*
运行下方的代码,使用`performance_metric`函数来计算模型的决定系数。
```
# Calculate the performance of this model
score = performance_metric([3, -0.5, 2, 7, 4.2], [2.5, 0.0, 2.1, 7.8, 5.3])
print "Model has a coefficient of determination, R^2, of {:.3f}.".format(score)
```
**回答:** 我认为这个模型能够成功地描述目标变量的变化,因为真实值和预测值都比较接近,R^2系数也比较高。
### 练习: 数据分割与重排
接下来,你需要把波士顿房屋数据集分成训练和测试两个子集。通常在这个过程中,数据也会被重新排序,以消除数据集中由于排序而产生的偏差。
在下面的代码中,你需要:
- 使用 `sklearn.model_selection` 中的 `train_test_split`, 将`features`和`prices`的数据都分成用于训练的数据子集和用于测试的数据子集。
- 分割比例为:80%的数据用于训练,20%用于测试;
- 选定一个数值以设定 `train_test_split` 中的 `random_state` ,这会确保结果的一致性;
- 最终分离出的子集为`X_train`,`X_test`,`y_train`,和`y_test`。
```
# TODO: Import 'train_test_split'
from sklearn.model_selection import train_test_split
# TODO: Shuffle and split the data into training and testing subsets
X_train, X_test, y_train, y_test = train_test_split(features, prices, test_size=0.20, random_state=42)
# Success
print "Training and testing split was successful."
```
### 问题 3- 训练及测试
*将数据集按一定比例分为训练用的数据集和测试用的数据集对学习算法有什么好处?*
**提示:** 如果没有数据来对模型进行测试,会出现什么问题?
**答案: ** 如果没有数据对模型进行测试,那么模型可能会存在过拟合的问题,也就是说,在训练集上,模型表现得很完美,而不在训练集上的数据,则表现的很差,过拟合是可能模型学习了训练集做特有的误差特征。分为训练用和测试用的数据集,可以检验学习算法对未知数据的性能。
----
## 分析模型的表现
在项目的第三部分,我们来看一下几个模型针对不同的数据集在学习和测试上的表现。另外,你需要专注于一个特定的算法,用全部训练集训练时,提高它的`'max_depth'` 参数,观察这一参数的变化如何影响模型的表现。把你模型的表现画出来对于分析过程十分有益。可视化可以让我们看到一些单看结果看不到的行为。
### 学习曲线
下方区域内的代码会输出四幅图像,它们是一个决策树模型在不同最大深度下的表现。每一条曲线都直观的显示了随着训练数据量的增加,模型学习曲线的训练评分和测试评分的变化。注意,曲线的阴影区域代表的是该曲线的不确定性(用标准差衡量)。这个模型的训练和测试部分都使用决定系数R<sup>2</sup>来评分。
运行下方区域中的代码,并利用输出的图形回答下面的问题。
```
# Produce learning curves for varying training set sizes and maximum depths
vs.ModelLearning(features, prices)
```
### 问题 4 - 学习数据
*选择上述图像中的其中一个,并给出其最大深度。随着训练数据量的增加,训练曲线的评分有怎样的变化?测试曲线呢?如果有更多的训练数据,是否能有效提升模型的表现呢?*
**提示:**学习曲线的评分是否最终会收敛到特定的值?
**答案: ** 第一幅图像,最大深度是1,训练曲线的评分从1.0开始逐渐下降,而测试曲线则从0.0开始逐渐上升,如果有更多的训练数据,训练模型也不会有更大的提升,因为深度有限,模型的表现能力趋于特定值。随着最大深度的增加,训练数据表现能力会逐渐提升,而测试曲线随着最大深度的增加,模型的能力会逐渐下降,也就是出现了过拟合,这就是第四幅图像出现的问题。
### 复杂度曲线
下列代码内的区域会输出一幅图像,它展示了一个已经经过训练和验证的决策树模型在不同最大深度条件下的表现。这个图形将包含两条曲线,一个是训练的变化,一个是测试的变化。跟**学习曲线**相似,阴影区域代表该曲线的不确定性,模型训练和测试部分的评分都用的 `performance_metric` 函数。
运行下方区域中的代码,并利用输出的图形并回答下面的两个问题。
```
vs.ModelComplexity(X_train, y_train)
```
### 问题 5- 偏差与方差之间的权衡取舍
*当模型以最大深度 1训练时,模型的预测是出现很大的偏差还是出现了很大的方差?当模型以最大深度10训练时,情形又如何呢?图形中的哪些特征能够支持你的结论?*
**提示:** 你如何得知模型是否出现了偏差很大或者方差很大的问题?
**答案: ** 当最大深度为1时,模型有很大的偏差,以为此时训练数据表现得分和测试表现得分比较接近而且很低,所以模型应出现了较大的偏差,而当最大深度为10时,训练得分较高,而测试得分与训练得分有较大的差距,模型应该出现了较大的方差。因为训练得分很高但和测试得分差距较大。
### 问题 6- 最优模型的猜测
*你认为最大深度是多少的模型能够最好地对未见过的数据进行预测?你得出这个答案的依据是什么?*
**答案: ** 最大深度应该是4,因为在测试得分上,当最大深度为4时,模型的测试得分最高,此时模型的方差和偏差趋于平衡,如果深度再大,测会出现高方差,深度减小,则会出现高偏差。
-----
## 评价模型表现
在这个项目的最后,你将自己建立模型,并使用最优化的`fit_model`函数,基于客户房子的特征来预测该房屋的价值。
### 问题 7- 网格搜索(Grid Search)
*什么是网格搜索法?如何用它来优化学习算法?*
**回答: ** 网格搜索法是使用不同的参数组合来训练模型,通过开发人员指定的相关参数组合,例如在决策树里,不同的参数组合主要是决策树的最大深度。最后通过遍历不同的参数组合,得出一个最优的参数组合和模型,可以自动化搜索最优参数和最优模型
### 问题 8- 交叉验证
*什么是K折交叉验证法(k-fold cross-validation)?优化模型时,使用这种方法对网格搜索有什么好处?网格搜索是如何结合交叉验证来完成对最佳参数组合的选择的?*
**提示:** 跟为何需要一组测试集的原因差不多,网格搜索时如果不使用交叉验证会有什么问题?GridSearchCV中的[`'cv_results'`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html)属性能告诉我们什么?
**答案: ** K折交叉验证法是将数据集等分成若干份,其中一份作为验证集而剩下的最为训练集,循环使用不同的验证集和训练集,最后对所有结果取平均,交叉验证能更好的训练模型,因为差不多使用了所有的数据集,通过使用交叉验证法,网格搜索能够更准确的搜索出最优的参数组合。
### 练习:训练模型
在最后一个练习中,你将需要将所学到的内容整合,使用**决策树演算法**训练一个模型。为了保证你得出的是一个最优模型,你需要使用网格搜索法训练模型,以找到最佳的 `'max_depth'` 参数。你可以把`'max_depth'` 参数理解为决策树算法在做出预测前,允许其对数据提出问题的数量。决策树是**监督学习算法**中的一种。
此外,你会发现你的实现使用的是 `ShuffleSplit()` 。它也是交叉验证的一种方式(见变量 `'cv_sets'`)。虽然这不是**问题8**中描述的 K-Fold 交叉验证,这个教程验证方法也很有用!这里 `ShuffleSplit()` 会创造10个(`'n_splits'`)混洗过的集合,每个集合中20%(`'test_size'`)的数据会被用作**验证集**。当你在实现的时候,想一想这跟 K-Fold 交叉验证有哪些相同点,哪些不同点?
在下方 `fit_model` 函数中,你需要做的是:
- 使用 `sklearn.tree` 中的 [`DecisionTreeRegressor`](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html) 创建一个决策树的回归函数;
- 将这个回归函数储存到 `'regressor'` 变量中;
- 为 `'max_depth'` 创造一个字典,它的值是从1至10的数组,并储存到 `'params'` 变量中;
- 使用 `sklearn.metrics` 中的 [`make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html) 创建一个评分函数;
- 将 `performance_metric` 作为参数传至这个函数中;
- 将评分函数储存到 `'scoring_fnc'` 变量中;
- 使用 `sklearn.model_selection` 中的 [`GridSearchCV`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) 创建一个网格搜索对象;
- 将变量`'regressor'`, `'params'`, `'scoring_fnc'`, 和 `'cv_sets'` 作为参数传至这个对象中;
- 将 `GridSearchCV` 存到 `'grid'` 变量中。
如果有同学对python函数如何传递多个参数不熟悉,可以参考这个MIT课程的[视频](http://cn-static.udacity.com/mlnd/videos/MIT600XXT114-V004200_DTH.mp4)。
```
# TODO: Import 'make_scorer', 'DecisionTreeRegressor', and 'GridSearchCV'
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import make_scorer
from sklearn.model_selection import GridSearchCV
def fit_model(X, y):
""" Performs grid search over the 'max_depth' parameter for a
decision tree regressor trained on the input data [X, y]. """
# Create cross-validation sets from the training data
cv_sets = ShuffleSplit(n_splits = 10, test_size = 0.20, random_state = 0)
# TODO: Create a decision tree regressor object
regressor = DecisionTreeRegressor()
# TODO: Create a dictionary for the parameter 'max_depth' with a range from 1 to 10
params = {'max_depth':[1,2,3,4,5,6,7,8,9,10]}
# TODO: Transform 'performance_metric' into a scoring function using 'make_scorer'
scoring_fnc = make_scorer(performance_metric)
# TODO: Create the grid search object
grid = GridSearchCV(regressor,params,scoring=scoring_fnc,cv=cv_sets)
# Fit the grid search object to the data to compute the optimal model
grid = grid.fit(X, y)
# Return the optimal model after fitting the data
return grid.best_estimator_
```
### 做出预测
当我们用数据训练出一个模型,它现在就可用于对新的数据进行预测。在决策树回归函数中,模型已经学会对新输入的数据*提问*,并返回对**目标变量**的预测值。你可以用这个预测来获取数据未知目标变量的信息,这些数据必须是不包含在训练数据之内的。
### 问题 9- 最优模型
*最优模型的最大深度(maximum depth)是多少?此答案与你在**问题 6**所做的猜测是否相同?*
运行下方区域内的代码,将决策树回归函数代入训练数据的集合,以得到最优化的模型。
```
# Fit the training data to the model using grid search
reg = fit_model(X_train, y_train)
# Produce the value for 'max_depth'
print "Parameter 'max_depth' is {} for the optimal model.".format(reg.get_params()['max_depth'])
```
**Answer: ** 最好的模型的深度是4
### 问题 10 - 预测销售价格
想像你是一个在波士顿地区的房屋经纪人,并期待使用此模型以帮助你的客户评估他们想出售的房屋。你已经从你的三个客户收集到以下的资讯:
| 特征 | 客戶 1 | 客戶 2 | 客戶 3 |
| :---: | :---: | :---: | :---: |
| 房屋内房间总数 | 5 间房间 | 4 间房间 | 8 间房间 |
| 社区贫困指数(%被认为是贫困阶层) | 17% | 32% | 3% |
| 邻近学校的学生-老师比例 | 15:1 | 22:1 | 12:1 |
*你会建议每位客户的房屋销售的价格为多少?从房屋特征的数值判断,这样的价格合理吗?*
**提示:**用你在**分析数据**部分计算出来的统计信息来帮助你证明你的答案。
运行下列的代码区域,使用你优化的模型来为每位客户的房屋价值做出预测。
```
# Produce a matrix for client data
client_data = [[5, 17, 15], # Client 1
[4, 32, 22], # Client 2
[8, 3, 12]] # Client 3
# Show predictions
for i, price in enumerate(reg.predict(client_data)):
print "Predicted selling price for Client {}'s home: ${:,.2f}".format(i+1, price)
```
**答案: **
- Client 1's home: \$403,025.00
- Client 2's home: \$237,478.72
- Client 3's home: \$931,636.36
从上面的预测结果来看,这样的价格还算合理,房间多的价格教贵,学生老师比小的,社区贫困指数也较低,说明和预期分析的差不多。而且整体符合之前的统计量,都在最大值和最小值之间,
### 敏感度
一个最优的模型不一定是一个健壮模型。有的时候模型会过于复杂或者过于简单,以致于难以泛化新增添的数据;有的时候模型采用的学习算法并不适用于特定的数据结构;有的时候样本本身可能有太多噪点或样本过少,使得模型无法准确地预测目标变量。这些情况下我们会说模型是欠拟合的。执行下方区域中的代码,采用不同的训练和测试集执行 `fit_model` 函数10次。注意观察对一个特定的客户来说,预测是如何随训练数据的变化而变化的。
```
vs.PredictTrials(features, prices, fit_model, client_data)
```
### 问题 11 - 实用性探讨
*简单地讨论一下你建构的模型能否在现实世界中使用?*
**提示:** 回答几个问题,并给出相应结论的理由:
- *1978年所采集的数据,在今天是否仍然适用?*
- *数据中呈现的特征是否足够描述一个房屋?*
- *模型是否足够健壮来保证预测的一致性?*
- *在波士顿这样的大都市采集的数据,能否应用在其它乡镇地区?*
**答案: **
- 1978年所采集的数据,现在应该不使用了,因为随着时代的发展有些特征已经不再是影响房价的主要因素,而可能又出现新的特征影响房价。
- 数据中呈现的特征我认为不足以描述一个房屋,因为除了这些因素以外,可能还存在着别的,比如面积,房屋的面积和房间的数量不是严格成正比的,长宽比,方形的房屋要比细长的好等。
- 我认为模型已经相当健壮,多次预测同一个房屋,价格相近。
- 像波士顿这种大都市采集的数据,不能应用到乡镇地区,因为大都市和乡镇有着不一样的特征。
最后,我认为该模型还不足以在现实世界中使用,还有一些缺陷。
### 可选问题 - 预测北京房价
(本题结果不影响项目是否通过)通过上面的实践,相信你对机器学习的一些常用概念有了很好的领悟和掌握。但利用70年代的波士顿房价数据进行建模的确对我们来说意义不是太大。现在你可以把你上面所学应用到北京房价数据集中`bj_housing.csv`。
免责声明:考虑到北京房价受到宏观经济、政策调整等众多因素的直接影响,预测结果仅供参考。
这个数据集的特征有:
- Area:房屋面积,平方米
- Room:房间数,间
- Living: 厅数,间
- School: 是否为学区房,0或1
- Year: 房屋建造时间,年
- Floor: 房屋所处楼层,层
目标变量:
- Value: 房屋人民币售价,万
你可以参考上面学到的内容,拿这个数据集来练习数据分割与重排、定义衡量标准、训练模型、评价模型表现、使用网格搜索配合交叉验证对参数进行调优并选出最佳参数,比较两者的差别,最终得出最佳模型对验证集的预测分数。
```
### 你的代码
bj_data = pd.read_csv('bj_housing.csv')
bj_prices = bj_data['Value']
bj_features = bj_data.drop('Value', axis = 1)
print "Boston housing dataset has {} data points with {} variables each.".format(*bj_data.shape)
X_train_bj, X_test_bj, y_train_bj, y_test_bj = train_test_split(bj_features, bj_prices, test_size=0.20, random_state=23)
vs.ModelComplexity(X_train_bj, y_train_bj)
def fit_model_bj(X, y):
""" Performs grid search over the 'max_depth' parameter for a
decision tree regressor trained on the input data [X, y]. """
# Create cross-validation sets from the training data
cv_sets = ShuffleSplit(n_splits = 10, test_size = 0.20, random_state = 0)
# TODO: Create a decision tree regressor object
regressor = DecisionTreeRegressor()
# TODO: Create a dictionary for the parameter 'max_depth' with a range from 1 to 10
params = {'max_depth':[1,2,3,4,5,6,7,8,9,10]}
# TODO: Transform 'performance_metric' into a scoring function using 'make_scorer'
scoring_fnc = make_scorer(performance_metric)
# TODO: Create the grid search object
grid = GridSearchCV(regressor,params,scoring=scoring_fnc,cv=cv_sets)
# Fit the grid search object to the data to compute the optimal model
grid = grid.fit(X, y)
# Return the optimal model after fitting the data
return grid.best_estimator_
reg_bj = fit_model_bj(X_train_bj, y_train_bj)
# Produce the value for 'max_depth'
print "Parameter 'max_depth' is {} for the optimal model.".format(reg_bj.get_params()['max_depth'])
y_pre_bj = reg_bj.predict(X_test_bj)
y_pre = reg.predict(X_test)
print performance_metric(y_test_bj,y_pre_bj)
print performance_metric(y_test,y_pre)
```
你成功的用新的数据集构建了模型了吗?他能对测试数据进行验证吗?它的表现是否符合你的预期?交叉验证是否有助于提升你模型的表现?
**答案:** 成功用新的数据集构建了模型,能对测试数据进行验证,表现一般,交叉验证有助于提升模型表现。
如果你是从零开始构建机器学习的代码会让你一时觉得无从下手。这时不要着急,你要做的只是查看之前写的代码,把每一行都看明白,然后逐步构建你的模型。当中遇到什么问题也可以在我们论坛寻找答案。也许你会发现你所构建的模型的表现并没有达到你的预期,这说明机器学习并非是一项简单的任务,构建一个表现良好的模型需要长时间的研究和测试。这也是我们接下来的课程中会逐渐学到的。
| github_jupyter |
```
import glob
import random
import sys
from itertools import chain
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.metrics import accuracy_score, confusion_matrix
from thundersvm import SVC
from tqdm import tqdm
np.random.seed(0)
random.seed(0)
```
### TEST TRAIN INDEX GENERATION FOR FOLDS
```
attribute_map = [
# {"Race": ["African", "Asian", "Indian", "Caucasian"]},
{"skintype": ["type1", "type2", "type3", "type4", "type5", "type6"]},
{"eye": ["normal", "narrow"]},
{"haircolor": ["red", "black", "gray", "brown", "blonde"]},
{"hairtype": ["straight", "wavy", "bald", "curly"]},
{"lips": ["small", "big"]},
{"nose": ["wide", "narrow"]},
]
vgg = pd.read_csv("/mnt/HDD/FaceDatasetCenter/metadata/VGGFace2_metadata_FDA.csv")
vgg_test = vgg[vgg.type == "test"]
vgg_test.head()
vgg_image = pd.read_csv(
"/mnt/HDD/FaceDatasetCenter/metadata/VGGFace2_image_meta_test.csv"
)
vgg_image_test = vgg_image[vgg_image.type == "test"]
vgg_image_test = vgg_image_test.sort_values(by="file")
vgg_image_test.head()
NUM_FOLDS = 3
TEST_SAMPLE_SIZE = 50
folds_folder = Path("folds")
folds_folder.mkdir(exist_ok=True)
def generate_fold():
all_folds = []
for fold in range(0, NUM_FOLDS):
print(TEST_SAMPLE_SIZE * NUM_FOLDS)
print(f"Fold {fold+1}")
class_folds = {"train": [], "test": []}
for i, group in vgg_image_test.groupby("Class_ID"):
num_samples = group.shape[0]
test_mask = np.zeros(num_samples, dtype=np.bool)
if TEST_SAMPLE_SIZE * NUM_FOLDS > num_samples:
start = fold * TEST_SAMPLE_SIZE
end = start + TEST_SAMPLE_SIZE
ix = [i % num_samples for i in range(start, end)]
# print(f"ClassID: {i}, fold: {fold} - [{ix[0]}:{ix[-1]}]")
else:
class_fold_size = num_samples // NUM_FOLDS
start = fold * class_fold_size
end = start + class_fold_size
ix = range(start, end)
test_mask[ix] = True
try:
class_folds["test"].append(
group[test_mask].sample(n=TEST_SAMPLE_SIZE, random_state=0)
)
except:
import pdb
pdb.set_trace()
class_folds["train"].append(group[~test_mask])
all_folds.append(class_folds)
return all_folds
all_folds = generate_fold()
print(len(all_folds))
for i, fold in enumerate(all_folds):
train = pd.concat(fold["train"])
test = pd.concat(fold["test"])
train.to_parquet(folds_folder / f"fold_{i}_train.pq", compression="GZIP")
test.to_parquet(folds_folder / f"fold_{i}_test.pq", compression="GZIP")
```
### Feature loading
```
features = np.load("features/vggface2_test_features.npy",allow_pickle=True)
path_arr = np.load("features/vggface2_test_paths.npy",allow_pickle=True)
meta = pd.DataFrame(path_arr, columns=["full_path"])
meta["file"] = meta.full_path.apply(lambda x: "/".join(Path(x).parts[-2:]))
labels = list(map(lambda x: str(x).split("/")[-2], path_arr))
le = preprocessing.LabelEncoder()
labels = le.fit_transform(labels)
meta["y_test"] = labels
meta = meta.merge(vgg_image_test,how='left',on='file')
meta.head()
#Train CODE
def train(X,y):
all_predictions = []
for i,fold in enumerate(range(0, NUM_FOLDS)):
train_ixs = pd.read_parquet(folds_folder / f"fold_{i}_100_train.pq")
test_ixs = pd.read_parquet(folds_folder / f"fold_{i}_100_test.pq")
print(folds_folder / f"fold_{i}_train.pq")
print(test_ixs.shape)
print(meta[meta.file.isin(test_ixs.file)].index.shape)
test_index = meta[meta.file.isin(test_ixs.file)].index
train_index = meta[meta.file.isin(train_ixs.file)].index
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
print(X_test.shape,y_test.shape)
print('SVM Training...')
svm_model_linear = SVC(kernel="linear", C=1).fit(X_train, y_train)
print("Starting prediction (The computer can be unresponsive during the prediction).")
TEST_BATCH_SIZE = 1000
preds = []
ys=[]
with tqdm(total=X_test.shape[0], file=sys.stdout) as pbar:
for i in range(0, X_test.shape[0], TEST_BATCH_SIZE):
X_test_batch = X_test[i : i + TEST_BATCH_SIZE]
pred = svm_model_linear.predict(X_test_batch)
preds.append(pred)
# update tqdm
pbar.set_description("Processed: %d" % (1 + i))
pbar.update(TEST_BATCH_SIZE)
all_predictions.append(preds)c
return all_predictions
X = np.asarray(features, dtype=np.float32)
y = labels
pred_list = train(X,y)
ap = np.asarray(pred_list)
ap = ap.reshape(ap.shape[0],ap.shape[1]*ap.shape[2])
ap.shape
# TEST CODE
result_dic = []
for i, fold in enumerate(range(0, 3)):
train_ixs = pd.read_parquet(folds_folder / f"fold_{i}_train.pq")
test_ixs = pd.read_parquet(folds_folder / f"fold_{i}_test.pq")
print(meta.shape,test_ixs.index)
meta_test = meta[meta.file.isin(test_ixs.file)]
print(meta_test.shape)
test_index = meta_test.index
y_test = y[test_index]
meta_test["y_pred"] = ap[i]
print("Overall Accuracy:", accuracy_score(meta_test["y_test"], meta_test["y_pred"]))
print("Group initilization!")
for attr in attribute_map:
# for one value of one attribute
for key, value in attr.items():
for val in value:
subgroup = meta_test[meta_test[key] == val]
score= accuracy_score(subgroup["y_test"], subgroup["y_pred"])
print(
key,
val,
":",
score,
subgroup.shape,
)
result_dic.append([key,val,score,subgroup.shape[0]])
subgroup.shape
results = pd.DataFrame(result_dic,columns=['feature','category','acc','size'])
results["attribute_name"] = results["feature"] +'_'+ results["category"]
results = results.groupby('attribute_name').mean().sort_values(by='attribute_name')
results = results.reset_index()
results['attribute'] = results.attribute_name.apply(lambda x:x.split('_')[0])
total_size = results.groupby('attribute').sum()['size'][0]
print('total size',total_size)
results['Ratio']=results['size'].apply(lambda x: x/total_size)
results
results.to_csv('face_identifiacation_attribute_based_results.csv',index=False)
print("std:", np.std(results.acc.values,ddof=1) * 100)
print("bias:", (1-results.acc.values.min()) / (1-results.acc.values.max()))
(1.0-results.acc.values.min())/(1-results.acc.values.max())
1-results.acc.values.max()
results
(1.0-results.acc.values.min()),(1-results.acc.values.max())
# print(results[['feature_name','acc']].to_latex())
results["Ratio"] = results["Ratio"].apply(lambda x: f"{100*x:.2f}")
results["Acc"] = results["acc"].apply(lambda x: f"{100*x:.2f}")
results["attribute_name"] = results["attribute_name"].str.replace("skintype", "")
results["attribute_name"] = results["attribute_name"].str.replace("haircolor", "hair ")
results["attribute_name"] = results["attribute_name"].str.replace("hairtype", "hair ")
results["attribute_name"] = results["attribute_name"].str.title()
results["attribute_name"] = results["attribute_name"].apply(
lambda x: " ".join(x.split("_")[::-1])
)
results = results.sort_values(by='Acc')
attribute_res = results[["attribute_name","Ratio", "Acc"]]
attribute_res = pd.concat(
[
attribute_res.iloc[:11].reset_index(drop=True),
attribute_res.iloc[11:].reset_index(drop=True),
],
axis=1,
ignore_index=True,
)
attribute_res.columns = ["Attribute Category", "Ratio (%)","Accuracy (%)", "Attribute Category(%)", "Ratio","Accuracy(%)"]
attribute_res
print(
attribute_res.to_latex(
index=False, caption="Table Caption", label="tab:fi1", na_rep=""
)
)
print(type(all_predictions), type(y_s))
for y_test, y_pred in zip(y_s, all_predictions):
print(type(y_pred), type(y_test))
y_pred = np.array(list(chain(*y_pred)))
print("Overall Accuracy:", accuracy_score(y_test, y_pred))
feature_arr = np.asarray(features, dtype=np.float32)
print(feature_arr[0][0], np.mean(feature_arr), np.std(feature_arr))
feature_arr = preprocessing.normalize(feature_arr)
print(feature_arr[0][0], np.mean(feature_arr), np.std(feature_arr))
labels = list(map(lambda x: x.split("/")[-2], path_arr))
le = preprocessing.LabelEncoder()
labels = le.fit_transform(labels)
X = feature_arr
y = labels
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
print("Data is ready!", X.shape, X.shape)
sss = StratifiedShuffleSplit(n_splits=1, test_size=0.1, random_state=0)
for train_index, test_index in sss.split(X, y):
print("TRAIN:", type(train_index), "TEST:", type(test_index))
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
svm_model_linear = SVC(kernel="linear", C=20).fit(X_train, y_train)
print("Training is completed.")
# import datetime
# timestr = datetime.datetime.now().isoformat().replace(":", ".")
# svm_model_file = f"svm_model_{timestr}"
# svm_model_linear.save_to_file(svm_model_file)
# print(f"Saved model to: {svm_model_file}")
import sys
from itertools import chain
from tqdm import tqdm
print("Starting prediction (The computer can be unresponsive during the prediction).")
TEST_BATCH_SIZE = 1000
preds = []
with tqdm(total=X_test.shape[0], file=sys.stdout) as pbar:
for i in range(0, X_test.shape[0], TEST_BATCH_SIZE):
X_test_batch = X_test[i : i + TEST_BATCH_SIZE]
pred = svm_model_linear.predict(X_test_batch)
preds.append(pred)
# update tqdm
pbar.set_description("Processed: %d" % (1 + i))
pbar.update(TEST_BATCH_SIZE)
y_pred = np.array(list(chain(*preds)))
print("Overall Accuracy:", accuracy_score(y_test, y_pred))
test_ixs["y_pred"] = y_pred.astype(np.int)
test_ixs["y_test"] = y_test
test_ixs = test_ixs.rename(columns={"subject": "Class_ID"})
test_data = test_ixs.merge(vgg_test, on="Class_ID", how="left")
attribute_map = [
{"skintype": ["type1", "type2", "type3", "type4", "type5", "type6"]},
{"hairtype": ["straight", "wavy", "bald", "curly"]},
{"haircolor": ["red", "black", "grey", "brown", "blonde"]},
{"lips": ["small", "big"]},
{"eye": ["normal", "narrow"]},
{"nose": ["wide", "narrow"]},
]
print("Group initilization!")
for attr in attribute_map:
# for one value of one attribute
for key, value in attr.items():
for val in value:
subgroup = test_data[test_data[key] == val]
print(
key,
val,
":",
accuracy_score(subgroup["y_test"], subgroup["y_pred"]),
subgroup.shape,
)
# y_pred = svm_model_linear.predict(X_test)
# features = np.load('features/unlearn_races_r50_feat_05ep.npz')
# meta_data = pd.read_csv('metadata/VGGFace2_200_Subjects_Test_Images.csv')
# features = np.load('../FeatureEncodingsRFW/senet50_ft_features.npy')
# train_ixs = pd.read_csv('../train_test_split/rfwtest_train_indexes.csv')
# test_ixs = pd.read_csv('../train_test_split/rfwtest_test_indexes.csv')
features = features["arr_0"]
feature_arr = np.asarray(features[:][:, :-1], dtype=np.float64)
path_arr = features[:][:, -1]
labels = list(map(lambda x: x.split("/")[0], path_arr))
le = preprocessing.LabelEncoder()
labels = le.fit_transform(labels)
X = pd.DataFrame(feature_arr)
y = pd.Series(labels)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
print("SVM!")
svm_model_linear = SVC(kernel="linear", C=1).fit(X_train, y_train)
y_pred = svm_model_linear.predict(X_test)
print("Overall Accuracy:", accuracy_score(y_test.values, y_pred))
print("Group initilization!")
test_pathes = path_arr[y_test.index.values]
for race in ["African", "Asian", "Caucasian", "Indian"]:
for gender in ["m", "f"]:
main_group = meta_data[
(meta_data.race == race)
& (meta_data.gender == gender)
& (meta_data.generated_version == "original")
]
group_file = main_group.filename.values
indexes = []
for el in group_file:
loc = np.argwhere(test_pathes == el)
if loc.size != 0:
indexes.append(int(loc[0][0]))
if len(indexes) > 0:
indexes = np.asarray(indexes)
print(race, gender)
print(
" accuracy:%d %.3f"
% (
len(y_test.values[indexes]),
accuracy_score(y_test.values[indexes], y_pred[indexes]),
)
)
from sklearn.model_selection import GridSearchCV
feature_arr = np.asarray(features[:][:, :-1], dtype=np.float64)
path_arr = features[:][:, -1]
labels = list(map(lambda x: x.split("/")[0], path_arr))
le = preprocessing.LabelEncoder()
labels = le.fit_transform(labels)
X = pd.DataFrame(feature_arr)
y = pd.Series(labels)
param_grid = [
{"C": [1, 10, 100, 1000], "kernel": ["linear"]},
{"C": [1, 10, 100, 1000], "gamma": [0.001, 0.0001], "kernel": ["rbf"]},
]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
grid_search = GridSearchCV(SVC(), param_grid, cv=2)
svm_model = grid_search.fit(X_train, y_train)
print(grid_search.best_params_)
# y_pred = svm_model.predict(X_test)
# print('Overall Accuracy:',accuracy_score(y_test.values, y_pred))
# print('Group initilization!')
# test_pathes = path_arr[y_test.index.values]
# for race in ['African','Asian','Caucasian', 'Indian']:
# for gender in ['f','m']:
# main_group = meta_data[(meta_data.race == race) & (meta_data.gender== gender) & (meta_data.generated_version== 'original') ]
# group_file = main_group.filename.values
# indexes = []
# for el in group_file:
# loc = np.argwhere(test_pathes==el)
# if loc.size != 0:
# indexes.append(int(loc[0][0]))
# if len(indexes)>0:
# indexes = np.asarray(indexes)
# print(race,gender)
# print(' accuracy:%d %.3f'%(len(y_test.values[indexes]), accuracy_score(y_test.values[indexes], y_pred[indexes])))
```
SVM!
Overall Accuracy: 0.5139621028636558
Group initilization!
African m
accuracy:1551 0.454
African f
accuracy:1953 0.473
Asian m
accuracy:1610 0.496
Asian f
accuracy:1516 0.383
Caucasian m
accuracy:1797 0.559
Caucasian f
accuracy:1959 0.590
Indian m
accuracy:1964 0.615
Indian f
accuracy:1688 0.498
| github_jupyter |
# Matplotlib - Intro
* **matplotlib** is a Python plotting library for producing publication quality figures
* allows for interactive, cross-platform control of plots
* makes it easy to produce static raster or vector graphics
* gives the developer complete control over the appearance of their plots, while still being usable through a powerful defaults system
* standard scientific plotting library
* online documentnation is on [matplotlib.org](https://matplotlib.org/index.html), with lots of examples in the [gallery](https://matplotlib.org/gallery.html)
* behaves similarly to Matlab
```
import matplotlib.pyplot as plt
import numpy as np
```
To be efficient with **matplotlib**, you first need to understand its termonology.
## Parts of a Figure
<img src="../../figures/matplotlib_figure_parts.png" style="height:90%; width:90%;">
### Figure, Axes, Axis
* **Figure** is the whole image, the top-level 'container' that holds all objects of an image.
* **Axes** is the region of a **Figure** that displays your data. Most plotting occurs here! Very similar to a subplot
* **Axes** contains **Axis** objects (x axis,y axis) which control the data limits.
* **Figure** can have any number of **Axes**, but to be useful should have at least one.
```
fig = plt.figure() # Create a figure
axes = fig.add_subplot(111) # add one Axes to Figure
```
Usually an **Axes** is set up with a call to `fig.add_subplot()`, `plt.subplot()`, or `plt.subplots()`
The most flexible option is `plt.subplots()`
```
fig,axes = plt.subplots(2,3,figsize=(12,6))
# This will create a figure and 6 axes arranged in 2 rows, 3 columns
```
### Line plots
Lets draw two cosine functions of different amplitude on the same **Axes**.
```
# Create data
X = np.linspace(-np.pi, np.pi, 100, endpoint=True)
Y1 = np.cos(X)
Y2 = 2*np.cos(X)
# Plot data
fig, axes = plt.subplots()
axes.plot(X, Y1)
axes.plot(X, Y2);
```
** Tip: by adding a semicolon at the end of a function, the output is suppressed.
### Default and named colors

**Exercise 0 (10 mins)**. The figure before is generated using the default settings. The code below shows these settings explicitly. Play with the values to explore their effect. For details on changing properties see [line plots on the matplotlib website](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html)
```
# Plot data (with explicit plotting settings)
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6,4))
axes.plot(X, Y1, color='C0', linewidth=5.0, linestyle='-',alpha=0.5)
axes.plot(X, Y2, color='r', linewidth=3.0, linestyle='--')
# Your code here
# Sample solution
# Plot data (with explicit plotting settings)
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(8,4))
axes.plot(X, Y1, color='r', linewidth=4, linestyle='--')
axes.plot(X, Y2, color='b', linewidth=2, linestyle='-.')
axes.set_xlim(-8, 8)
axes.set_ylim(-3, 3)
axes.set_xticks(np.linspace(-4,4,9,endpoint=True))
axes.set_yticks(np.linspace(-3,3,11,endpoint=True));
```
**Exercise 1 (10 mins)**. Having integer numbers on the x axis here might divert reader's attention from the critical points of the graph.
1. Change **xticks** and **xticklabels** into multiples of $\pi$. Use `axes.set_xticks()` and `axes.set_xticklabels()`.
\*\* Tip: use `np.pi` for **xticks** and '\$\pi$' for **xticklabels**. format strings in LaTeX by prepending 'r'ie `axes.set_xticklabels([r'$\pi$'])`
```
# Your code here
# Solution
# Change xticks, yticks and xticklabels
fig, axes = plt.subplots()
axes.plot(X, Y1);
axes.plot(X, Y2);
axes.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]);
axes.set_yticks([-2, -1, 0, 1, 2]);
axes.set_xticklabels(['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$']);
```
**Exersise 2 (5 mins)**. Add a legend.
1. Give both cosine functions a name by adding an extra keyword argument, a label, to `axes.plot()`.
2. Add a legend object to **Axes**.
```
# Your code here
# Solution
# Add a legend
fig, axes = plt.subplots()
axes.plot(X, Y1, label='cos(x)');
axes.plot(X, Y2, label='2cos(x)');
axes.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]);
axes.set_yticks([-2, -1, 0, 1, 2]);
axes.set_xticklabels(['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$']);
axes.legend(loc='upper left', frameon=False);
```
**Exercise 3 (10 mins)**. Annotate an interesting point on a graph, for example, $2\cos(\frac{\pi}{4})$.
1. Add a single point to the graph by using `axes.plot(..., marker='o')`.
2. Use `axes.annotate(s, xy=..., xytext=...)` to add annotation.
** Tip: visit [annotations](https://matplotlib.org/users/annotations_intro.html).
```
# Your code here
fig, axes = plt.subplots()
axes.plot(X, Y1, label='cos(x)');
axes.plot(X, Y2, label='2cos(x)');
axes.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]);
axes.set_yticks([-2, -1, 0, 1, 2]);
axes.set_xticklabels(['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$']);
axes.legend(loc='upper left', frameon=False);
point = np.pi/4
axes.plot(point, 2*np.cos(point), marker='o');
axes.annotate(r'$2\cos(\frac{\pi}{4})=\sqrt{2}$', xy=(point, 2*np.cos(point)), xytext=(1, 1.5), fontsize=16);
```
### Demonstration of bar() on NAO index data
Bar plots are created in much the same way as line plots, with two arrays of equal size.
Here we use `bar()` to plot the data on North Atlantic oscillation from the NWS Climate Prediction Center.
Data source: http://www.cpc.ncep.noaa.gov/products/precip/CWlink/pna/nao.shtml
Variable: monthly mean NAO index since January 1950 til March 2019.
Data stored in text file in the following way:
Year | Month | Value
1950 1 0.92000E+00
# Read NAO data
```
nao_yr, nao_mn, nao_val = np.loadtxt('../../data/nao_monthly.txt', unpack=True)
# Quick look at the data
fig, ax = plt.subplots(figsize=(25, 5))
ax.plot(nao_val);
```
Let's focus on the last 5 years and slice `nao_yr`, `nao_mn`, `nao_val` arrays accordingly.
```
# Slicing
nao_yr_sub = nao_yr[-12*5:]
nao_mn_sub = nao_mn[-12*5:]
nao_val_sub = nao_val[-12*5:]
# Create an array of month numbers
nao_time = np.arange(len(nao_val_sub))
nao_time
# Plot bar
fig, ax = plt.subplots(figsize=(15,4))
ax.bar(nao_time, nao_val_sub)
ax.set_title('NAO index')
ax.grid(True)
```
### Scatter plots
* display data as a collection of points, each having the value of one variable determining the position on the horizontal axis and the value of the other variable determining the position on the vertical axis
* colorcode the data points to display an additional variable
* good for non-gridded data
`scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, edgecolors=None, **kwargs)`
```
# Generate some data (circles of random diameter)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi*(15*np.random.rand(N))**2 # 0 to 15 point radii
colors = np.random.rand(N)
# Plot scatter
plt.scatter(x, y, s=area, c=colors);
```
### Multiple subplots
`plt.subplots()` is a function that creates a figure and a grid of subplots with a single call, while providing reasonable control over how the individual plots are created.
```
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(15,5)) # or plt.subplots(2,3,figsize=(15,5))
axes[0,0].set_title('subplot[0,0]', fontsize=18);
axes[0,1].set_title('subplot[0,1]', fontsize=18);
axes[0,2].set_title('subplot[0,2]', fontsize=18);
axes[1,0].set_title('subplot[1,0]', fontsize=18);
axes[1,1].set_title('subplot[1,1]', fontsize=18);
axes[1,2].set_title('subplot[1,2]', fontsize=18);
for ax in axes.flat: # you can loop over axes
ax.set_xticks([]);
ax.set_yticks([]);
```
### Subplots with real data
To practice our plotting we are going to work with data from the NOAA ESRL Carbon Cycle Cooperative Global Air Sampling Network.
Source: https://www.esrl.noaa.gov/gmd/dv/data/
Monthly averages of atmospheric carbon dioxide ($CO_2$) and methane ($CH_4$)
Stations:
* CGO = Cape Grim, Tasmania, Australia
* MHD = Mace Head, County Galway, Ireland
Units:
* $CO_2$ - ppm
* $CH_4$ - ppb
Data stored in a text file. The top row states the number of header lines in the file. No title headers. The actual data is ogranized as following:
|Station code | Year | Month | Measurement|
| :------------- | :----------: | :----------| :---------- |
|CGO | 1984 | 4 | 341.63 |
#### Read data from a text file
The simplest way to load data from a text file in `numpy` is to use `np.loadtxt()` function.
```
# np.loadtxt() # hit Shift+Tab+Tab
```
This function has a lot parameters that you can adjuct to fit your data format. Here we use only:
`np.loadtxt(fname, skiprows=..., usecols=..., unpack=...)`
```
data = np.loadtxt('../../data/co2_cgo_surface-flask_1_ccgg_month.txt', skiprows=68, usecols=(1, 2, 3))
data
```
If we want to have three separate arrays for year, month and value, we can set `unpack=True` and store the output from `np.loadtxt()` function in three separate arrays.
```
year, month, value = np.loadtxt('../../data/co2_cgo_surface-flask_1_ccgg_month.txt', skiprows=68, usecols=(1, 2, 3), unpack=True)
year[0:8]
month[0:8]
value[0:8]
```
#### Kwargs
* remember from yesterday, you can store any number of keyword arguments in a dictionary, and later unpack it when calling a function
```
# Kwargs
read_data_kwargs = dict(skiprows=68, usecols=(1, 2, 3), unpack=True)
# Read data
# CO2
cgo_co2_yr, cgo_co2_mn, cgo_co2_val = np.loadtxt('../../data/co2_cgo_surface-flask_1_ccgg_month.txt', **read_data_kwargs)
mhd_co2_yr, mhd_co2_mn, mhd_co2_val = np.loadtxt('../../data/co2_mhd_surface-flask_1_ccgg_month.txt', **read_data_kwargs)
# CH4
cgo_ch4_yr, cgo_ch4_mn, cgo_ch4_val = np.loadtxt('../../data/ch4_cgo_surface-flask_1_ccgg_month.txt', **read_data_kwargs)
mhd_ch4_yr, mhd_ch4_mn, mhd_ch4_val = np.loadtxt('../../data/ch4_mhd_surface-flask_1_ccgg_month.txt', **read_data_kwargs)
```
We'll find out how to properly plot on a time axis soon! For now, create dummy time arrays by some arithmetic to numpy arrays.
```
cgo_co2_time_dummy = cgo_co2_yr*12 + cgo_co2_mn
mhd_co2_time_dummy = mhd_co2_yr*12 + mhd_co2_mn
cgo_ch4_time_dummy = cgo_ch4_yr*12 + cgo_ch4_mn
mhd_ch4_time_dummy = mhd_ch4_yr*12 + mhd_ch4_mn
```
**Exercise 4a (20 mins)**. Construct two subplots using the arrays created above. Add titles, x and y labels, legend. If you have time, play with optional arguments of `plot()` and try to use **kwargs**.
The desired outcome is something like this (time on x axis will follow in part b):
<img src="../../figures/subplots_example.png">
```
# Your code here
# Solution
# plt.rcParams['mathtext.default'] = 'regular'
cgo_kwargs = dict(label='Cape Grim', color='C3', linestyle='-')
mhd_kwargs = dict(label='Mace Head', color='C7', linestyle='-')
fig, axes = plt.subplots(nrows=2, figsize=(9,9), sharex=True)
axes[0].plot(cgo_co2_time_dummy, cgo_co2_val, **cgo_kwargs)
axes[1].plot(cgo_ch4_time_dummy, cgo_ch4_val, **cgo_kwargs)
axes[0].plot(mhd_co2_time_dummy, mhd_co2_val, **mhd_kwargs)
axes[1].plot(mhd_ch4_time_dummy, mhd_ch4_val, **mhd_kwargs)
axes[0].set_title('$CO_{2}$')
axes[1].set_title('$CH_{4}$')
axes[0].set_ylabel('ppm')
axes[1].set_ylabel('ppb')
axes[0].legend();
#fig.savefig('../../figures/subplots_example.png',bbox_inches='tight')
```
#### Datetime
* `datetime` module helps to work with time arrays
```
from datetime import datetime
datetime.now()
a_date = datetime(2019, 5, 23)
a_date
python_course_dates = [datetime(2019, 5, i) for i in [22, 23, 24]]
python_course_dates
```
Let's apply it to our arrays.
```
# Using list comprehension
cgo_co2_time = [datetime(int(i), int(j), 1) for i, j in zip(cgo_co2_yr, cgo_co2_mn)]
# Same as in previous cell but using a for loop
cgo_co2_time = []
for i, j in zip(cgo_co2_yr, cgo_co2_mn):
cgo_co2_time.append(datetime(int(i), int(j), 1))
mhd_co2_time = [datetime(int(i), int(j), 1) for i, j in zip(mhd_co2_yr, mhd_co2_mn)]
cgo_ch4_time = [datetime(int(i), int(j), 1) for i, j in zip(cgo_ch4_yr, cgo_ch4_mn)]
mhd_ch4_time = [datetime(int(i), int(j), 1) for i, j in zip(mhd_ch4_yr, mhd_ch4_mn)]
```
<b>Exercise 4b.</b> Improve your solution to exercise 4a by using the newly created datetime arrays. Note how matplotlib understands the datetime format.
```
# Solution
# plt.rcParams['mathtext.default'] = 'regular'
cgo_kwargs = dict(label='Cape Grim', color='C3', linestyle='-')
mhd_kwargs = dict(label='Mace Head', color='C7', linestyle='-')
fig, axes = plt.subplots(nrows=2, figsize=(9,9), sharex=True)
axes[0].plot(cgo_co2_time, cgo_co2_val, **cgo_kwargs)
axes[1].plot(cgo_ch4_time, cgo_ch4_val, **cgo_kwargs)
axes[0].plot(mhd_co2_time, mhd_co2_val, **mhd_kwargs)
axes[1].plot(mhd_ch4_time, mhd_ch4_val, **mhd_kwargs)
axes[0].set_title('$CO_{2}$')
axes[1].set_title('$CH_{4}$')
axes[0].set_ylabel('ppm')
axes[1].set_ylabel('ppb')
axes[0].legend();
#fig.savefig('../../figures/subplots_example.png',bbox_inches='tight')
```
---
---
## Plotting 2D data: contour (and contourf) plots
```
import matplotlib.pyplot as plt
import numpy as np
```
* `contour()` and `contourf()` draw contour lines and filled contours, respectively
* good for 2D gridded data
** Note: `contourf()` differs from the Matlab version in that it does not draw the polygon edges. To draw edges, add line contours with calls to `contour()`.
`contour(Z)` - make a contour plot of an array Z. The level values are chosen automatically, axes will refer to indices in the array.
`contour(X, Y, Z)` - X, Y specify the (x, y) coordinates of the surface
`contour(X, Y, Z, N)` - contour up to N automatically-chosen levels
`contour(X, Y, Z, [level1, level2])` - contour on specific levels, e.g. level1, level2.
```
# Let's create a function to generate some data
def fun(x,y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
# Create a regular (x,y) grid
n = 200
x1d = np.linspace(-3,3,n)
y1d = np.linspace(-3,3,n)
X, Y = np.meshgrid(x1d, y1d) # repeat x y times and y x times
# Calculate the data
data = fun(X,Y)
# A simple example first:
plt.contour(data);
#plt.contour(X, Y, data);
# Plot subplots using contour and contourf
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4))
ax1.contour(X, Y, data, 10);
ax2.contourf(X, Y, data, 10);
#ax3.contour(X, Y, data, 10, colors='k');
#ax3.contourf(X, Y, data, 10);
```
### How to add a colorbar?
When adding a **colorbar**, it needs to know the relevant *axes* and *mappable* content - especially when working with subplots or layered figures.
Note that a colorbar will also have its own axes properties...
We tell matplotlib which plotted values to use for the colorbar content with: `fig.colorbar(mappable, ax=ax_no)`
```
# Plot contour and contourf with colorbars
# By default matplotlib contours negative values with a dashed line. This behaviour can be changed with rcparams:
#plt.rcParams['contour.negative_linestyle']= 'solid' # Reset to default with `= 'dashed'`
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4))
ax1.contour(X, Y, data, 10)
mappable2 = ax2.contourf(X, Y, data, 10)
#mappable2.set_clim(0,1)
ax3.contour(X, Y, data, 10, colors='k')
mappable3 = ax3.contourf(X, Y, data, 10)
fig.colorbar(mappable2, ax=ax2)
fig.colorbar(mappable3, ax=ax3);
```
#### Mini exercise: 10 min
Play around with the lines of code in the cell above, and see how the figure changes, e.g.
* What happens if you try to add a colorbar to ax1?
*Answer: Lines appear rather than blocks of colour.*
* Try plotting chosen contour levels for ax2 or ax3, and see what happens to the colorbar?
*Answer: The max/min levels will set the limits of your colorbar. Values outside these limits will appear white unless you specify `extend='max'`, `'min'` or `'both'`.*
```
# Examples:
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4))
mappable1 = ax1.contour(X, Y, data, 10)
mappable2 = ax2.contourf(X, Y, data, levels=np.linspace(-0.5,0.5,11))
#mappable2.set_clim(0,1)
ax3.contour(X, Y, data, 10, colors='k')
mappable3 = ax3.contourf(X, Y, data, 10, levels=np.linspace(-0.5,0.5,11), extend='both')
fig.colorbar(mappable1, ax=ax1)
fig.colorbar(mappable2, ax=ax2)
fig.colorbar(mappable3, ax=ax3);
```
---
## Final matplotlib exercise (20 mins)
Reproduce the figure below by using `contourf()` to show a map of sea surface temperature, and `plot()` for a zonally averaged temperature curve.
The code for loading and processing the data is provided below, so you can focus on producing the figure...
Data source: https://podaac-tools.jpl.nasa.gov/las/UI.vm
Dataset: AMSR-E Level 3 Sea Surface Temperature for Climate Model Comparison.
Variable: Sea Surface Temperature (K).
Time : 16-JUN-2002 00:00.
Spacial resolution: 1$^{\circ}$x1$^{\circ}$, 361 by 180 points (longitude by latitude).
Total Number of Records: 64980.
All the data processing is handled for you here, with the following steps:
* Read the data using `np.genfromtxt` (very similar to `np.loadtxt`, but can handle missing values).
* Reshape the 1D data into a 2D lat-lon grid.
* Calculate the zonal-mean temperature.
```
# Read modelling sst data
lon_raw, lat_raw, sst_raw = np.genfromtxt('../../data/AMSR-E_Level_3_Sea_Surface_Temperature_for_Climate_Model_Comparison.csv',
delimiter=',', skip_header=10, missing_values='-1.E+34',
usemask=True, usecols=(2, 3, 4), unpack=True)
# Reshape into a grid of sst with corresponding lat and lon coordinates
lon = np.unique(lon_raw)
lat = np.unique(lat_raw)
sst = np.reshape(sst_raw,(len(lat),len(lon)))
# Calculate the zonal-mean temperature here
temp_zonal_mean = np.nanmean(sst,1);
```
Now, plot the data...
```
# Example Solution
# == Increasing the font size to improve readability ==
plt.rcParams.update({"font.size": 20})
# == set the subplot layout ==
fig, ax = plt.subplots(1, 2, figsize=(12,8),
gridspec_kw={"width_ratios":[8, 1]}, sharey = True)
fig.subplots_adjust(wspace=0.05)
# plot the map on axis 0
cb = ax[0].contourf(lon, lat, sst, cmap='inferno')
ax[0].set_title('Sea surface temperature 16 June 2002')
ax[0].set(xlabel='Longitude', ylabel='Latitude', ylim = [-80,80])
# plot the zonal mean on axis 1
ax[1].plot(temp_zonal_mean, lat)
ax[1].set(xlabel='Mean temp')
# create a separate whole-width axis (cbar_ax) for the colorbar at the bottom
# -> set position relative to other axes.
fig.subplots_adjust(bottom=0.2)
pos0 = ax[0].get_position() # [x0=left, y0=bottom, x1=right, y1=top]
pos1 = ax[1].get_position()
cbar_ax = fig.add_axes([pos0.x0, 0.08, pos1.x1-pos0.x0, 0.03]) # [left, bottom, width, height]
fig.colorbar(cb, cax=cbar_ax, label=r"Temperature (K)", orientation='horizontal');
#fig.savefig('../../figures/matplotlib_map.png', dpi=300, bbox_inches='tight')
```
**NB. There is no "right" answer - you may find other ways to produce the same figure (or something better!)**
## References:
* https://matplotlib.org/faq/usage_faq.html
* http://www.labri.fr/perso/nrougier/teaching/matplotlib/matplotlib.html
* https://matplotlib.org/stable/index.html
* https://matplotlib.org/stable/gallery/index.html
* https://github.com/matplotlib/cheatsheets
| github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
logistic = lambda x: 1/(1+np.exp(-x))
np.random.seed(0)
X1 = np.random.randn(20, 2)+np.array([4, 4])
X2 = np.random.randn(20, 2)+np.array([1, 2])
plt.scatter(X1[:, 0], X1[:, 1])
plt.scatter(X2[:, 0], X2[:, 1])
plt.axis("equal")
def get_logistic_loss(X1, X2, a, b, c):
return np.sum(logistic(a*X1[:, 0]+b*X1[:, 1] + c)**2) + np.sum((1-logistic(a*X2[:, 0]+b*X2[:, 1] + c))**2)
def plot_logistic_regression_predictions(X1, X2, a, b, c):
plt.scatter(X1[:, 0], X1[:, 1])
plt.scatter(X2[:, 0], X2[:, 1])
X = np.concatenate((X1, X2), axis=0)
xmin = np.min(X, axis=0)
xmax = np.max(X, axis=0)
iv = max(xmax[1]-xmin[1], xmax[0]-xmin[0])
p0 = -c*np.array([a, b])/(a**2 + b**2)
v = np.array([-b, a])
mag = np.sqrt(np.sum(v**2))
if mag > 0:
v = v/mag
p = p0 - 2*iv*v
q = p0 + 2*iv*v
plt.plot([p[0], q[0]], [p[1], q[1]])
rg = xmax[0] - xmin[0]
plt.xlim([xmin[0]-0.2*rg, xmax[0]+0.2*rg])
rg = xmax[1] - xmin[1]
plt.ylim([xmin[1]-0.2*rg, xmax[1]+0.2*rg])
wrong = 0
for x in X1:
y = logistic(a*x[0] + b*x[1] + c)
proj = p0 + np.sum(v*(x-p0))*v
plt.plot([x[0], proj[0]], [x[1], proj[1]], c='C0')
if y > 0.5:
plt.scatter([x[0]], [x[1]], 200, c='C0', marker='x')
wrong += 1
for x in X2:
y = logistic(a*x[0] + b*x[1] + c)
proj = p0 + np.sum(v*(x-p0))*v
plt.plot([x[0], proj[0]], [x[1], proj[1]], c='C1')
if y < 0.5:
plt.scatter([x[0]], [x[1]], 200, c='C1', marker='x')
wrong += 1
loss = get_logistic_loss(X1, X2, a, b, c)
N = X.shape[0]
plt.title("a = {:.3f}, b = {:.3f}, c = {:.3f}\nLoss = {:.3f}, {} Wrong ({} % Accuracy)".format(a, b, c, loss, wrong, int(100*(N-wrong)/N)))
plt.axis("equal")
losses = []
steps = []
step = 0.01
n_iters = 150
a = 0
b = 0
c = 0
X = np.concatenate((X1, X2))
y = np.concatenate((np.zeros(X1.shape[0]), np.ones(X2.shape[0])))
plt.figure(figsize=(10, 5))
for it in range(n_iters):
## TODO: Update a, b, and c with Gradient descent
f = logistic(a*X[:, 0] + b*X[:, 1] + c)
## TODO: Fill this in to perform gradient descent on a, b, and c
steps.append([a, b])
loss = get_logistic_loss(X1, X2, a, b, c)
losses.append(loss)
plt.clf()
plt.subplot(121)
plot_logistic_regression_predictions(X1, X2, a, b, c)
plt.xlim([-1, 7])
plt.ylim([-1, 7])
plt.subplot(122)
plt.plot(losses)
plt.xlim([0, n_iters])
plt.ylim([0, np.max(losses)])
plt.title("Loss")
plt.xlabel("Iteration")
```
| github_jupyter |
```
# Let printing work the same in Python 2 and 3
from __future__ import print_function
# Turning on inline plots -- just for use in ipython notebooks.
import matplotlib
matplotlib.use('nbagg')
import numpy as np
import matplotlib.pyplot as plt
```
# Artists
Anything that can be displayed in a Figure is an [`Artist`](http://matplotlib.org/users/artists.html). There are two main classes of Artists: primatives and containers. Below is a sample of these primitives.
```
"""
Show examples of matplotlib artists
http://matplotlib.org/api/artist_api.html
Several examples of standard matplotlib graphics primitives (artists)
are drawn using matplotlib API. Full list of artists and the
documentation is available at
http://matplotlib.org/api/artist_api.html
Copyright (c) 2010, Bartosz Telenczuk
License: This work is licensed under the BSD. A copy should be
included with this source code, and is also available at
http://www.opensource.org/licenses/bsd-license.php
"""
from matplotlib.collections import PatchCollection
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
fig, ax = plt.subplots(1, 1, figsize=(7,7))
# create 3x3 grid to plot the artists
pos = np.mgrid[0.2:0.8:3j, 0.2:0.8:3j].reshape(2, -1)
patches = []
# add a circle
art = mpatches.Circle(pos[:, 0], 0.1, ec="none")
patches.append(art)
plt.text(pos[0, 0], pos[1, 0] - 0.15, "Circle", ha="center", size=14)
# add a rectangle
art = mpatches.Rectangle(pos[:, 1] - [0.025, 0.05], 0.05, 0.1, ec="none")
patches.append(art)
plt.text(pos[0, 1], pos[1, 1] - 0.15, "Rectangle", ha="center", size=14)
# add a wedge
wedge = mpatches.Wedge(pos[:, 2], 0.1, 30, 270, ec="none")
patches.append(wedge)
plt.text(pos[0, 2], pos[1, 2] - 0.15, "Wedge", ha="center", size=14)
# add a Polygon
polygon = mpatches.RegularPolygon(pos[:, 3], 5, 0.1)
patches.append(polygon)
plt.text(pos[0, 3], pos[1, 3] - 0.15, "Polygon", ha="center", size=14)
#add an ellipse
ellipse = mpatches.Ellipse(pos[:, 4], 0.2, 0.1)
patches.append(ellipse)
plt.text(pos[0, 4], pos[1, 4] - 0.15, "Ellipse", ha="center", size=14)
#add an arrow
arrow = mpatches.Arrow(pos[0, 5] - 0.05, pos[1, 5] - 0.05, 0.1, 0.1, width=0.1)
patches.append(arrow)
plt.text(pos[0, 5], pos[1, 5] - 0.15, "Arrow", ha="center", size=14)
# add a path patch
Path = mpath.Path
verts = np.array([
(0.158, -0.257),
(0.035, -0.11),
(-0.175, 0.20),
(0.0375, 0.20),
(0.085, 0.115),
(0.22, 0.32),
(0.3, 0.005),
(0.20, -0.05),
(0.158, -0.257),
])
verts = verts - verts.mean(0)
codes = [Path.MOVETO,
Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.LINETO,
Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CLOSEPOLY]
path = mpath.Path(verts / 2.5 + pos[:, 6], codes)
patch = mpatches.PathPatch(path)
patches.append(patch)
plt.text(pos[0, 6], pos[1, 6] - 0.15, "PathPatch", ha="center", size=14)
# add a fancy box
fancybox = mpatches.FancyBboxPatch(
pos[:, 7] - [0.025, 0.05], 0.05, 0.1,
boxstyle=mpatches.BoxStyle("Round", pad=0.02))
patches.append(fancybox)
plt.text(pos[0, 7], pos[1, 7] - 0.15, "FancyBoxPatch", ha="center", size=14)
# add a line
x,y = np.array([[-0.06, 0.0, 0.1], [0.05,-0.05, 0.05]])
line = mlines.Line2D(x+pos[0, 8], y+pos[1, 8], lw=5.)
plt.text(pos[0, 8], pos[1, 8] - 0.15, "Line2D", ha="center", size=14)
collection = PatchCollection(patches)
ax.add_collection(collection)
ax.add_line(line)
ax.set_axis_off()
plt.show()
```
Containers are objects like *Figure* and *Axes*. Containers are given primitives to draw. The plotting functions we discussed back in Parts 1 & 2 are convenience functions that generate these primitives and places them into the appropriate containers. In fact, most of those functions will return artist objects (or a list of artist objects) as well as store them into the appropriate axes container.
As discussed in Part 3, there is a wide range of properties that can be defined for your plots. These properties are processed and applied to their primitives. Ultimately, you can override anything you want just by directly setting a property to the object itself.
```
fig, ax = plt.subplots(1, 1)
lines = plt.plot([1, 2, 3, 4], [1, 2, 3, 4], 'b', [1, 2, 3, 4], [4, 3, 2, 1], 'r')
lines[0].set(linewidth=5)
lines[1].set(linewidth=10, alpha=0.7)
plt.show()
```
To see what properties are set for an artist, use [`getp()`](http://matplotlib.org/api/artist_api.html#matplotlib.artist.getp)
```
fig = plt.figure()
print(plt.getp(fig.patch))
plt.close(fig)
```
# Collections
In addition to the Figure and Axes containers, there is another special type of container called a [`Collection`](http://matplotlib.org/api/collections_api.html). A Collection usually contains a list of primitives of the same kind that should all be treated similiarly. For example, a [`CircleCollection`](http://matplotlib.org/api/collections_api.html#matplotlib.collections.CircleCollection) would have a list of [`Circle`](http://matplotlib.org/api/artist_api.html#matplotlib.patches.Circle) objects all with the same color, size, and edge width. Individual property values for artists in the collection can also be set (in some cases).
```
from matplotlib.collections import LineCollection
fig, ax = plt.subplots(1, 1)
# A collection of 3 lines
lc = LineCollection([[(4, 10), (16, 10)],
[(2, 2), (10, 15), (6, 7)],
[(14, 3), (1, 1), (3, 5)]])
lc.set_color('r')
lc.set_linewidth(5)
ax.add_collection(lc)
ax.set_xlim(0, 18)
ax.set_ylim(0, 18)
plt.show()
# Now set individual properties in a collection
fig, ax = plt.subplots(1, 1)
lc = LineCollection([[(4, 10), (16, 10)],
[(2, 2), (10, 15), (6, 7)],
[(14, 3), (1, 1), (3, 5)]])
lc.set_color(['r', 'blue', (0.2, 0.9, 0.3)])
lc.set_linewidth([4, 3, 6])
ax.add_collection(lc)
ax.set_xlim(0, 18)
ax.set_ylim(0, 18)
plt.show()
```
There are other kinds of collections that are not just simply a list of primitives, but are Artists in their own right. These special kinds of collections take advantage of various optimizations that can be assumed when rendering similar or identical things. You use these collections all the time whether you realize it or not! Markers are implemented this way (so, whenever you do `plot()` or `scatter()`, for example).
```
from matplotlib.collections import RegularPolyCollection
fig, ax = plt.subplots(1, 1)
offsets = np.random.rand(20, 2)
collection = RegularPolyCollection(
numsides=5, # a pentagon
sizes=(150,),
offsets=offsets,
transOffset=ax.transData,
)
ax.add_collection(collection)
plt.show()
```
## Exercise 5.1
Give yourselves 4 gold stars!
Hint: [StarPolygonCollection](http://matplotlib.org/api/collections_api.html#matplotlib.collections.StarPolygonCollection)
```
%load exercises/5.1-goldstar.py
from matplotlib.collections import StarPolygonCollection
fig, ax = plt.subplots(1, 1)
collection = StarPolygonCollection(5,
offsets=[(0.5, 0.5)],
transOffset=ax.transData)
ax.add_collection(collection)
plt.show()
```
| github_jupyter |
```
# default_exp optimizer
#export
from fastai.torch_basics import *
#hide
from nbdev.showdoc import *
```
# Optimizer
> Define the general fastai optimizer and the variants
## `_BaseOptimizer` -
```
#export
class _BaseOptimizer():
"Common functionality between `Optimizer` and `OptimWrapper`"
def all_params(self, n=slice(None), with_grad=False):
res = L((p,pg,self.state[p],hyper) for pg,hyper in zip(self.param_lists[n],self.hypers[n]) for p in pg)
return L(o for o in res if o[0].grad is not None) if with_grad else res
def _set_require_grad(self, rg, p,pg,state,h): p.requires_grad_(rg or state.get('force_train', False))
def freeze_to(self, n):
self.frozen_idx = n if n >= 0 else len(self.param_lists) + n
if self.frozen_idx >= len(self.param_lists):
warn(f"Freezing {self.frozen_idx} groups; model has {len(self.param_lists)}; whole model is frozen.")
for o in self.all_params(slice(n, None)): self._set_require_grad(True, *o)
for o in self.all_params(slice(None, n)): self._set_require_grad(False, *o)
def freeze(self):
assert(len(self.param_lists)>1)
self.freeze_to(-1)
def set_freeze(self, n, rg, ignore_force_train=False):
for p in self.param_lists[n]: p.requires_grad_(rg or (state.get('force_train', False) and not ignore_force_train))
def unfreeze(self): self.freeze_to(0)
def set_hypers(self, **kwargs): L(kwargs.items()).starmap(self.set_hyper)
def _set_hyper(self, k, v):
for v_,h in zip(v, self.hypers): h[k] = v_
def set_hyper(self, k, v):
if isinstance(v, slice):
if v.start: v = even_mults(v.start, v.stop, len(self.param_lists))
else: v = [v.stop/10]*(len(self.param_lists)-1) + [v.stop]
v = L(v, use_list=None)
if len(v)==1: v = v*len(self.param_lists)
assert len(v) == len(self.hypers), f"Trying to set {len(v)} values for {k} but there are {len(self.param_lists)} parameter groups."
self._set_hyper(k, v)
@property
def param_groups(self): return [{**{'params': pg}, **hp} for pg,hp in zip(self.param_lists, self.hypers)]
@param_groups.setter
def param_groups(self, v):
for pg,v_ in zip(self.param_lists,v): pg = v_['params']
for hyper,v_ in zip(self.hypers,v):
for k,t in v_.items():
if k != 'params': hyper[k] = t
add_docs(_BaseOptimizer,
all_params="List of param_groups, parameters, and hypers",
freeze_to="Freeze parameter groups up to `n`",
freeze="Freeze up to last parameter group",
set_freeze="Set `rg` for parameter group `n` only",
unfreeze="Unfreeze the entire model",
set_hypers="`set_hyper` for all `kwargs`",
set_hyper="Set the value(s) in `v` for hyper-parameter `k`")
#export
def _update(state, new=None):
if new is None: return state
if isinstance(new, dict): state.update(new)
return state
```
## `Optimizer` -
```
# export
@log_args(but='params,cbs,defaults')
class Optimizer(_BaseOptimizer):
"Base optimizer class for the fastai library, updating `params` with `cbs`"
_keep_on_clear = ['force_train', 'do_wd']
def __init__(self, params, cbs, train_bn=True, **defaults):
params = L(params)
self.cbs,self.state,self.train_bn = L(cbs),defaultdict(dict),train_bn
defaults = merge(*self.cbs.attrgot('defaults'), defaults)
self.param_lists = L(L(p) for p in params) if isinstance(params[0], (L,list)) else L([params])
self.hypers = L({} for _ in range_of(self.param_lists))
self.set_hypers(**defaults)
self.frozen_idx = 0
def zero_grad(self):
for p,*_ in self.all_params(with_grad=True):
p.grad.detach_()
p.grad.zero_()
def step(self):
for p,pg,state,hyper in self.all_params(with_grad=True):
for cb in self.cbs: state = _update(state, cb(p, **{**state, **hyper}))
self.state[p] = state
def clear_state(self):
for p,pg,state,hyper in self.all_params():
self.state[p] = {k: state[k] for k in self._keep_on_clear if k in state}
def state_dict(self):
state = [self.state[p] for p,*_ in self.all_params()]
return {'state': state, 'hypers': self.hypers}
def load_state_dict(self, sd):
assert len(sd["hypers"]) == len(self.param_lists)
assert len(sd["state"]) == sum([len(pg) for pg in self.param_lists])
self.hypers = sd['hypers']
self.state = {p: s for p,s in zip(self.all_params().itemgot(0), sd['state'])}
add_docs(Optimizer,
zero_grad="Standard PyTorch API: Zero all the grad attributes of the parameters",
step="Standard PyTorch API: Update the stats and execute the steppers in on all parameters that have a grad",
state_dict="Return the state of the optimizer in a dictionary",
load_state_dict="Load the content of `sd`",
clear_state="Reset the state of the optimizer")
```
### Initializing an Optimizer
`params` will be used to create the `param_groups` of the optimizer. If it's a collection (or a generator) of parameters, it will be a `L` containing one `L` with all the parameters. To define multiple parameter groups `params` should be passed as a collection (or a generator) of `L`s.
> Note: In PyTorch, <code>model.parameters()</code> returns a generator with all the parameters, that you can directly pass to <code>Optimizer</code>.
```
opt = Optimizer([1,2,3], noop)
test_eq(opt.param_lists, [[1,2,3]])
opt = Optimizer(range(3), noop)
test_eq(opt.param_lists, [[0,1,2]])
opt = Optimizer([[1,2],[3]], noop)
test_eq(opt.param_lists, [[1,2],[3]])
opt = Optimizer(([o,o+1] for o in range(0,4,2)), noop)
test_eq(opt.param_lists, [[0,1],[2,3]])
```
`cbs` is a list of functions that will be composed when applying the step. For instance, you can compose a function making the SGD step, with another one applying weight decay. Additionally, each `cb` can have a `defaults` attribute that contains hyper-parameters and their default value. Those are all gathered at initialization, and new values can be passed to override those defaults with the `defaults` kwargs. The steppers will be called by `Optimizer.step` (which is the standard PyTorch name), and gradients can be cleared with `Optimizer.zero_grad` (also a standard PyTorch name).
Once the defaults have all been pulled off, they are copied as many times as there are `param_groups` and stored in `hypers`. To apply different hyper-parameters to different groups (differential learning rates, or no weight decay for certain layers for instance), you will need to adjust those values after the init.
```
def tst_arg(p, lr=0, **kwargs): return p
tst_arg.defaults = dict(lr=1e-2)
def tst_arg2(p, lr2=0, **kwargs): return p
tst_arg2.defaults = dict(lr2=1e-3)
def tst_arg3(p, mom=0, **kwargs): return p
tst_arg3.defaults = dict(mom=0.9)
def tst_arg4(p, **kwargs): return p
opt = Optimizer([1,2,3], [tst_arg,tst_arg2, tst_arg3])
test_eq(opt.hypers, [{'lr2': 1e-3, 'mom': 0.9, 'lr': 1e-2}])
opt = Optimizer([1,2,3], tst_arg, lr=0.1)
test_eq(opt.hypers, [{'lr': 0.1}])
opt = Optimizer([[1,2],[3]], tst_arg)
test_eq(opt.hypers, [{'lr': 1e-2}, {'lr': 1e-2}])
opt = Optimizer([[1,2],[3]], tst_arg, lr=0.1)
test_eq(opt.hypers, [{'lr': 0.1}, {'lr': 0.1}])
```
For each hyper-parameter, you can pass a slice or a collection to set them, if there are multiple parameter groups. A slice will be converted to a log-uniform collection from its beginning to its end, or if it only has an end `e`, to a collection of as many values as there are parameter groups that are `...,e/10,e/10,e`.
Setting an hyper-parameter with a collection that has a different number of elements than the optimizer has parameter groups will raise an error.
```
opt = Optimizer([[1,2],[3]], tst_arg, lr=[0.1,0.2])
test_eq(opt.hypers, [{'lr': 0.1}, {'lr': 0.2}])
opt = Optimizer([[1,2],[3],[4]], tst_arg, lr=slice(1e-2))
test_eq(opt.hypers, [{'lr': 1e-3}, {'lr': 1e-3}, {'lr': 1e-2}])
opt = Optimizer([[1,2],[3],[4]], tst_arg, lr=slice(1e-4,1e-2))
test_eq(opt.hypers, [{'lr': 1e-4}, {'lr': 1e-3}, {'lr': 1e-2}])
test_eq(opt.param_groups, [{'params': [1,2], 'lr': 1e-4}, {'params': [3], 'lr': 1e-3}, {'params': [4], 'lr': 1e-2}])
test_fail(lambda: Optimizer([[1,2],[3],[4]], tst_arg, lr=np.array([0.1,0.2])))
```
### Basic steppers
To be able to give examples of optimizer steps, we will need some steppers, like the following:
```
#export
def sgd_step(p, lr, **kwargs):
p.data.add_(p.grad.data, alpha=-lr)
def tst_param(val, grad=None):
"Create a tensor with `val` and a gradient of `grad` for testing"
res = tensor([val]).float()
res.grad = tensor([val/10 if grad is None else grad]).float()
return res
p = tst_param(1., 0.1)
sgd_step(p, 1.)
test_eq(p, tensor([0.9]))
test_eq(p.grad, tensor([0.1]))
#export
def weight_decay(p, lr, wd, do_wd=True, **kwargs):
"Weight decay as decaying `p` with `lr*wd`"
if do_wd and wd!=0: p.data.mul_(1 - lr*wd)
weight_decay.defaults = dict(wd=0.)
p = tst_param(1., 0.1)
weight_decay(p, 1., 0.1)
test_eq(p, tensor([0.9]))
test_eq(p.grad, tensor([0.1]))
#export
def l2_reg(p, lr, wd, do_wd=True, **kwargs):
"L2 regularization as adding `wd*p` to `p.grad`"
if do_wd and wd!=0: p.grad.data.add_(p.data, alpha=wd)
l2_reg.defaults = dict(wd=0.)
p = tst_param(1., 0.1)
l2_reg(p, 1., 0.1)
test_eq(p, tensor([1.]))
test_eq(p.grad, tensor([0.2]))
```
> Warning: Weight decay and L2 regularization is the same thing for basic SGD, but for more complex optimizers, they are very different.
### Making the step
```
show_doc(Optimizer.step)
```
This method will loop over all param groups, then all parameters for which `grad` is not None and call each function in `stepper`, passing it the parameter `p` with the hyper-parameters in the corresponding dict in `hypers`.
```
#test basic step
r = L.range(4)
def tst_params(): return r.map(tst_param)
params = tst_params()
opt = Optimizer(params, sgd_step, lr=0.1)
opt.step()
test_close([p.item() for p in params], r.map(mul(0.99)))
#test two steps
params = tst_params()
opt = Optimizer(params, [weight_decay, sgd_step], lr=0.1, wd=0.1)
opt.step()
test_close([p.item() for p in params], r.map(mul(0.98)))
#test None gradients are ignored
params = tst_params()
opt = Optimizer(params, sgd_step, lr=0.1)
params[-1].grad = None
opt.step()
test_close([p.item() for p in params], [0., 0.99, 1.98, 3.])
#test discriminative lrs
params = tst_params()
opt = Optimizer([params[:2], params[2:]], sgd_step, lr=0.1)
opt.hypers[0]['lr'] = 0.01
opt.step()
test_close([p.item() for p in params], [0., 0.999, 1.98, 2.97])
show_doc(Optimizer.zero_grad)
params = tst_params()
opt = Optimizer(params, [weight_decay, sgd_step], lr=0.1, wd=0.1)
opt.zero_grad()
[test_eq(p.grad, tensor([0.])) for p in params];
```
Some of the `Optimizer` `cbs` can be functions updating the state associated with a parameter. That state can then be used by any stepper. The best example is a momentum calculation.
```
def tst_stat(p, **kwargs):
s = kwargs.get('sum', torch.zeros_like(p)) + p.data
return {'sum': s}
tst_stat.defaults = {'mom': 0.9}
#Test Optimizer init
opt = Optimizer([1,2,3], tst_stat)
test_eq(opt.hypers, [{'mom': 0.9}])
opt = Optimizer([1,2,3], tst_stat, mom=0.99)
test_eq(opt.hypers, [{'mom': 0.99}])
#Test stat
x = torch.randn(4,5)
state = tst_stat(x)
assert 'sum' in state
test_eq(x, state['sum'])
state = tst_stat(x, **state)
test_eq(state['sum'], 2*x)
```
## Statistics
```
# export
def average_grad(p, mom, dampening=False, grad_avg=None, **kwargs):
"Keeps track of the avg grads of `p` in `state` with `mom`."
if grad_avg is None: grad_avg = torch.zeros_like(p.grad.data)
damp = 1-mom if dampening else 1.
grad_avg.mul_(mom).add_(p.grad.data, alpha=damp)
return {'grad_avg': grad_avg}
average_grad.defaults = dict(mom=0.9)
```
`dampening=False` gives the classical formula for momentum in SGD:
```
new_val = old_val * mom + grad
```
whereas `dampening=True` makes it an exponential moving average:
```
new_val = old_val * mom + grad * (1-mom)
```
```
p = tst_param([1,2,3], [4,5,6])
state = {}
state = average_grad(p, mom=0.9, **state)
test_eq(state['grad_avg'], p.grad)
state = average_grad(p, mom=0.9, **state)
test_eq(state['grad_avg'], p.grad * 1.9)
#Test dampening
state = {}
state = average_grad(p, mom=0.9, dampening=True, **state)
test_eq(state['grad_avg'], 0.1*p.grad)
state = average_grad(p, mom=0.9, dampening=True, **state)
test_close(state['grad_avg'], (0.1*0.9+0.1)*p.grad)
# export
def average_sqr_grad(p, sqr_mom, dampening=True, sqr_avg=None, **kwargs):
if sqr_avg is None: sqr_avg = torch.zeros_like(p.grad.data)
damp = 1-sqr_mom if dampening else 1.
sqr_avg.mul_(sqr_mom).addcmul_(p.grad.data, p.grad.data, value=damp)
return {'sqr_avg': sqr_avg}
average_sqr_grad.defaults = dict(sqr_mom=0.99)
```
`dampening=False` gives the classical formula for momentum in SGD:
```
new_val = old_val * mom + grad**2
```
whereas `dampening=True` makes it an exponential moving average:
```
new_val = old_val * mom + (grad**2) * (1-mom)
```
```
p = tst_param([1,2,3], [4,5,6])
state = {}
state = average_sqr_grad(p, sqr_mom=0.99, dampening=False, **state)
test_eq(state['sqr_avg'], p.grad.pow(2))
state = average_sqr_grad(p, sqr_mom=0.99, dampening=False, **state)
test_eq(state['sqr_avg'], p.grad.pow(2) * 1.99)
#Test dampening
state = {}
state = average_sqr_grad(p, sqr_mom=0.99, **state)
test_close(state['sqr_avg'], 0.01*p.grad.pow(2))
state = average_sqr_grad(p, sqr_mom=0.99, **state)
test_close(state['sqr_avg'], (0.01*0.99+0.01)*p.grad.pow(2))
```
### Freezing part of the model
```
show_doc(Optimizer.freeze, name="Optimizer.freeze")
show_doc(Optimizer.freeze_to, name="Optimizer.freeze_to")
show_doc(Optimizer.unfreeze, name="Optimizer.unfreeze")
#Freezing the first layer
params = [tst_params(), tst_params(), tst_params()]
opt = Optimizer(params, sgd_step, lr=0.1)
opt.freeze_to(1)
req_grad = Self.requires_grad()
test_eq(L(params[0]).map(req_grad), [False]*4)
for i in {1,2}: test_eq(L(params[i]).map(req_grad), [True]*4)
#Unfreezing
opt.unfreeze()
for i in range(2): test_eq(L(params[i]).map(req_grad), [True]*4)
#TODO: test warning
# opt.freeze_to(3)
```
Parameters such as batchnorm weights/bias can be marked to always be in training mode, just put `force_train=true` in their state.
```
params = [tst_params(), tst_params(), tst_params()]
opt = Optimizer(params, sgd_step, lr=0.1)
for p in L(params[1])[[1,3]]: opt.state[p] = {'force_train': True}
opt.freeze()
test_eq(L(params[0]).map(req_grad), [False]*4)
test_eq(L(params[1]).map(req_grad), [False, True, False, True])
test_eq(L(params[2]).map(req_grad), [True]*4)
```
### Serializing
```
show_doc(Optimizer.state_dict)
show_doc(Optimizer.load_state_dict)
p = tst_param([1,2,3], [4,5,6])
opt = Optimizer(p, average_grad)
opt.step()
test_eq(opt.state[p]['grad_avg'], tensor([[4., 5., 6.]]))
sd = opt.state_dict()
p1 = tst_param([10,20,30], [40,50,60])
opt = Optimizer(p1, average_grad, mom=0.99)
test_eq(opt.hypers[0]['mom'], 0.99)
test_eq(opt.state, {})
opt.load_state_dict(sd)
test_eq(opt.hypers[0]['mom'], 0.9)
test_eq(opt.state[p1]['grad_avg'], tensor([[4., 5., 6.]]))
show_doc(Optimizer.clear_state)
p = tst_param([1,2,3], [4,5,6])
opt = Optimizer(p, average_grad)
opt.state[p] = {'force_train': True}
opt.step()
test_eq(opt.state[p]['grad_avg'], tensor([[4., 5., 6.]]))
opt.clear_state()
test_eq(opt.state[p], {'force_train': True})
```
## Optimizers
### SGD with momentum
```
#export
def momentum_step(p, lr, grad_avg, **kwargs):
"Step for SGD with momentum with `lr`"
p.data.add_(grad_avg, alpha=-lr)
#export
@log_args(to_return=True, but_as=Optimizer.__init__)
def SGD(params, lr, mom=0., wd=0., decouple_wd=True):
"A `Optimizer` for SGD with `lr` and `mom` and `params`"
cbs = [weight_decay] if decouple_wd else [l2_reg]
if mom != 0: cbs.append(average_grad)
cbs.append(sgd_step if mom==0 else momentum_step)
return Optimizer(params, cbs, lr=lr, mom=mom, wd=wd)
```
Optional weight decay of `wd` is applied, as true weight decay (decay the weights directly) if `decouple_wd=True` else as L2 regularization (add the decay to the gradients).
```
#Vanilla SGD
params = tst_params()
opt = SGD(params, lr=0.1)
opt.step()
test_close([p.item() for p in params], [i*0.99 for i in range(4)])
opt.step()
[p.item() for p in params]
test_close([p.item() for p in params], [i*0.98 for i in range(4)])
#SGD with momentum
params = tst_params()
opt = SGD(params, lr=0.1, mom=0.9)
assert isinstance(opt, Optimizer)
opt.step()
test_close([p.item() for p in params], [i*0.99 for i in range(4)])
opt.step()
[p.item() for p in params]
test_close([p.item() for p in params], [i*(1 - 0.1 * (0.1 + 0.1*1.9)) for i in range(4)])
for i,p in enumerate(params): test_close(opt.state[p]['grad_avg'].item(), i*0.19)
```
Test weight decay, notice how we can see that L2 regularization is different from weight decay even for simple SGD with momentum.
```
params = tst_params()
#Weight decay
opt = SGD(params, lr=0.1, mom=0.9, wd=0.1)
opt.step()
test_close([p.item() for p in params], [i*0.98 for i in range(4)])
#L2 reg
opt = SGD(params, lr=0.1, mom=0.9, wd=0.1, decouple_wd=False)
opt.step()
#TODO: fix cause this formula was wrong
#test_close([p.item() for p in params], [i*0.97 for i in range(4)])
```
### RMSProp
```
#export
def rms_prop_step(p, lr, sqr_avg, eps, grad_avg=None, **kwargs):
"Step for SGD with momentum with `lr`"
denom = sqr_avg.sqrt().add_(eps)
p.data.addcdiv_((grad_avg if grad_avg is not None else p.grad), denom, value=-lr)
rms_prop_step.defaults = dict(eps=1e-8)
#export
@log_args(to_return=True, but_as=Optimizer.__init__)
def RMSProp(params, lr, sqr_mom=0.99, mom=0., wd=0., decouple_wd=True):
"A `Optimizer` for RMSProp with `lr`, `sqr_mom`, `mom` and `params`"
cbs = [weight_decay] if decouple_wd else [l2_reg]
cbs += ([average_sqr_grad] if mom==0. else [average_grad, average_sqr_grad])
cbs.append(rms_prop_step)
return Optimizer(params, cbs, lr=lr, mom=mom, sqr_mom=sqr_mom, wd=wd)
```
RMSProp was introduced by Geoffrey Hinton in his [course](http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf). What is named `sqr_mom` here is the `alpha` in the course. Optional weight decay of `wd` is applied, as true weight decay (decay the weights directly) if `decouple_wd=True` else as L2 regularization (add the decay to the gradients).
```
#Without momentum
params = tst_param([1,2,3], [0.1,0.2,0.3])
opt = RMSProp(params, lr=0.1)
opt.step()
test_close(params[0], tensor([0.,1.,2.]))
opt.step()
step = - 0.1 * 0.1 / (math.sqrt((0.01*0.99+0.01) * 0.1**2) + 1e-8)
test_close(params[0], tensor([step, 1+step, 2+step]))
#With momentum
params = tst_param([1,2,3], [0.1,0.2,0.3])
opt = RMSProp(params, lr=0.1, mom=0.9)
opt.step()
test_close(params[0], tensor([0.,1.,2.]))
opt.step()
step = - 0.1 * (0.1 + 0.9*0.1) / (math.sqrt((0.01*0.99+0.01) * 0.1**2) + 1e-8)
test_close(params[0], tensor([step, 1+step, 2+step]))
```
### Adam
```
#export
def step_stat(p, step=0, **kwargs):
"Register the number of steps done in `state` for `p`"
step += 1
return {'step' : step}
p = tst_param(1,0.1)
state = {}
state = step_stat(p, **state)
test_eq(state['step'], 1)
for _ in range(5): state = step_stat(p, **state)
test_eq(state['step'], 6)
#export
def debias(mom, damp, step): return damp * (1 - mom**step) / (1-mom)
#export
def adam_step(p, lr, mom, step, sqr_mom, grad_avg, sqr_avg, eps, **kwargs):
"Step for Adam with `lr` on `p`"
debias1 = debias(mom, 1-mom, step)
debias2 = debias(sqr_mom, 1-sqr_mom, step)
p.data.addcdiv_(grad_avg, (sqr_avg/debias2).sqrt() + eps, value = -lr / debias1)
return p
adam_step._defaults = dict(eps=1e-5)
#export
@log_args(to_return=True, but_as=Optimizer.__init__)
def Adam(params, lr, mom=0.9, sqr_mom=0.99, eps=1e-5, wd=0.01, decouple_wd=True):
"A `Optimizer` for Adam with `lr`, `mom`, `sqr_mom`, `eps` and `params`"
cbs = [weight_decay] if decouple_wd else [l2_reg]
cbs += [partial(average_grad, dampening=True), average_sqr_grad, step_stat, adam_step]
return Optimizer(params, cbs, lr=lr, mom=mom, sqr_mom=sqr_mom, eps=eps, wd=wd)
```
Adam was introduced by Diederik P. Kingma and Jimmy Ba in [Adam: A Method for Stochastic Optimization](https://arxiv.org/abs/1412.6980). For consistency across optimizers, we renamed `beta1` and `beta2` in the paper to `mom` and `sqr_mom`. Note that our defaults also differ from the paper (0.99 for `sqr_mom` or `beta2`, 1e-5 for `eps`). Those values seem to be better from our experiments in a wide range of situations.
Optional weight decay of `wd` is applied, as true weight decay (decay the weights directly) if `decouple_wd=True` else as L2 regularization (add the decay to the gradients).
> Note: Don't forget that `eps` is an hyper-parameter you can change. Some models won't train without a very high `eps` like 0.1 (intuitively, the higher `eps` is, the closer we are to normal SGD). The usual default of 1e-8 is often too extreme in the sense we don't manage to get as good results as with SGD.
```
params = tst_param([1,2,3], [0.1,0.2,0.3])
opt = Adam(params, lr=0.1, wd=0)
opt.step()
step = -0.1 * 0.1 / (math.sqrt(0.1**2) + 1e-8)
test_close(params[0], tensor([1+step, 2+step, 3+step]))
opt.step()
test_close(params[0], tensor([1+2*step, 2+2*step, 3+2*step]), eps=1e-3)
```
### RAdam
RAdam (for rectified Adam) was introduced by Zhang et al. in [On the Variance of the Adaptive Learning Rate and Beyond](https://arxiv.org/abs/1907.08610) to slightly modify the Adam optimizer to be more stable at the beginning of training (and thus not require a long warmup). They use an estimate of the variance of the moving average of the squared gradients (the term in the denominator of traditional Adam) and rescale this moving average by this term before performing the update.
This version also incorporates [SAdam](https://arxiv.org/abs/1908.00700); set `beta` to enable this (definition same as in the paper).
```
#export
def radam_step(p, lr, mom, step, sqr_mom, grad_avg, sqr_avg, eps, beta, **kwargs):
"Step for RAdam with `lr` on `p`"
debias1 = debias(mom, 1-mom, step)
debias2 = debias(sqr_mom, 1-sqr_mom, step)
r_inf = 2/(1-sqr_mom) - 1
r = r_inf - 2*step*sqr_mom**step/(1-sqr_mom**step)
if r > 5:
v = math.sqrt(((r-4) * (r-2) * r_inf)/((r_inf-4)*(r_inf-2)*r))
denom = (sqr_avg/debias2).sqrt()
if eps: denom += eps
if beta: denom = F.softplus(denom, beta)
p.data.addcdiv_(grad_avg, denom, value = -lr*v / debias1)
else: p.data.add_(grad_avg, alpha=-lr / debias1)
return p
radam_step._defaults = dict(eps=1e-5)
#export
@log_args(to_return=True, but_as=Optimizer.__init__)
def RAdam(params, lr, mom=0.9, sqr_mom=0.99, eps=1e-5, wd=0., beta=0., decouple_wd=True):
"A `Optimizer` for Adam with `lr`, `mom`, `sqr_mom`, `eps` and `params`"
cbs = [weight_decay] if decouple_wd else [l2_reg]
cbs += [partial(average_grad, dampening=True), average_sqr_grad, step_stat, radam_step]
return Optimizer(params, cbs, lr=lr, mom=mom, sqr_mom=sqr_mom, eps=eps, wd=wd, beta=beta)
```
This is the effective correction reported to the adam step for 500 iterations in RAdam. We can see how it goes from 0 to 1, mimicking the effect of a warm-up.
```
beta = 0.99
r_inf = 2/(1-beta) - 1
rs = np.array([r_inf - 2*s*beta**s/(1-beta**s) for s in range(5,500)])
v = np.sqrt(((rs-4) * (rs-2) * r_inf)/((r_inf-4)*(r_inf-2)*rs))
plt.plot(v);
params = tst_param([1,2,3], [0.1,0.2,0.3])
opt = RAdam(params, lr=0.1)
#The r factor is lower than 5 during the first 5 steps so updates use the average of gradients (all the same)
r_inf = 2/(1-0.99) - 1
for i in range(5):
r = r_inf - 2*(i+1)*0.99**(i+1)/(1-0.99**(i+1))
assert r <= 5
opt.step()
p = tensor([0.95, 1.9, 2.85])
test_close(params[0], p)
#The r factor is greater than 5 for the sixth step so we update with RAdam
r = r_inf - 2*6*0.99**6/(1-0.99**6)
assert r > 5
opt.step()
v = math.sqrt(((r-4) * (r-2) * r_inf)/((r_inf-4)*(r_inf-2)*r))
step = -0.1*0.1*v/(math.sqrt(0.1**2) + 1e-8)
test_close(params[0], p+step)
```
### QHAdam
QHAdam (for Quasi-Hyperbolic Adam) was introduced by Ma & Yarats in [Quasi-Hyperbolic Momentum and Adam for Deep Learning](https://arxiv.org/pdf/1810.06801.pdf) as a *"computationally cheap, intuitive to interpret, and simple to implement"* optimizer. Additional code can be found in their [qhoptim repo](https://github.com/facebookresearch/qhoptim). QHAdam is based on QH-Momentum, which introduces the immediate discount factor `nu`, encapsulating plain SGD (`nu = 0`) and momentum (`nu = 1`). QH-Momentum is defined below, where g_t+1 is the update of the moment. An interpretation of QHM is as a nu-weighted average of the momentum update step and the plain SGD update step.
> θ_t+1 ← θ_t − lr * [(1 − nu) · ∇L_t(θ_t) + nu · g_t+1]
QHAdam takes the concept behind QHM above and applies it to Adam, replacing both of Adam’s moment estimators with quasi-hyperbolic terms.
The paper's suggested default parameters are `mom = 0.999`, `sqr_mom = 0.999`, `nu_1 = 0.7` and `and nu_2 = 1.0`. When training is not stable, it is possible that setting `nu_2 < 1` can improve stability by imposing a tighter step size bound. Note that QHAdam recovers Adam when `nu_1 = nu_2 = 1.0`. QHAdam recovers RMSProp (Hinton et al., 2012) when `nu_1 = 0` and `nu_2 = 1`, and NAdam (Dozat, 2016) when `nu_1 = mom` and `nu_2 = 1`.
Optional weight decay of `wd` is applied, as true weight decay (decay the weights directly) if `decouple_wd=True` else as L2 regularization (add the decay to the gradients).
```
#export
def qhadam_step(p, lr, mom, sqr_mom, sqr_avg, nu_1, nu_2, step, grad_avg, eps, **kwargs):
debias1 = debias(mom, 1-mom, step)
debias2 = debias(sqr_mom, 1-sqr_mom, step)
p.data.addcdiv_(((1-nu_1) * p.grad.data) + (nu_1 * (grad_avg / debias1)),
(((1 - nu_2) * (p.grad.data)**2) + (nu_2 * (sqr_avg / debias2))).sqrt() + eps,
value = -lr)
return p
qhadam_step._defaults = dict(eps=1e-8)
#export
@log_args(to_return=True, but_as=Optimizer.__init__)
def QHAdam(params, lr, mom=0.999, sqr_mom=0.999, nu_1=0.7, nu_2 = 1.0, eps=1e-8, wd=0., decouple_wd=True):
"An `Optimizer` for Adam with `lr`, `mom`, `sqr_mom`, `nus`, eps` and `params`"
cbs = [weight_decay] if decouple_wd else [l2_reg]
cbs += [partial(average_grad, dampening=True), partial(average_sqr_grad, dampening=True), step_stat, qhadam_step]
return Optimizer(params, cbs, lr=lr, nu_1=nu_1, nu_2=nu_2 ,
mom=mom, sqr_mom=sqr_mom, eps=eps, wd=wd)
params = tst_param([1,2,3], [0.1,0.2,0.3])
opt = QHAdam(params, lr=0.1)
opt.step()
step = -0.1 * (((1-0.7) * 0.1) + (0.7 * 0.1)) / (
math.sqrt(((1-1.0) * 0.1**2) + (1.0 * 0.1**2)) + 1e-8)
test_close(params[0], tensor([1+step, 2+step, 3+step]))
opt.step()
test_close(params[0], tensor([1+2*step, 2+2*step, 3+2*step]), eps=1e-3)
```
### LARS/LARC
```
#export
def larc_layer_lr(p, lr, trust_coeff, wd, eps, clip=True, **kwargs):
"Computes the local lr before weight decay is applied"
p_norm,g_norm = torch.norm(p.data),torch.norm(p.grad.data)
local_lr = lr*trust_coeff * (p_norm) / (g_norm + p_norm * wd + eps)
return {'local_lr': min(lr, local_lr) if clip else local_lr}
larc_layer_lr.defaults = dict(trust_coeff=0.02, wd=0., eps=1e-8)
#export
def larc_step(p, local_lr, grad_avg=None, **kwargs):
"Step for LARC `local_lr` on `p`"
p.data.add_(p.grad.data if grad_avg is None else grad_avg, alpha = -local_lr)
#export
@log_args(to_return=True, but_as=Optimizer.__init__)
def Larc(params, lr, mom=0.9, clip=True, trust_coeff=0.02, eps=1e-8, wd=0., decouple_wd=True):
"A `Optimizer` for Adam with `lr`, `mom`, `sqr_mom`, `eps` and `params`"
cbs = [weight_decay] if decouple_wd else [l2_reg]
if mom!=0.: cbs.append(average_grad)
cbs += [partial(larc_layer_lr, clip=clip), larc_step]
return Optimizer(params, cbs, lr=lr, mom=mom, trust_coeff=trust_coeff, eps=eps, wd=wd)
```
The LARS optimizer was first introduced in [Large Batch Training of Convolutional Networks](https://arxiv.org/abs/1708.03888) then refined in its LARC variant (original LARS is with `clip=False`). A learning rate is computed for each individual layer with a certain `trust_coefficient`, then clipped to be always less than `lr`.
Optional weight decay of `wd` is applied, as true weight decay (decay the weights directly) if `decouple_wd=True` else as L2 regularization (add the decay to the gradients).
```
params = [tst_param([1,2,3], [0.1,0.2,0.3]), tst_param([1,2,3], [0.01,0.02,0.03])]
opt = Larc(params, lr=0.1)
opt.step()
#First param local lr is 0.02 < lr so it's not clipped
test_close(opt.state[params[0]]['local_lr'], 0.02)
#Second param local lr is 0.2 > lr so it's clipped
test_eq(opt.state[params[1]]['local_lr'], 0.1)
test_close(params[0], tensor([0.998,1.996,2.994]))
test_close(params[1], tensor([0.999,1.998,2.997]))
params = [tst_param([1,2,3], [0.1,0.2,0.3]), tst_param([1,2,3], [0.01,0.02,0.03])]
opt = Larc(params, lr=0.1, clip=False)
opt.step()
#No clipping
test_close(opt.state[params[0]]['local_lr'], 0.02)
test_close(opt.state[params[1]]['local_lr'], 0.2)
test_close(params[0], tensor([0.998,1.996,2.994]))
test_close(params[1], tensor([0.998,1.996,2.994]))
```
### LAMB
```
#export
def lamb_step(p, lr, mom, step, sqr_mom, grad_avg, sqr_avg, eps, **kwargs):
"Step for LAMB with `lr` on `p`"
debias1 = debias(mom, 1-mom, step)
debias2 = debias(sqr_mom, 1-sqr_mom, step)
r1 = p.data.pow(2).mean().sqrt()
step = (grad_avg/debias1) / ((sqr_avg/debias2).sqrt()+eps)
r2 = step.pow(2).mean().sqrt()
q = 1 if r1 == 0 or r2 == 0 else min(r1/r2,10)
p.data.add_(step, alpha = -lr * q)
lamb_step._defaults = dict(eps=1e-6, wd=0.)
#export
@log_args(to_return=True, but_as=Optimizer.__init__)
def Lamb(params, lr, mom=0.9, sqr_mom=0.99, eps=1e-5, wd=0., decouple_wd=True):
"A `Optimizer` for Adam with `lr`, `mom`, `sqr_mom`, `eps` and `params`"
cbs = [weight_decay] if decouple_wd else [l2_reg]
cbs += [partial(average_grad, dampening=True), average_sqr_grad, step_stat, lamb_step]
return Optimizer(params, cbs, lr=lr, mom=mom, sqr_mom=sqr_mom, eps=eps, wd=wd)
```
LAMB was introduced in [Large Batch Optimization for Deep Learning: Training BERT in 76 minutes](https://arxiv.org/abs/1904.00962). Intuitively, it's LARC applied to Adam. As in `Adam`, we renamed `beta1` and `beta2` in the paper to `mom` and `sqr_mom`. Note that our defaults also differ from the paper (0.99 for `sqr_mom` or `beta2`, 1e-5 for `eps`). Those values seem to be better from our experiments in a wide range of situations.
Optional weight decay of `wd` is applied, as true weight decay (decay the weights directly) if `decouple_wd=True` else as L2 regularization (add the decay to the gradients).
```
params = tst_param([1,2,3], [0.1,0.2,0.3])
opt = Lamb(params, lr=0.1)
opt.step()
test_close(params[0], tensor([0.7840,1.7840,2.7840]), eps=1e-3)
```
## Lookahead -
Lookahead was introduced by Zhang et al. in [Lookahead Optimizer: k steps forward, 1 step back](https://arxiv.org/abs/1907.08610). It can be run on top of any optimizer and consists in having the final weights of the model be a moving average. In practice, we update our model using the internal optimizer but keep a copy of old weights that and every `k` steps, we change the weights by a moving average of the *fast weights* (the ones updated by the inner optimizer) with the *slow weights* (the copy of old weights). Those *slow weights* act like a stability mechanism.
```
#export
@log_args(but='opt')
class Lookahead(Optimizer, GetAttr):
"Wrap `opt` in a lookahead optimizer"
_default='opt'
def __init__(self, opt, k=6, alpha=0.5):
store_attr('opt,k,alpha')
self._init_state()
def step(self):
if self.slow_weights is None: self._copy_weights()
self.opt.step()
self.count += 1
if self.count%self.k != 0: return
for slow_pg,fast_pg in zip(self.slow_weights,self.param_lists):
for slow_p,fast_p in zip(slow_pg,fast_pg):
slow_p.data.add_(fast_p.data-slow_p.data, alpha=self.alpha)
fast_p.data.copy_(slow_p.data)
def clear_state(self):
self.opt.clear_state()
self._init_state()
def state_dict(self):
state = self.opt.state_dict()
state.update({'count': self.count, 'slow_weights': self.slow_weights})
return state
def load_state_dict(self, sd):
self.count = sd.pop('count')
self.slow_weights = sd.pop('slow_weights')
self.opt.load_state_dict(sd)
def _init_state(self): self.count,self.slow_weights = 0,None
def _copy_weights(self): self.slow_weights = L(L(p.clone().detach() for p in pg) for pg in self.param_lists)
@property
def param_lists(self): return self.opt.param_lists
@param_lists.setter
def param_lists(self, v): self.opt.param_lists = v
params = tst_param([1,2,3], [0.1,0.2,0.3])
p,g = params[0].data.clone(),tensor([0.1,0.2,0.3])
opt = Lookahead(SGD(params, lr=0.1))
for k in range(5): opt.step()
#first 5 steps are normal SGD steps
test_close(params[0], p - 0.5*g)
#Since k=6, sixth step is a moving average of the 6 SGD steps with the initial weight
opt.step()
test_close(params[0], p * 0.5 + (p-0.6*g) * 0.5)
#export
@delegates(RAdam)
def ranger(p, lr, mom=0.95, wd=0.01, eps=1e-6, **kwargs):
"Convenience method for `Lookahead` with `RAdam`"
return Lookahead(RAdam(p, lr=lr, mom=mom, wd=wd, eps=eps, **kwargs))
```
## OptimWrapper -
```
#export
def detuplify_pg(d):
res = {}
for k,v in d.items():
if k == 'params': continue
if is_listy(v): res.update(**{f'{k}__{i}': v_ for i,v_ in enumerate(v)})
else: res[k] = v
return res
tst = {'lr': 1e-2, 'mom': 0.9, 'params':[0,1,2]}
test_eq(detuplify_pg(tst), {'lr': 1e-2, 'mom': 0.9})
tst = {'lr': 1e-2, 'betas': (0.9,0.999), 'params':[0,1,2]}
test_eq(detuplify_pg(tst), {'lr': 1e-2, 'betas__0': 0.9, 'betas__1': 0.999})
#export
def set_item_pg(pg, k, v):
if '__' not in k: pg[k] = v
else:
name,idx = k.split('__')
pg[name] = tuple(v if i==int(idx) else pg[name][i] for i in range_of(pg[name]))
return pg
tst = {'lr': 1e-2, 'mom': 0.9, 'params':[0,1,2]}
test_eq(set_item_pg(tst, 'lr', 1e-3), {'lr': 1e-3, 'mom': 0.9, 'params':[0,1,2]})
tst = {'lr': 1e-2, 'betas': (0.9,0.999), 'params':[0,1,2]}
test_eq(set_item_pg(tst, 'betas__0', 0.95), {'lr': 1e-2, 'betas': (0.95,0.999), 'params':[0,1,2]})
#export
pytorch_hp_map = {'momentum': 'mom', 'weight_decay': 'wd', 'alpha': 'sqr_mom', 'betas__0': 'mom', 'betas__1': 'sqr_mom'}
#export
class OptimWrapper(_BaseOptimizer, GetAttr):
_xtra=['zero_grad', 'step', 'state_dict', 'load_state_dict']
_default='opt'
def __init__(self, opt, hp_map=None):
self.opt = opt
if hp_map is None: hp_map = pytorch_hp_map
self.fwd_map = {k: hp_map[k] if k in hp_map else k for k in detuplify_pg(opt.param_groups[0]).keys()}
self.bwd_map = {v:k for k,v in self.fwd_map.items()}
self.state = defaultdict(dict, {})
self.frozen_idx = 0
@property
def hypers(self):
return [{self.fwd_map[k]:v for k,v in detuplify_pg(pg).items() if k != 'params'} for pg in self.opt.param_groups]
def _set_hyper(self, k, v):
for pg,v_ in zip(self.opt.param_groups,v): pg = set_item_pg(pg, self.bwd_map[k], v_)
def clear_state(self): self.opt.state = defaultdict(dict, {})
@property
def param_lists(self): return [pg['params'] for pg in self.opt.param_groups]
@param_lists.setter
def param_lists(self, v):
for pg,v_ in zip(self.opt.param_groups,v): pg['params'] = v_
sgd = SGD([tensor([1,2,3])], lr=1e-3, mom=0.9, wd=1e-2)
tst_sgd = OptimWrapper(torch.optim.SGD([tensor([1,2,3])], lr=1e-3, momentum=0.9, weight_decay=1e-2))
#Access to param_groups
test_eq(tst_sgd.param_lists, sgd.param_lists)
#Set param_groups
tst_sgd.param_lists = [[tensor([4,5,6])]]
test_eq(tst_sgd.opt.param_groups[0]['params'], [tensor(4,5,6)])
#Access to hypers
test_eq(tst_sgd.hypers, [{**sgd.hypers[0], 'dampening': 0., 'nesterov': False}])
#Set hypers
tst_sgd.set_hyper('mom', 0.95)
test_eq(tst_sgd.opt.param_groups[0]['momentum'], 0.95)
tst_sgd = OptimWrapper(torch.optim.SGD([{'params': [tensor([1,2,3])], 'lr': 1e-3},
{'params': [tensor([4,5,6])], 'lr': 1e-2}], momentum=0.9, weight_decay=1e-2))
sgd = SGD([[tensor([1,2,3])], [tensor([4,5,6])]], lr=[1e-3, 1e-2], mom=0.9, wd=1e-2)
#Access to param_groups
test_eq(tst_sgd.param_lists, sgd.param_lists)
#Set param_groups
tst_sgd.param_lists = [[tensor([4,5,6])], [tensor([1,2,3])]]
test_eq(tst_sgd.opt.param_groups[0]['params'], [tensor(4,5,6)])
test_eq(tst_sgd.opt.param_groups[1]['params'], [tensor(1,2,3)])
#Access to hypers
test_eq(tst_sgd.hypers, [{**sgd.hypers[i], 'dampening': 0., 'nesterov': False} for i in range(2)])
#Set hypers
tst_sgd.set_hyper('mom', 0.95)
test_eq([pg['momentum'] for pg in tst_sgd.opt.param_groups], [0.95,0.95])
tst_sgd.set_hyper('lr', [1e-4,1e-3])
test_eq([pg['lr'] for pg in tst_sgd.opt.param_groups], [1e-4,1e-3])
#hide
#check it works with tuply hp names like in Adam
tst_adam = OptimWrapper(torch.optim.Adam([tensor([1,2,3])], lr=1e-2, betas=(0.9, 0.99)))
test_eq(tst_adam.hypers, [{'lr': 0.01, 'mom': 0.9, 'sqr_mom': 0.99, 'eps': 1e-08, 'wd': 0, 'amsgrad': False}])
tst_adam.set_hyper('mom', 0.95)
test_eq(tst_adam.opt.param_groups[0]['betas'], (0.95, 0.99))
tst_adam.set_hyper('sqr_mom', 0.9)
test_eq(tst_adam.opt.param_groups[0]['betas'], (0.95, 0.9))
def _mock_train(m, x, y, opt):
m.train()
for i in range(0, 100, 25):
z = m(x[i:i+25])
loss = F.mse_loss(z, y[i:i+25])
loss.backward()
opt.step()
opt.zero_grad()
m = nn.Linear(4,5)
x = torch.randn(100, 3, 4)
y = torch.randn(100, 3, 5)
try:
torch.save(m.state_dict(), 'tmp.pth')
wgt,bias = m.weight.data.clone(),m.bias.data.clone()
m.load_state_dict(torch.load('tmp.pth'))
opt1 = OptimWrapper(torch.optim.AdamW(m.parameters(), betas=(0.9, 0.99), eps=1e-5, weight_decay=1e-2))
_mock_train(m, x.clone(), y.clone(), opt1)
wgt1,bias1 = m.weight.data.clone(),m.bias.data.clone()
m.load_state_dict(torch.load('tmp.pth'))
opt2 = Adam(m.parameters(), 1e-3, wd=1e-2)
_mock_train(m, x.clone(), y.clone(), opt2)
wgt2,bias2 = m.weight.data.clone(),m.bias.data.clone()
test_close(wgt1,wgt2,eps=1e-3)
test_close(bias1,bias2,eps=1e-3)
finally: os.remove('tmp.pth')
m = nn.Linear(4,5)
x = torch.randn(100, 3, 4)
y = torch.randn(100, 3, 5)
try:
torch.save(m.state_dict(), 'tmp.pth')
wgt,bias = m.weight.data.clone(),m.bias.data.clone()
m.load_state_dict(torch.load('tmp.pth'))
opt1 = OptimWrapper(torch.optim.Adam(m.parameters(), betas=(0.9, 0.99), eps=1e-5, weight_decay=1e-2))
_mock_train(m, x.clone(), y.clone(), opt1)
wgt1,bias1 = m.weight.data.clone(),m.bias.data.clone()
m.load_state_dict(torch.load('tmp.pth'))
opt2 = Adam(m.parameters(), 1e-3, wd=1e-2, decouple_wd=False)
_mock_train(m, x.clone(), y.clone(), opt2)
wgt2,bias2 = m.weight.data.clone(),m.bias.data.clone()
test_close(wgt1,wgt2,eps=1e-3)
test_close(bias1,bias2,eps=1e-3)
finally: os.remove('tmp.pth')
```
## Export -
```
#hide
from nbdev.export import *
notebook2script()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/trevorwjames/DS-Unit-2-Kaggle-Challenge/blob/master/module2-random-forests/Trevor_James_LS_DS_222_assignment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Lambda School Data Science
*Unit 2, Sprint 2, Module 2*
---
# Random Forests
## Assignment
- [ ] Read [“Adopting a Hypothesis-Driven Workflow”](http://archive.is/Nu3EI), a blog post by a Lambda DS student about the Tanzania Waterpumps challenge.
- [ ] Continue to participate in our Kaggle challenge.
- [ ] Define a function to wrangle train, validate, and test sets in the same way. Clean outliers and engineer features.
- [ ] Try Ordinal Encoding.
- [ ] Try a Random Forest Classifier.
- [ ] Submit your predictions to our Kaggle competition. (Go to our Kaggle InClass competition webpage. Use the blue **Submit Predictions** button to upload your CSV file. Or you can use the Kaggle API to submit your predictions.)
- [ ] Commit your notebook to your fork of the GitHub repo.
## Stretch Goals
### Doing
- [ ] Add your own stretch goal(s) !
- [ ] Do more exploratory data analysis, data cleaning, feature engineering, and feature selection.
- [ ] Try other [categorical encodings](https://contrib.scikit-learn.org/category_encoders/).
- [ ] Get and plot your feature importances.
- [ ] Make visualizations and share on Slack.
### Reading
Top recommendations in _**bold italic:**_
#### Decision Trees
- A Visual Introduction to Machine Learning, [Part 1: A Decision Tree](http://www.r2d3.us/visual-intro-to-machine-learning-part-1/), and _**[Part 2: Bias and Variance](http://www.r2d3.us/visual-intro-to-machine-learning-part-2/)**_
- [Decision Trees: Advantages & Disadvantages](https://christophm.github.io/interpretable-ml-book/tree.html#advantages-2)
- [How a Russian mathematician constructed a decision tree — by hand — to solve a medical problem](http://fastml.com/how-a-russian-mathematician-constructed-a-decision-tree-by-hand-to-solve-a-medical-problem/)
- [How decision trees work](https://brohrer.github.io/how_decision_trees_work.html)
- [Let’s Write a Decision Tree Classifier from Scratch](https://www.youtube.com/watch?v=LDRbO9a6XPU)
#### Random Forests
- [_An Introduction to Statistical Learning_](http://www-bcf.usc.edu/~gareth/ISL/), Chapter 8: Tree-Based Methods
- [Coloring with Random Forests](http://structuringtheunstructured.blogspot.com/2017/11/coloring-with-random-forests.html)
- _**[Random Forests for Complete Beginners: The definitive guide to Random Forests and Decision Trees](https://victorzhou.com/blog/intro-to-random-forests/)**_
#### Categorical encoding for trees
- [Are categorical variables getting lost in your random forests?](https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/)
- [Beyond One-Hot: An Exploration of Categorical Variables](http://www.willmcginnis.com/2015/11/29/beyond-one-hot-an-exploration-of-categorical-variables/)
- _**[Categorical Features and Encoding in Decision Trees](https://medium.com/data-design/visiting-categorical-features-and-encoding-in-decision-trees-53400fa65931)**_
- _**[Coursera — How to Win a Data Science Competition: Learn from Top Kagglers — Concept of mean encoding](https://www.coursera.org/lecture/competitive-data-science/concept-of-mean-encoding-b5Gxv)**_
- [Mean (likelihood) encodings: a comprehensive study](https://www.kaggle.com/vprokopev/mean-likelihood-encodings-a-comprehensive-study)
- [The Mechanics of Machine Learning, Chapter 6: Categorically Speaking](https://mlbook.explained.ai/catvars.html)
#### Imposter Syndrome
- [Effort Shock and Reward Shock (How The Karate Kid Ruined The Modern World)](http://www.tempobook.com/2014/07/09/effort-shock-and-reward-shock/)
- [How to manage impostor syndrome in data science](https://towardsdatascience.com/how-to-manage-impostor-syndrome-in-data-science-ad814809f068)
- ["I am not a real data scientist"](https://brohrer.github.io/imposter_syndrome.html)
- _**[Imposter Syndrome in Data Science](https://caitlinhudon.com/2018/01/19/imposter-syndrome-in-data-science/)**_
### More Categorical Encodings
**1.** The article **[Categorical Features and Encoding in Decision Trees](https://medium.com/data-design/visiting-categorical-features-and-encoding-in-decision-trees-53400fa65931)** mentions 4 encodings:
- **"Categorical Encoding":** This means using the raw categorical values as-is, not encoded. Scikit-learn doesn't support this, but some tree algorithm implementations do. For example, [Catboost](https://catboost.ai/), or R's [rpart](https://cran.r-project.org/web/packages/rpart/index.html) package.
- **Numeric Encoding:** Synonymous with Label Encoding, or "Ordinal" Encoding with random order. We can use [category_encoders.OrdinalEncoder](https://contrib.scikit-learn.org/category_encoders/ordinal.html).
- **One-Hot Encoding:** We can use [category_encoders.OneHotEncoder](https://contrib.scikit-learn.org/category_encoders/onehot.html).
- **Binary Encoding:** We can use [category_encoders.BinaryEncoder](https://contrib.scikit-learn.org/category_encoders/binary.html).
**2.** The short video
**[Coursera — How to Win a Data Science Competition: Learn from Top Kagglers — Concept of mean encoding](https://www.coursera.org/lecture/competitive-data-science/concept-of-mean-encoding-b5Gxv)** introduces an interesting idea: use both X _and_ y to encode categoricals.
Category Encoders has multiple implementations of this general concept:
- [CatBoost Encoder](https://contrib.scikit-learn.org/category_encoders/catboost.html)
- [Generalized Linear Mixed Model Encoder](https://contrib.scikit-learn.org/category_encoders/glmm.html)
- [James-Stein Encoder](https://contrib.scikit-learn.org/category_encoders/jamesstein.html)
- [Leave One Out](https://contrib.scikit-learn.org/category_encoders/leaveoneout.html)
- [M-estimate](https://contrib.scikit-learn.org/category_encoders/mestimate.html)
- [Target Encoder](https://contrib.scikit-learn.org/category_encoders/targetencoder.html)
- [Weight of Evidence](https://contrib.scikit-learn.org/category_encoders/woe.html)
Category Encoder's mean encoding implementations work for regression problems or binary classification problems.
For multi-class classification problems, you will need to temporarily reformulate it as binary classification. For example:
```python
encoder = ce.TargetEncoder(min_samples_leaf=..., smoothing=...) # Both parameters > 1 to avoid overfitting
X_train_encoded = encoder.fit_transform(X_train, y_train=='functional')
X_val_encoded = encoder.transform(X_train, y_val=='functional')
```
For this reason, mean encoding won't work well within pipelines for multi-class classification problems.
**3.** The **[dirty_cat](https://dirty-cat.github.io/stable/)** library has a Target Encoder implementation that works with multi-class classification.
```python
dirty_cat.TargetEncoder(clf_type='multiclass-clf')
```
It also implements an interesting idea called ["Similarity Encoder" for dirty categories](https://www.slideshare.net/GaelVaroquaux/machine-learning-on-non-curated-data-154905090).
However, it seems like dirty_cat doesn't handle missing values or unknown categories as well as category_encoders does. And you may need to use it with one column at a time, instead of with your whole dataframe.
**4. [Embeddings](https://www.kaggle.com/colinmorris/embedding-layers)** can work well with sparse / high cardinality categoricals.
_**I hope it’s not too frustrating or confusing that there’s not one “canonical” way to encode categoricals. It’s an active area of research and experimentation — maybe you can make your own contributions!**_
### Setup
You can work locally (follow the [local setup instructions](https://lambdaschool.github.io/ds/unit2/local/)) or on Colab (run the code cell below).
```
%%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge/master/data/'
!pip install category_encoders==2.*
# If you're working locally:
else:
DATA_PATH = '../data/'
import pandas as pd
from sklearn.model_selection import train_test_split
train = pd.merge(pd.read_csv(DATA_PATH+'waterpumps/train_features.csv'),
pd.read_csv(DATA_PATH+'waterpumps/train_labels.csv'))
test = pd.read_csv(DATA_PATH+'waterpumps/test_features.csv')
sample_submission = pd.read_csv(DATA_PATH+'waterpumps/sample_submission.csv')
# adding in a val during the data set loading
train, val = train_test_split(train, train_size=.80, test_size=.20,
stratify=train['status_group'], random_state=42)
train.shape, val.shape, test.shape
```
# Data Wrangle Function
```
import numpy as np
def wrangle(X):
# Working with a copy
X = X.copy()
# dealing with very small near 0 values
X['latitude'] = X['latitude'].replace(-2e-08, 0)
# replacing the missing values that are actually 0 with NaNs
cols_with_zeros = ['longitude', 'latitude']
for col in cols_with_zeros:
X[col] = X[col].replace(0, np.nan)
# dropping repetive columns
X = X.drop(columns=['quantity_group', 'id', 'waterpoint_type_group', 'payment_type',
'extraction_type_group'])
# convert date_recorded feature to date_time
X['date_recorded'] = pd.to_datetime(X['date_recorded'])
return X
train = wrangle(train)
val = wrangle(val)
test = wrangle(test)
train.shape
X_train.shape
```
# Feature Engineering
```
# data cleaning of high cardinality features
target = 'status_group'
train_features = train.drop(columns=target)
numeric_features = train_features.select_dtypes(include='number').columns.tolist()
cardinality = train_features.select_dtypes(exclude='number').nunique()
categorical_features = cardinality[cardinality <=50].index.tolist()
features = numeric_features + categorical_features
train.head(5)
X_train['waterpoint_type'].unique()
X_train['waterpoint_type_group'].unique()
X_train['payment'].unique()
X_train['payment_type'].unique()
X_train['source_class'].unique()
```
# Feature/Target Separation
```
X_train = train[features]
y_train = train[target]
X_val = val[features]
y_val = val[target]
X_test = test[features]
```
# Model Building
```
import category_encoders as ce
from sklearn.impute import SimpleImputer
from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.impute import KNNImputer
from sklearn.ensemble import RandomForestClassifier
```
#### Trying a simple model using Random Forrest
- Including: OHE, Simple Imputer
```
# Starding with a simple model using RF
model = Pipeline([
('ohe', ce.OneHotEncoder(use_cat_names=True, cols=categorical_features)),
('impute', SimpleImputer()),
('classifier', RandomForestClassifier(random_state=42))
])
#fitting model
model.fit(X_train, y_train)
#train data score
print('Training Data Accuracy:', model.score(X_train, y_train))
print('Val data accuracy:', model.score(X_val, y_val))
```
We see an inrease in Val data accuracy, although from the training data we see a possibility of an overfit model.
#### Stay within random forrest
- using a Ordinal Encoder instead of OHE
```
model = Pipeline([
('OE', ce.OrdinalEncoder(cols=categorical_features)),
('impute', SimpleImputer()),
('classifier', RandomForestClassifier(random_state=42))
])
#fitting model
model.fit(X_train, y_train)
#train data score
print('Training Data Accuracy:', model.score(X_train, y_train))
print('Val data accuracy:', model.score(X_val, y_val))
model = Pipeline([
('OE', ce.OrdinalEncoder(cols=categorical_features)),
('impute', KNNImputer()),
('classifier', RandomForestClassifier(random_state=42))
])
model
# max_depth = 17
model = Pipeline([
('OE', ce.OrdinalEncoder(cols=categorical_features)),
('impute', SimpleImputer()),
('classifier', RandomForestClassifier(bootstrap=True, ccp_alpha=0.0,
class_weight=None, criterion='gini',
max_depth=18, max_features='auto',
max_leaf_nodes=None, max_samples=None,
min_impurity_decrease=0.0,
min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0,
n_estimators=100, n_jobs=None,
oob_score=False, random_state=42,
verbose=0, warm_start=False))
])
#fitting model
model.fit(X_train, y_train)
#train data score
print('Training Data Accuracy:', model.score(X_train, y_train))
print('Val data accuracy:', model.score(X_val, y_val))
```
Max_depth = 17 created a better generalizable model. Alhough did not yeild as high of a predicition on the leaderboard
```
model = Pipeline([
('OE', ce.OrdinalEncoder(cols=categorical_features)),
('impute', SimpleImputer()),
('classifier', RandomForestClassifier(bootstrap=True, ccp_alpha=0.0,
class_weight=None, criterion='gini',
max_depth=18, max_features='auto',
max_leaf_nodes=None, max_samples=None,
min_impurity_decrease=0.0,
min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0,
n_estimators=100, n_jobs=None,
oob_score=False, random_state=42,
verbose=0, warm_start=False))
])
#fitting model
model.fit(X_train, y_train)
#train/val data score
print('Training Data Accuracy:', model.score(X_train, y_train))
print('Val data accuracy:', model.score(X_val, y_val))
import matplotlib.pyplot as plt
# this doesnt want to plot for some reason. All the conditions work.
encoder = model.named_steps['OE']
encoded_columns = encoder.transform(X_val).columns
importances = pd.Series(model['classifier'].feature_importances_, encoded_columns)
plt.figure(figsize=(10,40))
importances.sort_values().plot.barh()
```
# Submission to Kaggle CSV
```
X_train2 = pd.concat([X_train, X_val])
y_train2 = pd.concat([y_train, y_val])
model.fit(X_train2, y_train2)
print('Training Data Accuracy:', model.score(X_train, y_train))
print('Val data accuracy:', model.score(X_val, y_val))
y_pred = model.predict(X_test)
submission = sample_submission.copy()
submission['status_group'] = y_pred
submission.to_csv('trevor-james-submission5.csv', index=False)
```
| github_jupyter |
```
%matplotlib inline
```
# Compute real-time evoked responses with FieldTrip client
This example demonstrates how to connect the MNE real-time
system to the Fieldtrip buffer using FieldTripClient class.
This example was tested in simulation mode
neuromag2ft --file MNE-sample-data/MEG/sample/sample_audvis_raw.fif
using a modified version of neuromag2ft available at
https://staff.washington.edu/larsoner/minimal_cmds.tar.gz
to run the FieldTrip buffer. Then running this example acquires the
data on the client side.
Since the Fieldtrip buffer does not contain all the
measurement information required by the MNE real-time processing
pipeline, an info dictionary must be provided to instantiate FieldTripClient.
Alternatively, the MNE-Python script will try to guess the missing
measurement info from the Fieldtrip Header object.
Together with RtEpochs, this can be used to compute evoked
responses using moving averages.
```
# Author: Mainak Jas <mainak@neuro.hut.fi>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
import mne
from mne.viz import plot_events
from mne.realtime import FieldTripClient, RtEpochs
print(__doc__)
# select the left-auditory condition
event_id, tmin, tmax = 1, -0.2, 0.5
# user must provide list of bad channels because
# FieldTrip header object does not provide that
bads = ['MEG 2443', 'EEG 053']
plt.ion() # make plot interactive
_, ax = plt.subplots(2, 1, figsize=(8, 8)) # create subplots
with FieldTripClient(host='localhost', port=1972,
tmax=150, wait_max=10) as rt_client:
# get measurement info guessed by MNE-Python
raw_info = rt_client.get_measurement_info()
# select gradiometers
picks = mne.pick_types(raw_info, meg='grad', eeg=False, eog=True,
stim=True, exclude=bads)
# create the real-time epochs object
rt_epochs = RtEpochs(rt_client, event_id, tmin, tmax,
stim_channel='STI 014', picks=picks,
reject=dict(grad=4000e-13, eog=150e-6),
decim=1, isi_max=10.0, proj=None)
# start the acquisition
rt_epochs.start()
for ii, ev in enumerate(rt_epochs.iter_evoked()):
print("Just got epoch %d" % (ii + 1))
ev.pick_types(meg=True, eog=False)
if ii == 0:
evoked = ev
else:
evoked = mne.combine_evoked([evoked, ev], weights='nave')
ax[0].cla()
ax[1].cla() # clear axis
plot_events(rt_epochs.events[-5:], sfreq=ev.info['sfreq'],
first_samp=-rt_client.tmin_samp, axes=ax[0])
# plot on second subplot
evoked.plot(axes=ax[1], selectable=False, time_unit='s')
ax[1].set_title('Evoked response for gradiometer channels'
'(event_id = %d)' % event_id)
plt.pause(0.05)
plt.draw()
rt_epochs.stop()
plt.close()
```
| github_jupyter |
```
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white", color_codes=True)
iris = pd.read_csv("iris.csv") # the iris dataset is now a Pandas DataFrame
iris.head()
iris["Species"].value_counts()
# .plot extension from pandas framework is used to make scatterplots
iris.plot(kind="scatter", x="SepalLengthCm", y="SepalWidthCm")
#A seaborn jointplot shows bivariate scatterplots and univariate histograms
sns.jointplot(x="SepalLengthCm", y="SepalWidthCm", data=iris, size=5)
#Seaborn's FacetGrid is used to color the scatterplot by species
sns.FacetGrid(iris, hue="Species", size=5) \
.map(plt.scatter, "SepalLengthCm", "SepalWidthCm") \
.add_legend()
#Boxplots are used to examine the individual feature in seaborn.
sns.boxplot(x="Species", y="PetalLengthCm", data=iris)
#One way to extend this plot is by adding a layer of individual points on top of it through Seaborn's striplot.
#We'll use jitter=True so that all the points don't fall in single vertical lines above the species
ax = sns.boxplot(x="Species", y="PetalLengthCm", data=iris)
ax = sns.stripplot(x="Species", y="PetalLengthCm", data=iris, jitter=True, edgecolor="gray")
#A violin plot combines the benefits of the previous two plots and simplifies them denser regions of the data are fatter, and sparser thiner in a violin plot
sns.violinplot(x="Species", y="PetalLengthCm", data=iris, size=6)
#A final seaborn plot useful for looking at univariate relations is the kdeplot, which creates and visualizes a kernel density estimate of the underlying feature
sns.FacetGrid(iris, hue="Species", size=6) \
.map(sns.kdeplot, "PetalLengthCm") \
.add_legend()
#Another useful seaborn plot is the pairplot, which shows the bivariate relation between each pair of features.
#From the pairplot, we'll see that the Iris-setosa species is separataed from the other two across all feature combinations
sns.pairplot(iris.drop("Id", axis=1), hue="Species", size=3)
#The diagonal elements in a pairplot show the histogram by default.
#We can update these elements to show other things, such as a kde.
sns.pairplot(iris.drop("Id", axis=1), hue="Species", size=3, diag_kind="kde")
#Boxplot with Pandas
iris.drop("Id", axis=1).boxplot(by="Species", figsize=(12, 6))
#One cool more sophisticated technique pandas has available is called Andrews Curves.
#Andrews Curves involve using attributes of samples as coefficients for Fourier series and then plotting these
from pandas.plotting import andrews_curves
andrews_curves(iris.drop("Id", axis=1), "Species")
#Another multivariate visualization technique pandas has is parallel_coordinates.
#Parallel coordinates plots each feature on a separate column & then draws lines connecting the features for each data sample
from pandas.plotting import parallel_coordinates
parallel_coordinates(iris.drop("Id", axis=1), "Species")
#A final multivariate visualization technique pandas has is radviz which puts each feature as a point on a 2D plane,
#and then simulates having each sample attached to those points through a spring weighted by the relative value for that feature
from pandas.plotting import radviz
radviz(iris.drop("Id", axis=1), "Species")
```
| github_jupyter |
# Set up environment for GPU (!important)
```
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
import keras
import tensorflow as tf
print("TF version", tf.__version__)
print("keras version:", keras.__version__)
physical_devices = tf.config.list_physical_devices('GPU')
print("Num GPUs Available: ", len(physical_devices))
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
# If this last line give an error, stop the notebook kernel, reset it and run again
```
# Train module
## Import required modules to process data
```
from keras_preprocessing.image import ImageDataGenerator
import pandas as pd
import numpy as np
```
## Train configuration
```
IMAGE_SIZE = 96 # Images are 96x96 px
IMAGE_CHANNELS = 3 # Images are 3 chanell (RGB)
```
## Load train data info
```
# Function to append image file extension to train img ids
def appendExt(id):
return id + ".tif"
# Load CSVs
traindf = pd.read_csv("/dataset/train_labels.csv")
# ========= FOR PROTOTYPING ONLY =========== #
# traindf = traindf[:100]
# ========================================== #
# Add extensions to id files
traindf["id"] = traindf["id"].apply(appendExt)
# Labels must be strings
traindf["label"] = traindf["label"].astype(str)
# removing this image because it caused a training error previously
traindf[traindf['id'] != 'dd6dfed324f9fcb6f93f46f32fc800f2ec196be2']
# removing this image because it's black
traindf[traindf['id'] != '9369c7278ec8bcc6c880d99194de09fc2bd4efbe']
```
## Build image data generator
```
datagen = ImageDataGenerator(rescale=1./255., validation_split=0.25)
train_generator=datagen.flow_from_dataframe(
dataframe = traindf,
directory = "/dataset/train/",
x_col = "id",
y_col = "label",
subset = "training",
target_size = (IMAGE_SIZE, IMAGE_SIZE),
batch_size = 10,
shuffle = True,
class_mode = "categorical",
)
valid_generator=datagen.flow_from_dataframe(
dataframe = traindf,
directory = "/dataset/train/",
x_col = "id",
y_col = "label",
subset = "validation",
target_size = (IMAGE_SIZE, IMAGE_SIZE),
batch_size = 10,
shuffle = True,
class_mode = "categorical",
)
# Calculate class weigths
from sklearn.utils import class_weight
class_weights = class_weight.compute_class_weight(
'balanced',
classes=np.unique(traindf['label']),
y=traindf['label']
)
class_weights = dict(enumerate(class_weights))
print("Class weights:", class_weights)
```
## Build example model
```
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten, Dropout, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras import regularizers, optimizers
from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
kernel_size = (3,3)
pool_size= (2,2)
first_filters = 32
second_filters = 64
third_filters = 128
dropout_conv = 0.3
dropout_dense = 0.3
model = Sequential()
model.add(Conv2D(first_filters, kernel_size, activation = 'relu', input_shape = (96, 96, 3)))
model.add(Conv2D(first_filters, kernel_size, activation = 'relu'))
model.add(Conv2D(first_filters, kernel_size, activation = 'relu'))
model.add(MaxPooling2D(pool_size = pool_size))
model.add(Dropout(dropout_conv))
model.add(Conv2D(second_filters, kernel_size, activation ='relu'))
model.add(Conv2D(second_filters, kernel_size, activation ='relu'))
model.add(Conv2D(second_filters, kernel_size, activation ='relu'))
model.add(MaxPooling2D(pool_size = pool_size))
model.add(Dropout(dropout_conv))
model.add(Conv2D(third_filters, kernel_size, activation ='relu'))
model.add(Conv2D(third_filters, kernel_size, activation ='relu'))
model.add(Conv2D(third_filters, kernel_size, activation ='relu'))
model.add(MaxPooling2D(pool_size = pool_size))
model.add(Dropout(dropout_conv))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(dropout_dense))
model.add(Dense(2, activation = "softmax"))
model.compile(
optimizers.Adam(lr=0.0001),
loss='categorical_crossentropy',
metrics=['accuracy']
)
model.summary()
```
## Train the example model
```
STEP_SIZE_TRAIN = train_generator.n//train_generator.batch_size
STEP_SIZE_VALID = valid_generator.n//valid_generator.batch_size
print("STEP_SIZE_TRAIN:", STEP_SIZE_TRAIN)
print("STEP_SIZE_VALID:", STEP_SIZE_VALID)
# Save best model
checkpointPath = "/usr/src/scripts/best-model.h5"
checkpoint = ModelCheckpoint(
checkpointPath,
monitor='val_accuracy',
verbose=1,
save_best_only=True,
mode='max'
)
# Dynamic learning rate
reduce_lr = ReduceLROnPlateau(
monitor='val_accuracy',
factor=0.5,
patience=2,
verbose=1,
mode='max',
min_lr=0.00001
)
callbacks_list = [checkpoint, reduce_lr]
model.fit(
train_generator,
steps_per_epoch=STEP_SIZE_TRAIN,
class_weight=class_weights,
validation_data=valid_generator,
validation_steps=STEP_SIZE_VALID,
epochs=10, # Only for test!
verbose=1,
callbacks=callbacks_list
)
val_loss, val_accuracy = model.evaluate(valid_generator, steps=STEP_SIZE_VALID)
```
## Predict test data
```
# Load test data
testdf = pd.read_csv("/dataset/sample_submission.csv")
testdf["id"] = testdf["id"].apply(appendExt)
# Set up test data generator (only apply normalization)
test_datagen=ImageDataGenerator(rescale=1./255.)
test_generator=test_datagen.flow_from_dataframe(
dataframe=testdf,
directory="/dataset/test/",
x_col="id",
y_col=None,
batch_size=10,
shuffle=False,
class_mode=None,
target_size=(IMAGE_SIZE,IMAGE_SIZE)
)
STEP_SIZE_TEST = test_generator.n//test_generator.batch_size
test_generator.reset()
model.predict(test_generator, steps=STEP_SIZE_TEST)
```
| github_jupyter |
# Train with Scikit-learn on AzureML
## Prerequisites
* Install the Azure Machine Learning Python SDK and create an Azure ML Workspace
```
import time
#check core SDK version
import azureml.core
print("SDK version:", azureml.core.VERSION)
# data_dir = '../../data_airline_updated'
```
## 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.workspace import Workspace
# if a locally-saved configuration file for the workspace is not available, use the following to load workspace
# ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, workspace_name=workspace_name)
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')
datastore = ws.get_default_datastore()
print("Default datastore's name: {}".format(datastore.name))
# datastore.upload(src_dir='../../data_airline_updated', target_path='data_airline', overwrite=False, show_progress=True)
path_on_datastore = 'data_airline'
ds_data = datastore.path(path_on_datastore)
print(ds_data)
```
## Create 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, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource.
As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota.
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_DS5_v2` GPU VMs.
```
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
#choose a name for your cluster
cpu_cluster_name = "cpu-cluster"
if cpu_cluster_name in ws.compute_targets:
cpu_cluster = ws.compute_targets[cpu_cluster_name]
if cpu_cluster and type(cpu_cluster) is AmlCompute:
print('Found compute target. Will use {0} '.format(cpu_cluster_name))
else:
print("creating new cluster")
provisioning_config = AmlCompute.provisioning_configuration(vm_size = 'Standard_DS5_v2', max_nodes = 1)
#create the cluster
cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, provisioning_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())
```
## Train model on the remote compute
Now that you have your data and training script prepared, you are ready to train on your remote compute.
Create a directory that will contain all the necessary code from your local machine that you will need access to on the remote resource. This includes the training script and any additional files your training script depends on.
```
import os
project_folder = './train_sklearn'
os.makedirs(project_folder, exist_ok=True)
```
### Prepare training script
Now you will need to create your training script. We log the parameters and the highest accuracy the model achieves:
```python
run.log('Accuracy', np.float(accuracy))
```
These run metrics will become particularly important when we begin hyperparameter tuning our model in the "Tune model hyperparameters" section.
Once your script is ready, copy the training script `train_sklearn_RF.py` into your project directory.
```
import shutil
shutil.copy('train_sklearn_RF.py', project_folder)
```
### Create an experiment
Create an [Experiment](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#experiment) to track all the runs in your workspace.
```
from azureml.core import Experiment
experiment_name = 'train_sklearn'
experiment = Experiment(ws, name=experiment_name)
```
### Create a scikit-learn estimator
```
from azureml.train.sklearn import SKLearn
script_params = {
'--data_dir': ds_data.as_mount(),
'--n_estimators': 100,
'--max_depth': 8,
'--max_features': 0.6,
}
estimator = SKLearn(source_directory=project_folder,
script_params=script_params,
compute_target=cpu_cluster,
entry_script='train_sklearn_RF.py',
pip_packages=['pyarrow'])
```
The `script_params` parameter is a dictionary containing the command-line arguments to your training script `entry_script`.
### Submit job
Run your experiment by submitting your estimator object. Note that this call is asynchronous.
```
run = experiment.submit(estimator)
```
## Monitor your run
Monitor the progress of the run with a Jupyter widget.The widget is asynchronous and provides live updates every 10-15 seconds until the job completes.
```
from azureml.widgets import RunDetails
RunDetails(run).show()
# run.cancel()
```
| github_jupyter |
```
import warnings
from itertools import product
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from graspy.plot import heatmap
from graspy.simulations import er_np, sbm
from graspy.utils import symmetrize
from joblib import Parallel, delayed
from scipy.stats import ttest_ind, wilcoxon, mannwhitneyu, truncnorm
warnings.filterwarnings("ignore")
%matplotlib inline
def generate_pop(m, var_1, var_2, seed, block_1 = 5, block_2=15):
np.random.seed(seed)
n = [block_1, block_2]
p = [
[1, 1],
[1, 1]
]
sd_1 = np.sqrt(var_1)
sd_2 = np.sqrt(var_2)
wt_func = [
[truncnorm.rvs, truncnorm.rvs],
[truncnorm.rvs, truncnorm.rvs]
]
wt_args_1 = [
[dict(a=-1/sd_1, b=1/sd_1, scale=sd_1, random_state=seed), dict(a=-1/sd_1, b=1/sd_1, scale=sd_1, random_state=seed)],
[dict(a=-1/sd_1, b=1/sd_1, scale=sd_1, random_state=seed), dict(a=-1/sd_1, b=1/sd_1, scale=sd_1, random_state=seed)],
]
wt_args_2 = [
[dict(a=-1/sd_2, b=1/sd_2, scale=sd_2, random_state=seed), dict(a=-1/sd_2, b=1/sd_2, scale=sd_2, random_state=seed)],
[dict(a=-1/sd_2, b=1/sd_2, scale=sd_2, random_state=seed), dict(a=-1/sd_2, b=1/sd_2, scale=sd_2, random_state=seed)],
]
pop_1 = np.array([sbm(n, p, wt=wt_func, wtargs=wt_args_1) for _ in range(m)])
pop_2 = np.array([sbm(n, p, wt=wt_func, wtargs=wt_args_2) for _ in range(m)])
return pop_1, pop_2
def compute_statistic(test, pop1, pop2):
if test.__name__ == 'ttest_ind':
test_statistics, _ = ttest_ind(pop1, pop2, axis=0)
np.nan_to_num(test_statistics, copy=False)
else:
n = pop1.shape[-1]
test_statistics = np.zeros((n, n))
for i in range(n):
for j in range(i, n):
x_ij = pop1[:, i, j]
y_ij = pop2[:, i, j]
if np.array_equal(x_ij, y_ij):
test_statistics[i, j] = 0
else:
tmp, pval = test(x_ij, y_ij)
test_statistics[i, j] = tmp
test_statistics = symmetrize(test_statistics)
return test_statistics
def compute_pr_at_k(different_n, k, test_statistics, test):
n = test_statistics.shape[0]
labels = np.zeros((n, n))
labels[0:different_n, 0:different_n] = 1
triu_idx = np.triu_indices_from(test_statistics, k=1)
test_statistics_ = np.abs(test_statistics[triu_idx])
labels_ = labels[triu_idx]
if test.__name__ == 'ttest_ind':
idx = np.argsort(test_statistics_)[::-1]
else:
idx = np.argsort(test_statistics_)
sorted_labels = labels_[idx]
precision_at_k = sorted_labels[:k].mean()
recall_at_k = sorted_labels[:k].sum() / sorted_labels.sum()
return precision_at_k, recall_at_k
def compute_trustworthiness(pvals):
idx = np.triu_indices(pvals.shape[0], k=1)
res = pvals[idx]
fraction_correct = (res <=0.05).mean()
all_correct = np.all(res <= 0.05)
return fraction_correct, all_correct
def run_experiment(m, var_1, var_2, seed, reps):
tests = ttest_ind, wilcoxon, mannwhitneyu
precisions = []
recalls = []
for i in range(reps):
tmp_precisions = []
tmp_recalls = []
pop1, pop2 = generate_pop(m=m, var_1=var_1, var_2=var_2, seed = seed+i)
for test in tests:
test_statistics = compute_statistic(test, pop1, pop2)
for k in range(1, 11):
precision, recall = compute_pr_at_k(5, k, test_statistics, test)
tmp_precisions.append(precision)
tmp_recalls.append(recall)
precisions.append(tmp_precisions)
recalls.append(tmp_recalls)
precisions = np.array(precisions).mean(axis=0)
recalls = np.array(recalls).mean(axis=0)
to_append = [var_1, var_2, m, *precisions, *recalls]
return to_append
spacing = 50
delta = 0.05
var_1s = np.linspace(1, 3, spacing)
var_2s = np.ones(spacing)
ms = np.linspace(0, 500, spacing +1).astype(int)[1:]
reps=100
args = [
(m, var_1, var_2, seed*reps, reps)
for seed, (m, (var_1, var_2))
in enumerate(product(ms, zip(var_1s, var_2s)))
]
res = Parallel(n_jobs=-3, verbose=1)(
delayed(run_experiment)(
*arg
) for arg in args
)
cols = [
'var1',
'var2',
'm',
*[f"{test.__name__}_precision_at_{k}" for test in [ttest_ind, wilcoxon, mannwhitneyu] for k in range(1, 11)],
*[f"{test.__name__}_recall_at_{k}" for test in [ttest_ind, wilcoxon, mannwhitneyu] for k in range(1, 11)]]
res_df = pd.DataFrame(res, columns = cols)
res_df.to_csv("20200120_precision_recall_results.csv", index=False)
```
# Figures
```
size = np.sqrt(res_df.shape[0]).astype(int)
ttest_prec = np.flipud(res_df.ttest_ind_precision_at_10.values.reshape(-1, spacing))
wilcoxon_prec = np.flipud(res_df.wilcoxon_precision_at_10.values.reshape(-1, spacing))
mannwhitney_prec = np.flipud(res_df.mannwhitneyu_precision_at_10.values.reshape(-1, spacing))
samples = np.linspace(0, 500, spacing +1).astype(int)[1:] *2
samples = [str(i) for i in samples]
vmin = -.5
vmax = -vmin
fmt = lambda x: "{:.2f}".format(x)
with sns.plotting_context('talk', font_scale=1.25):
# fig, ax = plt.subplots(figsize=(10, 10))
fig, ax = plt.subplots(1, 4, gridspec_kw={'width_ratios': [1, 1, 1, 0.05]}, figsize=(20, 8))
sns.heatmap(
ttest_prec - wilcoxon_prec,
ax = ax[0],
square=True,
center=0,
cmap="RdBu_r",
cbar_kws = dict(shrink=0.7),
xticklabels=[f"{mu1:.02f}" for mu1 in var_1s],
yticklabels=[f"{int(m*2)}" for m in ms][::-1],
cbar_ax=ax[-1],
vmin=vmin,
vmax=vmax
)
#ax[0].set_xticks(np.arange(0, ax[0].get_xlim()[1]+1, 10))
#ax[0].set_yticks(np.arange(0, ax[0].get_ylim()[0]+1, 10)[::-1])
ax[0].set_title("T-Test - Wilcoxon")
sns.heatmap(
ttest_prec - mannwhitney_prec,
ax = ax[1],
square=True,
center=0,
cmap="RdBu_r",
cbar_kws = dict(shrink=0.7),
xticklabels=[f"{mu1:.02f}" for mu1 in var_1s],
cbar_ax=ax[-1],
vmin=vmin,
vmax=vmax
)
#ax[1].set_xticks(np.arange(0, ax[1].get_xlim()[1]+1, 10))
#ax[1].set_yticks(np.arange(0, ax[1].get_ylim()[0]+1, 10)[::-1])
ax[1].yaxis.set_major_formatter(plt.NullFormatter())
ax[1].set_title("T-Test - Mann-Whitney")
sns.heatmap(
wilcoxon_prec - mannwhitney_prec,
ax = ax[2],
square=True,
center=0,
cmap="RdBu_r",
cbar_kws = dict(shrink=0.7),
xticklabels=[f"{mu1:.02f}" for mu1 in var_2s],
cbar_ax=ax[-1],
vmin=vmin,
vmax=vmax
)
#ax[2].set_xticks(np.arange(0, ax[1].get_xlim()[1]+1, 10))
#ax[2].set_yticks(np.arange(0, ax[1].get_ylim()[0]+1, 10)[::-1])
ax[2].yaxis.set_major_formatter(plt.NullFormatter())
ax[2].set_title("Wilcoxon - Mann-Whitney")
fig.text(-0.01, 0.5, "Sample Size", va='center', rotation='vertical')
fig.text(0.5, -0.03, "Mu", va='center', ha='center')
fig.tight_layout()
#fig.savefig("./figures/20191209_precision_diff.png", dpi=300, bbox_inches='tight')
#fig.savefig("./figures/20191209_precision_diff.pdf", dpi=300, bbox_inches='tight')
size = np.sqrt(res_df.shape[0]).astype(int)
ttest_prec = np.flipud(res_df.ttest_ind_precision_at_10.values.reshape(-1, spacing))
wilcoxon_prec = np.flipud(res_df.wilcoxon_precision_at_10.values.reshape(-1, spacing))
mannwhitney_prec = np.flipud(res_df.mannwhitneyu_precision_at_10.values.reshape(-1, spacing))
samples = np.arange(0, 501, spacing)[1:] *2
samples[0] += 10
samples = [str(i) for i in samples]
vmin = -0.05
vmax = -vmin
fmt = lambda x: "{:.2f}".format(x)
with sns.plotting_context('talk', font_scale=1.25):
# fig, ax = plt.subplots(figsize=(10, 10))
fig, ax = plt.subplots(1, 4, gridspec_kw={'width_ratios': [1, 1, 1, 0.05]}, figsize=(20, 8))
sns.heatmap(
ttest_prec - wilcoxon_prec,
ax = ax[0],
square=True,
center=0,
cmap="RdBu_r",
cbar_kws = dict(shrink=0.7),
xticklabels=[f"{mu1:.02f}" for mu1 in var_1s],
yticklabels=[f"{int(m*2)}" for m in ms][::-1],
cbar_ax=ax[-1],
vmin=vmin,
vmax=vmax
)
#ax[0].set_xticks(np.arange(0, ax[0].get_xlim()[1]+1, 10))
#ax[0].set_yticks(np.arange(0, ax[0].get_ylim()[0]+1, 10)[::-1])
ax[0].set_title("T-Test - Wilcoxon")
sns.heatmap(
ttest_prec - mannwhitney_prec,
ax = ax[1],
square=True,
center=0,
cmap="RdBu_r",
cbar_kws = dict(shrink=0.7),
xticklabels=[f"{mu1:.02f}" for mu1 in var_1s],
cbar_ax=ax[-1],
vmin=vmin,
vmax=vmax
)
#ax[1].set_xticks(np.arange(0, ax[1].get_xlim()[1]+1, 10))
#ax[1].set_yticks(np.arange(0, ax[1].get_ylim()[0]+1, 10)[::-1])
ax[1].yaxis.set_major_formatter(plt.NullFormatter())
ax[1].set_title("T-Test - Mann-Whitney")
sns.heatmap(
wilcoxon_prec - mannwhitney_prec,
ax = ax[2],
square=True,
center=0,
cmap="RdBu_r",
cbar_kws = dict(shrink=0.7),
xticklabels=[f"{mu1:.02f}" for mu1 in var_2s],
cbar_ax=ax[-1],
vmin=vmin,
vmax=vmax
)
#ax[2].set_xticks(np.arange(0, ax[1].get_xlim()[1]+1, 10))
#ax[2].set_yticks(np.arange(0, ax[1].get_ylim()[0]+1, 10)[::-1])
ax[2].yaxis.set_major_formatter(plt.NullFormatter())
ax[2].set_title("Wilcoxon - Mann-Whitney")
fig.text(-0.01, 0.5, "Sample Size", va='center', rotation='vertical')
fig.text(0.5, -0.03, "Mu", va='center', ha='center')
fig.tight_layout()
#fig.savefig("./figures/20191209_precision_diff.png", dpi=300, bbox_inches='tight')
#fig.savefig("./figures/20191209_precision_diff.pdf", dpi=300, bbox_inches='tight')
```
| github_jupyter |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
```
print('sdjhjfvsjdf')
df_a = pd.read_csv('../datafiles/titanic_train.csv')
df_b = pd.read_csv('../datafiles/titanic_test.csv')
print(df_a.shape,df_b.shape)
df_b
df_a.head()
df_a.info()
# df_a.drop('PassengerId',1, None,None,None,True)
df_a
df_a['Survived'].hist(by=df_a['Sex'])
sns.countplot(x='Survived',hue='Sex',data=df_a)
sns.countplot(x='Survived',hue='Pclass',data=df_a)
sns.distplot(a=df_a['Survived'])
fig,axes = plt.subplots()
axes.scatter(x='Survived',y='Sex',data=df_a)
```
Correlation
```
df_a.corr()
sns.heatmap(data = df_a.corr())
```
Concatenating the dataset
```
Y=df_a['Survived'].copy()
df_a_temp =df_a.drop('Survived',1)
ful = pd.concat([df_a_temp,df_b])
ful.reset_index(inplace=True)
ful
```
missing value percentage
```
(ful.isna().sum() / ful.shape[0])*100
```
Filling age with the avg from respective 'Pclass' attribut
```
ful.groupby('Pclass')['Age'].apply(lambda x:print(x))
ful['Age'] = ful.groupby('Pclass')['Age'].transform(lambda x:x.fillna(x.mean()))
ful
```
dropping the 'Cabin' column as it was wy more missing values and also its categories done think matter much
```
ful.drop(['Cabin'],axis=1,inplace=True);
ful
```
check for missing values
Analysing the relation between the Fare and the Embarked to fill the embarked missing values
```
ful[ful['Fare']>300 ]
fig = plt.figure(figsize=(7,10))
sns.boxplot(x='Embarked',y='Fare',data=ful,showfliers = False)
ful.groupby('Embarked')['Fare'].median()
ful.groupby('Embarked')['Fare'].mean()
```
Function to sort the values of the Fare according to the Embarked attribute(whichh is the destination of boarding)
```
def impute_embarked(data):
if(pd.isna(data[1])):
if(0<data[0]<=20):
return 'Q'
elif(20<data[0]<=45):
return 'S'
else:
return 'C'
else:
return data[1]
ful[ful['Embarked'].isna()]
ful['Embarked']=ful[['Fare','Embarked']].apply(impute_embarked,axis=1)
ful.iloc[61]
(ful.isna().sum() / ful.shape[0])*100
ful[ful['Fare'].isna()]
```
as you can see that the Embarked is 'S' so i am goung to directly put 27 as the mean() in its category
you can also leave some missong vaues missing : )
```
ful.loc[1043,'Fare'] = 27
ful.iloc[1043]['Fare']
(ful.isna().sum() / ful.shape[0])*100
```
We are good to go !!!!! keeping relevent data
```
ful
ful.drop(columns=['index','PassengerId','Name','Ticket'], inplace=True)
```
Procedure to convet the cateorical variables
```
print(ful)
print(ful.nunique())
ful
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
colt = ColumnTransformer(transformers=[('encoder',OneHotEncoder(),['Pclass','Sex','SibSp','Parch','Embarked'])])
X= pd.DataFrame(colt.fit_transform(ful).toarray())
X
X[['Age','Fare']]= ful[['Age','Fare']].copy()
X
X_train_csv=X.loc[:890].copy()
X_train_csv
```
> ## All the var with X_test_csv is the data set to be used to submit to the kaggle
### And should not be used in any sort of training,, we further split the X_train_csv to train and test set to obtain the precision
```
X_test_csv=X.loc[891:].copy()
X_test_csv
```
Now see we have combined the training and test set from the Kaggle Titanic set
#### But if we want to evauate the model we need to use the Training_csv data and split into the train and test as i the Test_csv data we do not have Y/ Dependent Variable
```
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_train_csv, Y, test_size=0.30, random_state=101)
print(X_train.shape,X_test.shape, y_train.shape, y_test.shape)
from sklearn.linear_model import LogisticRegression
logmodel = LogisticRegression(max_iter=350)
logmodel.fit(X_train,y_train)
predictions = logmodel.predict(X_test)
from sklearn.metrics import classification_report
print(classification_report(y_test,predictions))
```
##### <font color='red'> we got the prediction but now we have to see how to increase the precision
> ### TRY 2)so now we will first try creating the dummy variable using pandas...........................................................................................................
```
X2 = pd.get_dummies(data = ful,columns=['Pclass','Sex','SibSp','Parch','Embarked'],drop_first=True)
X2
```
splittint the full set into train and test
```
X_train_csv_dummybypandas = X2.loc[:890].copy()
X_test_csv_dummybypandas = X2.loc[891:].copy()
print(X_train_csv_dummybypandas.shape,X_test_csv_dummybypandas.shape)
X_train2, X_test2, y_train2, y_test2 = train_test_split(X_train_csv_dummybypandas, Y, test_size=0.30, random_state=101)
print(X_train2.shape,X_test2.shape, y_train2.shape, y_test2.shape)
logmodel2 = LogisticRegression(max_iter=350)
logmodel2.fit(X_train2,y_train2)
predictions2 = logmodel2.predict(X_test2)
print(classification_report(y_test2,predictions2))
print(logmodel2.coef_)
```
># <font color='red'>so we can say that getting dummy variables from pandas or scikit learn does not matter use any one
> ### TRY 3)Now we try converting only Sex and Embarkment to dummy as done by Portilia.
```
X3 = pd.get_dummies(data = ful,columns=['Sex','Embarked'],drop_first=True)
X3
X_train_csv_3= X3.loc[:890].copy()
print(X_train_csv_3.shape)
X_train3, X_test3, y_train3, y_test3 = train_test_split(X_train_csv_3, Y, test_size=0.30,random_state=101)
print(X_train3.shape,X_test3.shape, y_train3.shape, y_test3.shape)
logmodel3 = LogisticRegression(max_iter=350)
logmodel3.fit(X_train3,y_train3)
predictions3 = logmodel3.predict(X_test3)
print(classification_report(y_test3,predictions3))
```
># <font color='red'>so we can say that getting dummy variables from pandas or scikit learn does not matter use any one
#### so now we will try to map 'Age' like portilia
```
ful2 = pd.concat([df_a,df_b])
ful2.reset_index(inplace=True)
ful2
def impute_age(cols):
Age = cols[0]
Pclass = cols[1]
if pd.isnull(Age):
if Pclass == 1:
return 37
elif Pclass == 2:
return 29
else:
return 24
else:
return Age
ful2['Age'] = ful2[['Age','Pclass']].apply(impute_age,axis=1)
ful2.isna().sum()
def impute_embarked(data):
if(pd.isna(data[1])):
if(0<data[0]<=20):
return 'Q'
elif(20<data[0]<=45):
return 'S'
else:
return 'C'
else:
return data[1]
# ful2['Embarked']=ful2[['Fare','Embarked']].apply(impute_embarked,axis=1)
ful2.drop('Cabin',axis=1,inplace=True)
ful2['Embarked'].dropna(inplace=True)
ful2['Fare'].dropna(inplace=True)
ful2.isna().sum()
# ful2.loc[1043,'Fare'] = 27
# ful2.drop(columns=['index','PassengerId','Name','Ticket','Cabin'], inplace=True)
ful2.drop(columns=['index','Name','Ticket'], inplace=True)
ful2.shape
X4 = pd.get_dummies(data = ful2,columns=['Sex','Embarked'],drop_first=True)
X_train_csv_4= X4.loc[:890].copy()
print(X_train_csv_4.shape)
X_train4, X_test4, y_train4, y_test4 = train_test_split(X_train_csv_4.drop('Survived',axis=1), Y, test_size=0.30,random_state=101)
print(X_train4.shape,X_test4.shape, y_train4.shape, y_test4.shape)
logmodel4 = LogisticRegression(max_iter=1000)
logmodel4.fit(X_train4,y_train4)
predictions4 = logmodel4.predict(X_test4)
print(classification_report(y_test4,predictions4))
logmodel4.coef_
```
# Here i tried to maximum imitate the portilia's method
# <font color='blue'> Now we are going to try the Andrew NG's method
- Hypothesis function (not needed in the actual implementation)
```
# teta = pd.Series(np.zeros(21))
# def H_teta(X,teta):
# return 1/(1+np.exp(np.dot(X,teta)))
# predictions = H_teta(X_train2,teta)
```
- Standardising the Age & Fare columns
```
from sklearn.preprocessing import StandardScaler
X_anng = X_train2.copy()
X_anng[['Fare', 'Age']] = StandardScaler().fit_transform(X_anng[['Fare', 'Age']])
```
- Adding x0 in X_train2
```
# y=y_train2.to_numpy(copy=True)
# print(y,y.reshape(len(y),1))
# X_anng['const'] = 1
X_anng.insert(loc=0, column='const', value=1)
X_anng
```
- Cost function
```
def Cost(x,y,teta):
pred = 1/(1+np.exp(-np.dot(x,teta)))
m=len(y)
err = (-y*np.log(pred))-((1-y)*np.log(1-pred))
gradient = (1/m)*np.dot(x.transpose(),(pred-y))
return (1/m)*sum(err),gradient
```
- Gradient Descent Function
```
teta = pd.Series(np.zeros(21))
def gradDes(x,y,teta,alpha,n):
m=len(y)
j_old=[]
for i in range(n):
cost, grad = Cost(x,y,teta)
teta = teta - (alpha * grad)
j_old.append(cost)
return cost,j_old,teta
cost,j,teta = gradDes(X_anng,y_train2,teta,1,500)
```
- Plotting the Cost vs Iterations graph
```
fig,ax = plt.subplots()
ax.scatter(np.arange(len(j)),j);
```
> ## Regularisation (Andrew NG)
```
teta2 = pd.Series(np.zeros(21))
def regAN(x,y,teta,alpha,lmda,n):
m=len(y)
j_old=[]
coo = []
for i in range(n):
cost, grad = Cost(x,y,teta)
# print(grad.shape)
teta[0] = teta[0] - (alpha * grad[0])
teta.loc[1:20] = teta.loc[1:20]*(1-((alpha*lmda)/m)) - (alpha * grad[1:])
cooo = 1-((alpha*lmda)/m)
coo.append(cooo)
j_old.append(cost)
return cost,j_old,teta,coo
cost2,j2,teta2,coo2 = regAN(X_anng,y_train2,teta2,1,1,500)
fig,ax = plt.subplots()
ax.scatter(np.arange(len(j2)),j2);
regularisation_comparison = pd.DataFrame({'teta':teta,'teta2':teta2})
regularisation_comparison.head(100)
```
- ## Gridsearch Cross-validation
```
from sklearn.model_selection import GridSearchCV
gscv = GridSearchCV(LogisticRegression(),{'C':[10**-4,10**-2,10**0,10**2,10**4]},cv=5,scoring='f1')
gscv.fit(X_train,y_train)
print(gscv.best_estimator_)
print(gscv.score(X_test,y_test))
gscv2 = GridSearchCV(LogisticRegression(),{'C':[50,100,200,500,1000,5000]},cv=5,scoring='f1')
gscv2.fit(X_train,y_train)
print(gscv2.best_estimator_)
print(gscv2.score(X_test,y_test)) ### if you can see the f1score actually drops
gscv3 = GridSearchCV(LogisticRegression(),{'C':[545,550,555]},cv=5,scoring='f1')
gscv3.fit(X_train,y_train)
print(gscv3.best_estimator_)
print(gscv3.score(X_test,y_test)) ### this is the best f1 score we achive at 5-fold
gscv4 = GridSearchCV(LogisticRegression(),{'C':[0.0001,0.001,0.01,0.1,1,100,1000,10000]},cv=10,scoring='f1')
gscv4.fit(X_train,y_train)
print(gscv4.best_estimator_)
print(gscv4.score(X_test,y_test)) ### at 10 k-fold
```
- ## Randomsearch Cross-validation
```
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import uniform,norm
distributions = dict(C=uniform(loc=0, scale=10),penalty=['l2', 'l1'])
rscv = RandomizedSearchCV(LogisticRegression(), distributions,)
rscv.fit(X_train,y_train)
print(rscv.best_estimator_)
print(rscv.score(X_test,y_test))
distributions2 = dict(C=norm(),penalty=['l2', 'l1'])
rscv2 = RandomizedSearchCV(LogisticRegression(), distributions,)
rscv2.fit(X_train,y_train)
print(rscv2.best_estimator_)
print(rscv2.score(X_test,y_test))
plt.hist(norm.rvs(size=1000))
```
>> ## Checking how sparcity works
```
li = [0.001,0.01,0.1,1,10,100,1000]
zro = []
for x in li:
l1lr = LogisticRegression(C=x,penalty='l1')
l1lr.fit(X_train,y_train)
zro.append(np.count_nonzero(l1lr.coef_))
pd.DataFrame({'C':li,'No of non-zero coeff':zro})
li = [10**-6,10**-5,10**-4,0.001,0.01,0.1,1,10,100,1000,10000]
zrol1 = []
zrol2 = []
for x in li:
l1lr = LogisticRegression(C=x,penalty='l1', tol=0.01 ,solver='saga')
l2lr = LogisticRegression(C=x,penalty='l2', tol=0.01, solver='saga')
l1lr.fit(X_train,y_train)
l2lr.fit(X_train,y_train)
zrol1.append(np.count_nonzero(l1lr.coef_))
zrol2.append(np.count_nonzero(l2lr.coef_))
lmbda = [1/x for x in li]
pd.DataFrame({'Lambda':lmbda,'No of non-zero coeff L1':zrol1,'And L2':zrol2})
```
> so as lambda increases more and more of coeff tends to zero
```
```
| github_jupyter |
# Exercise 3 - Quantum error correction
## Historical background
Shor's algorithm gave quantum computers a worthwhile use case—but the inherent noisiness of quantum mechanics meant that building hardware capable of running such an algorithm would be a huge struggle. In 1995, Shor released another landmark paper: a scheme that shared quantum information over multiple qubits in order to reduce errors.[1]
A great deal of progress has been made over the decades since. New forms of error correcting codes have been discovered, and a large theoretical framework has been built around them. The surface codes proposed by Kitaev in 1997 have emerged as the leading candidate, and many variations on the original design have emerged since then. But there is still a lot of progress to make in tailoring codes to the specific details of quantum hardware.[2]
In this exercise we'll consider a case in which artificial 'errors' are inserted into a circuit. Your task is to design the circuit such that these additional gates can be identified.
You'll then need to think about how to implement your circuit on a real device. This means you'll need to tailor your solution to the layout of the qubits. Your solution will be scored on how few entangling gates (the noisiest type of gate) that you use.
### References
1. Shor, Peter W. "Scheme for reducing decoherence in quantum computer memory." Physical review A 52.4 (1995): R2493.
1. Dennis, Eric, et al. "Topological quantum memory." Journal of Mathematical Physics 43.9 (2002): 4452-4505.
## The problem of errors
Errors occur when some spurious operation acts on our qubits. Their effects cause things to go wrong in our circuits. The strange results you may have seen when running on real devices is all due to these errors.
There are many spurious operations that can occur, but it turns out that we can pretend that there are only two types of error: bit flips and phase flips.
Bit flips have the same effect as the `x` gate. They flip the $|0\rangle$ state of a single qubit to $|1\rangle$ and vice-versa. Phase flips have the same effect as the `z` gate, introducing a phase of $-1$ into superpositions. Put simply, they flip the $|+\rangle$ state of a single qubit to $|-\rangle$ and vice-versa.
The reason we can think of any error in terms of just these two is because any error can be represented by some matrix, and any matrix can be written in terms of the matrices $X$ and $Z$. Specifically, for any single qubit matrix $M$,
$$
M = \alpha I + \beta X + \gamma XZ + \delta Z,
$$
for some suitably chosen values $\alpha$, $\beta$, $\gamma$ and $\delta$.
So whenever we apply this matrix to some single qubit state $|\psi\rangle$ we get
$$
M |\psi\rangle = \alpha |\psi\rangle + \beta X |\psi\rangle + \gamma XZ |\psi\rangle + \delta Z |\psi\rangle.
$$
The resulting superposition is composed of the original state, the state we'd have if the error was just a bit flip, the state for just a phase flip and the state for both. If we had some way to measure whether a bit or phase flip happened, the state would then collapse to just one possibility. And our complex error would become just a simple bit or phase flip.
So how do we detect whether we have a bit flip or a phase flip (or both). And what do we do about it once we know? Answering these questions is what quantum error correction is all about.
## An overly simple example
One of the first quantum circuits that most people ever write is to create a pair of entangled qubits. In this journey into quantum error correction, we'll start the same way.
```
from qiskit import QuantumCircuit, Aer
# Make an entangled pair
qc_init = QuantumCircuit(2)
qc_init.h(0)
qc_init.cx(0,1)
# Draw the circuit
display(qc_init.draw('mpl'))
# Get an output
qc = qc_init.copy()
qc.measure_all()
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
Here we see the expected result when we run the circuit: the results `00` and `11` occurring with equal probability.
But what happens when we have the same circuit, but with a bit flip 'error' inserted manually.
```
# Make bit flip error
qc_insert = QuantumCircuit(2)
qc_insert.x(0)
# Add it to our original circuit
qc = qc_init.copy()
qc = qc.compose(qc_insert)
# Draw the circuit
display(qc.draw('mpl'))
# Get an output
qc.measure_all()
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
Now the results are different: `01` and `10`. The two bit values have gone from always agreeing to always disagreeing. In this way, we detect the effect of the error.
Another way we can detect it is to undo the entanglement with a few more gates. If there are no errors, we return to the initial $|00\rangle$ state.
```
# Undo entanglement
qc_syn = QuantumCircuit(2)
qc_syn.cx(0,1)
qc_syn.h(0)
# Add this after the error
qc = qc_init.copy()
qc = qc.compose(qc_syn)
# Draw the circuit
display(qc.draw('mpl'))
# Get an output
qc.measure_all()
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
But what happens if there are errors one of the qubits? Try inserting different errors to find out.
Here's a circuit with all the components we've introduced so far: the initialization `qc_init`, the inserted error in `qc_insert` and the final `qc_syn` which ensures that the final measurement gives a nice definite answer.
```
# Define an error
qc_insert = QuantumCircuit(2)
qc_insert.x(0)
# Undo entanglement
qc_syn = QuantumCircuit(2)
qc_syn.cx(0,1)
qc_syn.h(0)
# Add this after the error
qc = qc_init.copy()
qc = qc.compose(qc_insert)
qc = qc.compose(qc_syn)
# Draw the circuit
display(qc.draw('mpl'))
# Get an output
qc.measure_all()
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
You'll find that the output tells us exactly what is going on with the errors. Both the bit and phase flips can be detected. The bit value on the left is `1` only if there is a bit flip (and so if we have inserted an `x(0)` or `x(1)`). The bit on the right similarly tells us there is a phase flip (an inserted `z(0)` or `z(1)`).
This ability to detect and distinguish bit and phase flips is very useful. But it is not quite useful enough. We can only tell *what type* of errors are happening, but not *where*. Without more detail, it is not possible to figure out how to remove the effects of these operations from our computations. For quantum error correction we therefore need something bigger and better.
It's your task to do just that! Here's a list of what you need to submit. Everything here is then explained by the example that follows.
<div class="alert alert-block alert-success">
<b>Goal</b>
Create circuits which can detect `x` and `z` errors on two qubits.
You can come up with a solution of your own. Or just tweak the almost valid solution given below.
</div>
<div class="alert alert-block alert-danger">
<b>What to submit</b>
* You need to supply two circuits:
* `qc_init`: Prepares the qubits (of which there are at least two) in a desired initial state;
* `qc_syn`: Measures a subset of the qubits.
* The artificial errors to be inserted are `x` and `z` gates on two particular qubits. You need to pick the two qubits to be used for this (supplied as the list `error_qubits`).
* There are 16 possible sets of errors to be inserted (including the trivial case of no errors). The measurement result of `qc_syn` should output a unique bit string for each. The grader will return the error message *'Please make sure the circuit is created to the initial layout.'* if this is not satisfied.
* The grader will compile the complete circuit for the backend `ibmq_tokyo` (a retired device). To show that your solution is tailor made for the device, this transpilation should not change the number of `cx` gates. If it does, you will get the error message *'Please make sure the circuit is created to the initial layout.'*
* To guide the transpilation, you'll need to tell the transpiler which qubits on the device should be used as which qubits in your circuit. This is done with an `initial_layout` list.
* You may start with the example given below, which can become a valid answer with a few tweaks.
</div>
## A better example: the surface code
```
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
import qiskit.tools.jupyter
from qiskit.test.mock import FakeTokyo
code = QuantumRegister(5,'code')
```
In this example we'll use 5 qubits that we'll call code qubits. To keep track of them, we'll define a special quantum register.
We'll also have an additional four qubits we'll call syndrome qubits.
```
syn = QuantumRegister(4,'syn')
```
Similarly we define a register for the four output bits, used when measuring the syndrome qubits.
```
out = ClassicalRegister(4,'output')
```
We consider the qubits to be laid out as follows, with the code qubits forming the corners of four triangles, and the syndrome qubits living inside each triangle.
```
c0----------c1
| \ s0 / |
| \ / |
| s1 c2 s2 |
| / \ |
| / s3 \ |
c3----------c4
```
For each triangle we associate a stabilizer operation on its three qubits. For the qubits on the sides, the stabilizers are ZZZ. For the top and bottom ones, they are XXX.
The syndrome measurement circuit corresponds to a measurement of these observables. This is done in a similar way to surface code stabilizers (in fact, this code is a small version of a surface code).
<div class="alert alert-block alert-danger">
<b>Warning</b>
You should remove the barriers before submitting the code as it might interfere with transpilation. It is given here for visualization only.
</div>
The initialization circuit prepares an eigenstate of these observables, such that the output of the syndrome measurement will be `0000` with certainty.
```
qc_syn = QuantumCircuit(code,syn,out)
# Left ZZZ
qc_syn.cx(code[0],syn[1])
qc_syn.cx(code[2],syn[1])
qc_syn.cx(code[3],syn[1])
#qc_syn.barrier()
# Right ZZZ
qc_syn.swap(code[1],syn[0])
qc_syn.cx(syn[0],syn[2])
qc_syn.swap(code[1],syn[0])
qc_syn.cx(code[2],syn[2])
#qc_syn.swap(code[1],syn[2])
#qc_syn.swap(code[4],syn[2])
qc_syn.cx(code[4],syn[2])
#qc_syn.barrier()
# Top XXX
qc_syn.h(syn[0])
#qc_syn.swap(syn[2],code[1])
qc_syn.cx(syn[0],code[0])
qc_syn.cx(syn[0],code[1])
#qc_syn.swap(syn[2],code[4])
qc_syn.cx(syn[0],code[2])
qc_syn.h(syn[0])
#qc_syn.barrier()
# Bottom XXX
qc_syn.h(syn[3])
qc_syn.cx(syn[3],code[2])
qc_syn.cx(syn[3],code[3])
qc_syn.cx(syn[3],code[4])
qc_syn.h(syn[3])
#qc_syn.barrier()
# Measure the auxilliary qubits
qc_syn.measure(syn,out)
qc_syn.draw('mpl')
qc_init = QuantumCircuit(code,syn,out)
qc_init.h(syn[0])
qc_init.cx(syn[0],code[0])
#qc_init.swap(syn[0],code[1])
qc_init.cx(syn[0],code[1])
qc_init.cx(syn[0],code[2])
#qc_init.swap(syn[2],code[1])
qc_init.cx(code[2],syn[0])
qc_init.h(syn[3])
qc_init.cx(syn[3],code[2])
qc_init.cx(syn[3],code[3])
qc_init.cx(syn[3],code[4])
qc_init.cx(code[4],syn[3])
#qc_init.barrier()
qc_init.draw('mpl')
```
Let's check that is true.
```
qc = qc_init.compose(qc_syn)
display(qc.draw('mpl'))
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
Now let's make a circuit with which we can insert `x` and `z` gates on our two code qubits. For this we'll need to choose which of the 5 code qubits we have will correspond to the two required for the validity condition.
For this code we need to choose opposite corners.
```
error_qubits = [0,4]
```
Here 0 and 4 refer to the positions of the qubits in the following list, and hence are qubits `code[0]` and `code[4]`.
```
qc.qubits
```
To check that the code does as we require, we can use the following function to create circuits for inserting artificial errors. Here the errors we want to add are listed in `errors` as a simple text string, such as `x0` for an `x` on `error_qubits[0]`.
```
def insert(errors,error_qubits,code,syn,out):
qc_insert = QuantumCircuit(code,syn,out)
if 'x0' in errors:
qc_insert.x(error_qubits[0])
if 'x1' in errors:
qc_insert.x(error_qubits[1])
if 'z0' in errors:
qc_insert.z(error_qubits[0])
if 'z1' in errors:
qc_insert.z(error_qubits[1])
return qc_insert
```
Rather than all 16 possibilities, let's just look at the four cases where a single error is inserted.
```
for error in ['x0','x1','z0','z1']:
qc = qc_init.compose(insert([error],error_qubits,code,syn,out)).compose(qc_syn)
job = Aer.get_backend('qasm_simulator').run(qc)
print('\nFor error '+error+':')
counts = job.result().get_counts()
for output in counts:
print('Output was',output,'for',counts[output],'shots.')
```
Here we see that each bit in the output is `1` when a particular error occurs: the leftmost detects `z` on `error_qubits[1]`, then the next detects `x` on `error_qubits[1]`, and so on.
<div class="alert alert-block alert-danger">
<b>Attention</b>
The correct ordering of the output is important for this exercise. Please follow the order as given below:
1. The leftmost output represents `z` on `code[1]`.
2. The second output from left represents `x` on `code[1]`.
3. The third output from left represents `x` on `code[0]`.
4. The rightmost output represents `z` on `code[0]`.
</div>
When more errors affect the circuit, it becomes hard to unambiguously tell which errors occurred. However, by continuously repeating the syndrome readout to get more results and analysing the data through the process of decoding, it is still possible to determine enough about the errors to correct their effects.
These kinds of considerations are beyond what we will look at in this challenge. Instead we'll focus on something simpler, but just as important: the fewer errors you have, and the simpler they are, the better your error correction will be. To ensure this, your error correction procedure should be tailor-made to the device you are using.
In this challenge we'll be considering the device `ibmq_tokyo`. Though the real version of this was retired some time ago, it still lives on as one of the mock backends.
```
# Please use the backend given here
backend = FakeTokyo()
backend
```
As a simple idea of how our original circuit is laid out, let's see how many two-qubit gates it contains.
If we were to transpile it to the `ibmq_tokyo` backend, remapping would need to occur at the cost of adding for two-qubit gates.
```
qc1 = transpile(qc,backend,basis_gates=['u','cx'], optimization_level=3)
qc1.num_nonlocal_gates()
qc = qc_init.compose(qc_syn)
qc = transpile(qc, basis_gates=['u','cx'])
qc.num_nonlocal_gates()
```
We can control this to an extent by looking at which qubits on the device would be best to use as the qubits in the code. If we look at what qubits in the code need to be connected by two-qubit gates in `qc_syn`, we find the following required connectivity graph.
```
c0....s0....c1
: : :
: : :
s1....c2....s2
: : :
: : :
c3....s3....c4
```
No set of qubits on `ibmq_tokyo` can provide this, but certain sets like 0,1,2,5,6,7,10,11,12 come close. So we can set an `initial_layout` to tell the transpiler to use these.
```
initial_layout = [0,2,6,10,12,1,5,7,11]
```
These tell the transpiler which qubits on the device to use for the qubits in the circuit (for the order they are listed in `qc.qubits`). So the first five entries in this list tell the circuit which qubits to use as the code qubits and the next four entries in this list are similarly for the syndrome qubits. So we use qubit 0 on the device as `code[0]`, qubit 2 as `code[1]` and so on.
Now let's use this for the transpilation.
```
qc2 = transpile(qc,backend,initial_layout=initial_layout, basis_gates=['u','cx'], optimization_level=3)
qc2.num_nonlocal_gates()
```
Though transpilation is a random process, you should typically find that this uses less two-qubit gates than when no initial layout is provided (you might need to re-run both transpilation code multiple times to see it as transpilation is a random process).
Nevertheless, a properly designed error correction scheme should not need any remapping at all. It should be written for the exact device used, and the number of two-qubit gates should remain constant with certainty. This is a condition for a solution to be valid. So you'll not just need to provide an `initial_layout`, but also design your circuits specifically for that layout.
But that part we leave up to you!
```
# Check your answer using following code
from qc_grader import grade_ex3
grade_ex3(qc_init,qc_syn,error_qubits,initial_layout)
# Submit your answer. You can re-submit at any time.
from qc_grader import submit_ex3
submit_ex3(qc_init,qc_syn,error_qubits,initial_layout)
```
## Additional information
**Created by:** James Wootton, Rahul Pratap Singh
**Version:** 1.0.0
| github_jupyter |
# Simple Image Classifier - Bring Your Own Data
## Neuronale Netze auf https://bootcamp.codecentric.ai
Jetzt wird es Zeit, mit einem eigenen Dataset zu experimentieren.
Hinweis: Wenn du auf einem Rechner trainierst, wo keine gut GPU verfügbar ist, kann dies sehr lange dauern. Evtl. möchtest du in dem Fall das Kapitel zu "Training in der Cloud" vorziehen und das Experiment dort durchführen.
Imports und Settings
```
from fastai.basics import *
from fastai.vision import *
```
### Ordner festlegen, wo Daten liegen
Überlege dir, welche Bilder du klassifizieren möchtest.
Wenn du dich zum Beispiel für Vogel vs. Turnschuh entscheidest, lege eine Ordnerstruktur an - z.B.:
- /data/byod/train/
- vogel/bild1.jpg
- vogel/bild2.jpg
- vogel/...
- turnschuh/bild1.jpg
- turnschuh/...
Die Namen der Ordner sind wichtig - das sind deine Label. Die Namen der Bilder sind egal (es müssen auch nicht nur jpg sein).
Die Bilder werden anhand der Ordner "gelabelt".
Wieviele Bilder braucht man dafür? Fang doch einfach mal mit 10-20 Bildern pro Kategorie an und probiere es aus ... Vllt. findest du auch eine Möglichkeit "automatisiert" mehrere Bilder herunter zu laden.
Oft ist es ein großer Aufwand erstmal genügend Daten in der entsprechenden Qualität zu bekommen.
```
DATA = "/data/byod/"
TRAIN = DATA + "train/"
```
Der folgende Befehl macht:
* Daten aus Ordner laden (bzw. einen Loader definieren)
* Labels aus Ordner Namen zuordnen (alle Bilder im Ordner Kiwi sind Kiwis)
* Split Train/Valid (20 %)
* Bilder verkleinern (wenn du nur auf CPU trainierst wähle eine kleine Size, sonst dauert das Training sehr lang)
* (und einiges mehr)
```
data = ImageDataBunch.from_folder(TRAIN, valid_pct=0.2, size=200, bs=20)
```
Wie sehen unsere Daten aus? Einfach mal ein paar Beispiele der Trainigsdaten anzeigen:
```
data.show_batch(rows=3, figsize=(6, 6))
```
Der folgende Befehl macht:
* Erzeuge ein CNN
* mit einer Standard Architektur (vortrainiertes ResNet)
* Architektur wird automatisch auf neue Daten angepasst (Bildgrößen, Klassen, etc.)
* gebe im Trainingsloop die Metrik "Accuracy" aus
* unter der Haube werden viele Standard-Werte gesetzt (welcher Optimizer, Hyperparameter, Best Practices, ...)
```
learn = cnn_learner(data, models.resnet18, metrics=accuracy)
```
### Start Training
```
learn.fit(1)
```
### Jetzt mit dem trainierten Modell eine Vorhersage machen
Wenn du ein paar Bilder testen möchtest, dann lege unter /data/byod/ einen test Ordner an und kopiere ein paar Bilder hinein (Bilder, die nicht beim Training verwendet wurden). Hierbei musst du keine Unterordner anlegen (das Modell soll ja vorhersagen, welche Klasse es ist)
Jetzt nehmen wir ein random Bild aus dem Test Ordner:
```
TEST = DATA + "test/"
TEST_IMAGES = os.listdir(TEST)
TEST_IMAGES
test_img = open_image(TEST + random.choice(TEST_IMAGES))
test_img
```
und machen eine prediction mit dem Modell:
```
learn.predict(test_img)
```
## Credits
Für die Übung verwenden wir die fast.ai Library - siehe http://fast.ai
| github_jupyter |
```
from openeye import oedocking
from openeye import oeomega
from openeye import oechem
# Load the T4 receptor; the files of the different receptors used in this study can be found in:
# T4L-temperature-effects/Docking/OEdock/binders-non-binders/files-to-prepare-receptors/cryo-closed-raw
imstr = oemolistream('receptor.pdb')
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(imstr, protein)
#imstr.close()
# Load a reference ligand to specify the binding site
ligand = oechem.OEGraphMol()
imstr = oechem.oemolistream('toluene_oe.mol2')
oechem.OEReadMolecule(imstr, ligand)
imstr.close()
# Initialize the receptor for docking
receptor = oechem.OEGraphMol()
oedocking.OEMakeReceptor(receptor, protein, ligand)
# Set the docking method and resolution
dock_method = oedocking.OEDockMethod_Chemscore
dock_resolution = oedocking.OESearchResolution_Default
sdtag = oedocking.OEDockMethodGetName( dock_method )
# OEDocking object
dock = oedocking.OEDock( dock_method, dock_resolution)
if not dock.Initialize(receptor):
raise Exception("Unable to initialize Docking with {0}".format(self.args.receptor))
def dock_molecule( dock: "OEDock", sdtag: str, num_poses: int, mcmol ) -> tuple:
''' Docks the multiconfomer molecule, with the given number of poses
Returns a tuple of the docked molecule (dockedMol) and its score
i.e. ( dockedMol, score )
'''
dockedMol = oechem.OEMol()
# Dock the molecule
res = dock.DockMultiConformerMolecule(dockedMol, mcmol, num_poses)
if res == oedocking.OEDockingReturnCode_Success:
# Label the molecule with the score and SDTag
oedocking.OESetSDScore(dockedMol, dock, sdtag)
dock.AnnotatePose(dockedMol)
score = dock.ScoreLigand(dockedMol)
oechem.OESetSDData(dockedMol, sdtag, "{}".format(score))
return dockedMol, score
else:
# raise an exception if the docking is not successful
raise Exception("Unable to dock ligand {0} to receptor".format( dockedMol ))
# Decoys created via DUD-E
decoys = open("decoys.smi").read().splitlines()
# Zinc list - described as binders
zinc = open("zinc.smi").read().splitlines()
# Experimentally validated active compounds - Mobley work + Minh et al
actives = open("mobley-minh-actives.smi").read().splitlines()
#combine all the compounds in one list
all_compounds = decoys + zinc + actives
# save list to file
with open('all_compounds.smi', 'w') as f:
for item in all_compounds:
f.write("%s\n" % item)
omega = oeomega.OEOmega()
omega.SetStrictStereo(False)
# Generate conformers then dock
inmols = []
usednames = []
for idx,line in enumerate(all_compounds):
tmp = line.split()
smi = tmp[0]
mol = oechem.OEMol()
name = tmp[1]
if name=='' or name==None or len(name)<3:
#Define alternate name based on index
name = 'mol%s smiles %s' % (idx, smi)
print("No name found on line %s; using alternate name %s..." % (idx, name))
if not name in usednames:
usednames.append(name)
oechem.OEParseSmiles(mol, smi)
mol.SetTitle(name)
builtOK = omega(mol)
inmols.append(mol)
else:
continue
# Define how many docked poses to generate per molecule
num_poses = 2
# Open a filestream to write the docked poses
scores = {}
with oechem.oemolostream( 'dock-results-Chemscore.sdf') as ofs:
# Loop over 3D molecules from the input filestream
for mcmol in inmols:
# Call docking function
dockedMol, score = dock_molecule( dock, sdtag, num_poses, mcmol )
print("{} {} score = {:.4f}".format(sdtag, dockedMol.GetTitle(), score))
# Write docked molecules to output filestream
oechem.OEWriteMolecule(ofs, dockedMol)
# Store scores
scores[ mcmol.GetTitle()] = score
active_smiles_by_name = {}
file = open('mobley-minh-actives', 'r')
text = file.readlines()
file.close()
for line in text:
tmp = line.split()
active_smiles_by_name[tmp[1]] = tmp[0]
# Build list of titles sorted by score
sorted_titles = list(scores.keys())
sorted_titles.sort( key = lambda title: scores[title] )
# Count how many actives are found at which ranks
ct = 0
fnd_actives = []
for active_name in active_smiles_by_name.keys():
if active_name in sorted_titles:
ct += 1
print("Active %s found in docking results at rank %s" % ( active_name, sorted_titles.index(active_name)))
fnd_actives.append( active_name )
print("Total compounds: %s" % len(sorted_titles))
#Find number of actives
n_actives = len(fnd_actives)
```
| github_jupyter |
# Network based predictions
The state of the art in crime predication increasingly appears to be "network based". That is, looking at real street networks, and assigning risk to streets, rather than areal grid cells.
This is currently an introduction, a very brief literature review, and a plan of action.
# Literature review
Not complete.
1. Rosser at al. "Predictive Crime Mapping: Arbitrary Grids or Street Networks?" J Quant Criminol (2016). https://doi.org/10.1007/s10940-016-9321-x
2. Shiode, Shiode, "Microscale Prediction of Near-Future Crime Concentrations with Street-Level Geosurveillance" Geographical Analysis (2014) 46 435–455 https://doi.org/10.1111/gean.12065
3. Okabe et al. "A kernel density estimation method for networks, its computational method and a GIS‐based tool",
International Journal of Geographical Information Science (2009) 23 https://doi.org/10.1080/13658810802475491
Some comments:
1. "Prospective hotspotting on a network". Algorithm is fairly clear. Some useful info on estimating parameters.
2. Uses a space/time search window to form a statistical test of whether there is an "outbreak" of crime (so similar-ish to SatScan in some sense).
3. Not about _crime_ as such, but the details on how to adapt KDE methods to a network are very detailed and will be useful.
# Action plan
## Network data
- Open street map. I started to look at off-line processing of data with this repository: https://github.com/MatthewDaws/OSMDigest
- Might also consider [OSMNX](https://github.com/gboeing/osmnx)
- [TIGER/Line shapefiles](https://www.census.gov/geo/maps-data/data/tiger-line.html) USA only, but a canonical source.
- [Ordnance Survey](https://www.ordnancesurvey.co.uk/) is the canonical source of data in the UK.
- I am very keen to use only [freely available](https://www.ordnancesurvey.co.uk/business-and-government/products/opendata-products.html) (potentially, as in Beer) data
- I think the two appropriate products for us are:
- [OS Open Roads](https://www.ordnancesurvey.co.uk/business-and-government/products/os-open-roads.html) This is vector data, and a single download.
- [OS OpenMap Local](https://www.ordnancesurvey.co.uk/business-and-government/products/os-open-map-local.html) Available as vector and raster for each national grid reference square. (Or for all of the UK, but a massive download). The raster maps are very detailed. The vector data, for _roads_, seems no more complete than the "Open Roads" download. But does include _buildings_ in vector format (but no address level data).
- [OS VectorMap](https://www.ordnancesurvey.co.uk/business-and-government/products/vectormap-district.html) Shape files are slightly less detailed than OpenMap; raster format is 1/2 the detail. Might want to support optionally.
| github_jupyter |
Experimenting with my hack `star_so.py`
```
#!/usr/bin/env python
# All of the argument parsing is done in the `parallel.py` module.
import numpy as np
import Starfish
from Starfish.model import ThetaParam, PhiParam
#import argparse
#parser = argparse.ArgumentParser(prog="star_so.py", description="Run Starfish fitting model in single order mode with many walkers.")
#parser.add_argument("--sample", choices=["ThetaCheb", "ThetaPhi", "ThetaPhiLines"], help="Sample the all stellar and nuisance parameters at the same time.")
#parser.add_argument("--samples", type=int, default=5, help="How many samples to run?")
#parser.add_argument("--incremental_save", type=int, default=0, help="How often to save incremental progress of MCMC samples.")
#parser.add_argument("--use_cov", action="store_true", help="Use the local optimal jump matrix if present.")
#args = parser.parse_args()
import os
import Starfish.grid_tools
from Starfish.samplers import StateSampler
from Starfish.spectrum import DataSpectrum, Mask, ChebyshevSpectrum
from Starfish.emulator import Emulator
import Starfish.constants as C
from Starfish.covariance import get_dense_C, make_k_func, make_k_func_region
from scipy.special import j1
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.linalg import cho_factor, cho_solve
from numpy.linalg import slogdet
from astropy.stats import sigma_clip
import gc
import logging
from itertools import chain
from collections import deque
from operator import itemgetter
import yaml
import shutil
import json
Starfish.routdir = ""
# list of keys from 0 to (norders - 1)
order_keys = np.arange(1)
DataSpectra = [DataSpectrum.open(os.path.expandvars(file), orders=Starfish.data["orders"]) for file in Starfish.data["files"]]
# list of keys from 0 to (nspectra - 1) Used for indexing purposes.
spectra_keys = np.arange(len(DataSpectra))
#Instruments are provided as one per dataset
Instruments = [eval("Starfish.grid_tools." + inst)() for inst in Starfish.data["instruments"]]
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", filename="{}log.log".format(
Starfish.routdir), level=logging.DEBUG, filemode="w", datefmt='%m/%d/%Y %I:%M:%S %p')
class Order:
def __init__(self, debug=False):
'''
This object contains all of the variables necessary for the partial
lnprob calculation for one echelle order. It is designed to first be
instantiated within the main processes and then forked to other
subprocesses. Once operating in the subprocess, the variables specific
to the order are loaded with an `INIT` message call, which tells which key
to initialize on in the `self.initialize()`.
'''
self.lnprob = -np.inf
self.lnprob_last = -np.inf
self.debug = debug
def initialize(self, key):
'''
Initialize to the correct chunk of data (echelle order).
:param key: (spectrum_id, order_key)
:param type: (int, int)
This method should only be called after all subprocess have been forked.
'''
self.id = key
spectrum_id, self.order_key = self.id
# Make sure these are ints
self.spectrum_id = int(spectrum_id)
self.instrument = Instruments[self.spectrum_id]
self.dataSpectrum = DataSpectra[self.spectrum_id]
self.wl = self.dataSpectrum.wls[self.order_key]
self.fl = self.dataSpectrum.fls[self.order_key]
self.sigma = self.dataSpectrum.sigmas[self.order_key]
self.ndata = len(self.wl)
self.mask = self.dataSpectrum.masks[self.order_key]
self.order = int(self.dataSpectrum.orders[self.order_key])
self.logger = logging.getLogger("{} {}".format(self.__class__.__name__, self.order))
if self.debug:
self.logger.setLevel(logging.DEBUG)
else:
self.logger.setLevel(logging.INFO)
self.logger.info("Initializing model on Spectrum {}, order {}.".format(self.spectrum_id, self.order_key))
self.npoly = Starfish.config["cheb_degree"]
self.chebyshevSpectrum = ChebyshevSpectrum(self.dataSpectrum, self.order_key, npoly=self.npoly)
# If the file exists, optionally initiliaze to the chebyshev values
fname = Starfish.specfmt.format(self.spectrum_id, self.order) + "phi.json"
if os.path.exists(fname):
self.logger.debug("Loading stored Chebyshev parameters.")
phi = PhiParam.load(fname)
self.chebyshevSpectrum.update(phi.cheb)
self.resid_deque = deque(maxlen=500) #Deque that stores the last residual spectra, for averaging
self.counter = 0
self.emulator = Emulator.open()
self.emulator.determine_chunk_log(self.wl)
self.pca = self.emulator.pca
self.wl_FFT = self.pca.wl
# The raw eigenspectra and mean flux components
self.EIGENSPECTRA = np.vstack((self.pca.flux_mean[np.newaxis,:], self.pca.flux_std[np.newaxis,:], self.pca.eigenspectra))
self.ss = np.fft.rfftfreq(self.pca.npix, d=self.emulator.dv)
self.ss[0] = 0.01 # junk so we don't get a divide by zero error
# Holders to store the convolved and resampled eigenspectra
self.eigenspectra = np.empty((self.pca.m, self.ndata))
self.flux_mean = np.empty((self.ndata,))
self.flux_std = np.empty((self.ndata,))
self.sigma_mat = self.sigma**2 * np.eye(self.ndata)
self.mus, self.C_GP, self.data_mat = None, None, None
self.lnprior = 0.0 # Modified and set by NuisanceSampler.lnprob
# self.nregions = 0
# self.exceptions = []
# Update the outdir based upon id
self.noutdir = Starfish.routdir + "{}/{}/".format(self.spectrum_id, self.order)
def lnprob_Theta(self, p):
'''
Update the model to the Theta parameters and then evaluate the lnprob.
Intended to be called from the master process via the command "LNPROB".
'''
try:
self.update_Theta(p)
lnp = self.evaluate() # Also sets self.lnprob to new value
return lnp
except C.ModelError:
self.logger.debug("ModelError in stellar parameters, sending back -np.inf {}".format(p))
return -np.inf
def evaluate(self):
'''
Return the lnprob using the current version of the C_GP matrix, data matrix,
and other intermediate products.
'''
self.lnprob_last = self.lnprob
X = (self.chebyshevSpectrum.k * self.flux_std * np.eye(self.ndata)).dot(self.eigenspectra.T)
CC = X.dot(self.C_GP.dot(X.T)) + self.data_mat
try:
factor, flag = cho_factor(CC)
except np.linalg.linalg.LinAlgError:
print("Spectrum:", self.spectrum_id, "Order:", self.order)
self.CC_debugger(CC)
raise
try:
R = self.fl - self.chebyshevSpectrum.k * self.flux_mean - X.dot(self.mus)
logdet = np.sum(2 * np.log((np.diag(factor))))
self.lnprob = -0.5 * (np.dot(R, cho_solve((factor, flag), R)) + logdet)
self.logger.debug("Evaluating lnprob={}".format(self.lnprob))
return self.lnprob
# To give us some debugging information about what went wrong.
except np.linalg.linalg.LinAlgError:
print("Spectrum:", self.spectrum_id, "Order:", self.order)
raise
def update_Theta(self, p):
'''
Update the model to the current Theta parameters.
:param p: parameters to update model to
:type p: model.ThetaParam
'''
# durty HACK to get fixed logg
# Simply fixes the middle value to be 4.29
# Check to see if it exists, as well
fix_logg = Starfish.config.get("fix_logg", None)
if fix_logg is not None:
p.grid[1] = fix_logg
print("grid pars are", p.grid)
self.logger.debug("Updating Theta parameters to {}".format(p))
# Store the current accepted values before overwriting with new proposed values.
self.flux_mean_last = self.flux_mean.copy()
self.flux_std_last = self.flux_std.copy()
self.eigenspectra_last = self.eigenspectra.copy()
self.mus_last = self.mus
self.C_GP_last = self.C_GP
# Local, shifted copy of wavelengths
wl_FFT = self.wl_FFT * np.sqrt((C.c_kms + p.vz) / (C.c_kms - p.vz))
# If vsini is less than 0.2 km/s, we might run into issues with
# the grid spacing. Therefore skip the convolution step if we have
# values smaller than this.
# FFT and convolve operations
if p.vsini < 0.0:
raise C.ModelError("vsini must be positive")
elif p.vsini < 0.2:
# Skip the vsini taper due to instrumental effects
eigenspectra_full = self.EIGENSPECTRA.copy()
else:
FF = np.fft.rfft(self.EIGENSPECTRA, axis=1)
# Determine the stellar broadening kernel
ub = 2. * np.pi * p.vsini * self.ss
sb = j1(ub) / ub - 3 * np.cos(ub) / (2 * ub ** 2) + 3. * np.sin(ub) / (2 * ub ** 3)
# set zeroth frequency to 1 separately (DC term)
sb[0] = 1.
# institute vsini taper
FF_tap = FF * sb
# do ifft
eigenspectra_full = np.fft.irfft(FF_tap, self.pca.npix, axis=1)
# Spectrum resample operations
if min(self.wl) < min(wl_FFT) or max(self.wl) > max(wl_FFT):
raise RuntimeError("Data wl grid ({:.2f},{:.2f}) must fit within the range of wl_FFT ({:.2f},{:.2f})".format(min(self.wl), max(self.wl), min(wl_FFT), max(wl_FFT)))
# Take the output from the FFT operation (eigenspectra_full), and stuff them
# into respective data products
for lres, hres in zip(chain([self.flux_mean, self.flux_std], self.eigenspectra), eigenspectra_full):
interp = InterpolatedUnivariateSpline(wl_FFT, hres, k=5)
lres[:] = interp(self.wl)
del interp
# Helps keep memory usage low, seems like the numpy routine is slow
# to clear allocated memory for each iteration.
gc.collect()
# Adjust flux_mean and flux_std by Omega
Omega = 10**p.logOmega
self.flux_mean *= Omega
self.flux_std *= Omega
# Now update the parameters from the emulator
# If pars are outside the grid, Emulator will raise C.ModelError
self.emulator.params = p.grid
self.mus, self.C_GP = self.emulator.matrix
class SampleThetaPhi(Order):
def initialize(self, key):
# Run through the standard initialization
super().initialize(key)
# for now, start with white noise
self.data_mat = self.sigma_mat.copy()
self.data_mat_last = self.data_mat.copy()
#Set up p0 and the independent sampler
fname = Starfish.specfmt.format(self.spectrum_id, self.order) + "phi.json"
phi = PhiParam.load(fname)
# Set the regions to None, since we don't want to include them even if they
# are there
phi.regions = None
#Loading file that was previously output
# Convert PhiParam object to an array
self.p0 = phi.toarray()
jump = Starfish.config["Phi_jump"]
cheb_len = (self.npoly - 1) if self.chebyshevSpectrum.fix_c0 else self.npoly
cov_arr = np.concatenate((Starfish.config["cheb_jump"]**2 * np.ones((cheb_len,)), np.array([jump["sigAmp"], jump["logAmp"], jump["l"]])**2 ))
cov = np.diag(cov_arr)
def lnfunc(p):
# Convert p array into a PhiParam object
ind = self.npoly
if self.chebyshevSpectrum.fix_c0:
ind -= 1
cheb = p[0:ind]
sigAmp = p[ind]
ind+=1
logAmp = p[ind]
ind+=1
l = p[ind]
par = PhiParam(self.spectrum_id, self.order, self.chebyshevSpectrum.fix_c0, cheb, sigAmp, logAmp, l)
self.update_Phi(par)
# sigAmp must be positive (this is effectively a prior)
# See https://github.com/iancze/Starfish/issues/26
if not (0.0 < sigAmp):
self.lnprob_last = self.lnprob
lnp = -np.inf
self.logger.debug("sigAmp was negative, returning -np.inf")
self.lnprob = lnp # Same behavior as self.evaluate()
else:
lnp = self.evaluate()
self.logger.debug("Evaluated Phi parameters: {} {}".format(par, lnp))
return lnp
def update_Phi(self, p):
self.logger.debug("Updating nuisance parameters to {}".format(p))
# Read off the Chebyshev parameters and update
self.chebyshevSpectrum.update(p.cheb)
# Check to make sure the global covariance parameters make sense
#if p.sigAmp < 0.1:
# raise C.ModelError("sigAmp shouldn't be lower than 0.1, something is wrong.")
max_r = 6.0 * p.l # [km/s]
# Create a partial function which returns the proper element.
k_func = make_k_func(p)
# Store the previous data matrix in case we want to revert later
self.data_mat_last = self.data_mat
self.data_mat = get_dense_C(self.wl, k_func=k_func, max_r=max_r) + p.sigAmp*self.sigma_mat
```
# Run the program.
```
model = SampleThetaPhi(debug=True)
model.initialize((0,0))
def lnprob_all(p):
pars1 = ThetaParam(grid=p[0:3], vz=p[3], vsini=p[4], logOmega=p[5])
model.update_Theta(pars1)
# hard code npoly=3 (for fixc0 = True with npoly=4) !
pars2 = PhiParam(0, 0, True, p[6:9], p[9], p[10], p[11])
model.update_Phi(pars2)
lnp = model.evaluate()
return lnp
import emcee
start = Starfish.config["Theta"]
fname = Starfish.specfmt.format(model.spectrum_id, model.order) + "phi.json"
phi0 = PhiParam.load(fname)
p0 = np.array(start["grid"] + [start["vz"], start["vsini"], start["logOmega"]] +
phi0.cheb.tolist() + [phi0.sigAmp, phi0.logAmp, phi0.l])
p0
sampler = emcee.EnsembleSampler(32, 12, lnprob_all)
sampler.lnprobfn.f(p0)
p0.shape
p0.shape
p0_std = [5, 0.02, 0.02, 0.5, 0.5, -0.01, -0.005, -0.005, -0.005, 0.01, 0.001, 0.5]
nwalkers=36
p0_ball = emcee.utils.sample_ball(p0, p0_std, size=nwalkers)
p0_ball.shape
```
# This will take a while:
```
#val = sampler.run_mcmc(p0_ball, 10)
np.save('emcee_chain.npy',sampler.chain)
print("The end.")
```
The end.
| github_jupyter |
# Condicionales IF...ELIF...ELSE
nos permite realizar evaluaciones basada en respuestas TRUE o FALSE
```
if respuesta == 'SI' or respuesta == 'S' or respuesta == 'si':
print("Continuar...")
print("Completado!")
elif respuesta == 'not' or respuesta == 'N' or respuesta == 'no':
print("Salida!")
else:
print("Intentalo nuevamente....")
```
# Vamos con el laboratorio 2
Escribir un programa que convierta la temperatura de Fahrenheit a Celsius
En este código se muestra la fórmula matemática para convertir una temperatura medida en grados Fahrenheit a una temperatura medida en grados Celsius:
celsius = (fahrenheit - 32) * 5/9
Use esta fórmula para compilar un programa que **solicite a los usuarios** una temperatura en grados Fahrenheit, realice la conversión a Celsius y, después, muestre la temperatura en grados Celsius.
Si el usuario escribe el valor 55, el programa debe generar este resultado:
*OUTPUT What is the temperature in fahrenheit? 55 Temperature in celsius is 12 *
Pero si el usuario escribe un valor no válido, el programa debe indicarle que hay un problema y, después, cerrar el programa. En este caso, si el usuario escribe el valor Bob, el programa debe generar este resultado:
OUTPUT What is the temperature in fahrenheit? bob Input is not a number.
Nota
Para comprobar el trabajo, use un conversor de temperatura en línea y confirme que el resultado del programa coincide con el del conversor.
Tanto si tiene dificultades y necesita echar un vistazo a la solución como si finaliza el ejercicio correctamente, continúe para ver una solución a este desafío.
```
a = 56
type(a)
fahrenheit = input("Cuál es la temperatura FAH de: ")
```
### GENERAR UN PSEUDOCÓDIGO
```
fah = introducir un valor numérico
evaluamos este valor numèrico, y
SI es valor NO ES numérico,
ELSE print (Este valor no es numèrico)
o reintenta
SI el valor ES numérico
celsius = int(fah - 32) * 5/9
print(La temperatura es CELSIUS)
```
```
type(fahrenheit) # la evaluación de un valor almacenado a través de un input, lo transforma en STRING (cadena de texto)
# celsius = (fahrenheit - 32) * 5/9
```
Aquí empieza la práctica - Talita
```
print ("Por favor informar la temperatura en Fahrenheit")
fah = int(input())
type(fah) # Para coprobar el tipo
celsius = int((int(fah)-32)*5/9)
celsius # por comprobar
type(celsius) # por comprobar
if type(fah) == int:
print ("Su temperatura es de",celsius, " Celsius.")
else:
print (fah, "no es un valor numerico, informe un valor valido")
```
Segundo test
```
print ("Por favor informar la temperatura en Fahrenheit")
fah2 = input()
type(fah2)
fah4 = int(fah2)
type (fah4)
celsius2 = int((int(fah4)-32)*5/9)
numb = list(range(0,1000))
fah4 in numb #Por comprobar
if fah4 in numb:
print("Su temperatura es de ", celsius2," Celsius.")
else:
print (fah2, "no es un valor numerico, informe un valor valido.")
```
Tercer tentativa
```
print("Por favor informar la temperatura en Fahrenheit :")
fah3 = input()
type (fah3)
celsius3 = int((int(fah3)-32)*5/9)
if type(int(fah3))== int:
print ("Su temperatura es de ", celsius3," Celsius.")
else:
print (fah3, "no es un valor numerico, informe un valor valido.")
```
# es tarde no estoy segura si soy capaz
Si determino a principio que el input es un integer, cuando intento poner letras me da error, pero si no determino quees un integer a principios, no reconoce en en momento de la cmprobación.
He intentado con lista de rango, pero tampoco me sirve.
He pensado que la comprobacion debe ir a principios, en el momento que inputa el dato, pero no lo sé hacerlo.
Si la intención es que el usário informe lo que quiera, no veo como
| github_jupyter |
# Midterm aka Assignment 5 - Our first real data science project
```{admonition} Tips
:class: tip
1. Read all instructions before starting.
1. Start early. Work on the components of the project in parallel with related class discussions.
1. RECHECK THESE INSTRUCTIONS BEFORE SUBMITTING
```
```{warning}
Per the [syllabus](../about/gradeoverview), this project is 10% if your overall grade, which is about 2x the weight of a typical assignment. It will probably take 2-3x the time of a typical assignment.
**Really fun news:** This is a end-to-end data science project! You will be downloading a lot of files, parsing/exploring/cleaning those file, and then exploring the data.
BUT: It will take time! If you start the day before it is due, YOU WILL NOT FINISH IT. If you start two days before it is do, you might finish it, but it will not be done well.
```
## Project Set Up
The nuts and bolts of the set up are:
- Basic question: What "types" of firms were hurt more or less by covid?
- Specific questions: What risk factors were associated with better/worse stock returns around the onset of covid?
- This is called a "cross-sectional event study"
- Expected minimum output: Scatterplot (x = some "risk factors", y = returns around March 2020) with regression lines; formatted well
- Discussion of the economics linking the your risk factors to the returns is expected
- Pro output: Regression tables, heatmaps, better scatterplots
- New data science technique: Textual analysis. We will estimate "risk factors" from the text of S&P 500 firm's 10-K filings.
- More on this below
- Data needed:
- Returns: Stock returns for S&P 500 firms can be pulled from Yahoo
- Risk factors for each firm will be created from their 10-K filings.
So your main challenge... is to create variables that measure risks for each firm.
## Steps to complete the assignment
```{dropdown} 1. Start the assignment
- As usual, click the link I provide in the discussion board.
- But unlike before, the repo will be essentially empty. This is a start to finish project, so I'm letting you dictate the structure of the files.
- Clone this to your computer.
```
````{dropdown} 2. Edit **.gitignore**
The `download_text_files.ipynb` file will create a large data structure in a subfolder called `text_files/` with all the downloaded 10-K files. There will be several gigs of data in this folder. We don't want to save/push all these files to github!
```{warning}
So add this directory (`text_files/`) to your gitignore before you proceed!
```
````
````{dropdown} 3. Create **download_text_files.ipynb**
This file
1. Should create a subfolder for inputs (`inputs/`). You should probably save the S&P500 list from the wikipedia page there.
1. Should create another subfolder (`text_files/`) to hold all the text files you download. Because scraping can generate large amounts of files, I usually put it in a dedicated input folder instead of the generic input folder we just made.
**Tips/recommendations**
1. Try to download just one 10-K at first. When you can successfully do that, try a few more, one at a time. Check the folders on your computer - did they download like you expected? Are the files correct? If yes, continue. If not, you have an error to fix.
1. The website has really good info on "building a spider." Highly recommend!
1.
```{tip}
When you are confident the program works,
1. Delete your whole `text_files/` and `input/` subfolders on your computer so you have a "fresh start"
2. Rerun this from scratch.
3. Rerun the file AGAIN (but don't delete the files you have). Does the file work after it's already been run, or partially completed it's work? Real spiders have to resume where they left off. You might need to make some conditional tweaks to the file to account for this. You don't want the code to actually re-download the data, but the code should still run without error!
```
````
```{dropdown} 4. IMPORTANT: Create **screenshot.png**
It's not polite to upload so much data to GitHub. It takes up space on the server, and your collaborators/peer reviewers will have to download them all when they clone your repo.
That's why you edited the gitignore before doing all those downloads. If you did it correctly and check Github Desktop, you won't see any of the text files!
1. Now that your `download_text_files.ipynb` is done running, push the repo. Even though your _computer_ has a `/text_files/*` folder on it with many files and some hard drive space used, the repo in your browser doesn't show this at all! Good job!
2. **Create `screenshot.png`. The purpose of this is to upload proof of the files for your reviewers.**
Right click your `text_files` folder so it shows the number of files inside of it, and take a screenshot showing this. Save it as `screenshot.png` inside your repo.
```
```{dropdown} 5. Download **near_regex.py** from the community codebook into your repo
This will be used in the next step.
```
````{dropdown} 6. Create **measure_risk.ipynb**
The basic idea is to measure risks by counting the number of times a given risk topic is discussed in the 10-K.
This file (broad steps)
1. Creates an `output/` folder
1. Loads the initial dataset of sample firms saved inside of `input/`.
1. For each firm, load the corresponding 10-K and create (at least) 5 different risk measures, and save those new measurements to each of 5 new variables in that row.
1. **Pick one risk type, and think of three ways to measure it.** For example, there are many ways you could try to measure "antitrust risk", so come up with 3 different ways to measure it from the text. You can try different terms, different combinations of terms, different limits on how close terms need to be, and more. Comparing these different ways might help you understand how your choices can improve or hurt the value of your measurement.
2. **Pick a second risk type and create a single measure for it** (you only need to do one measurement on this risk type, but you can do more)
3. **Pick a third risk type and create a single measure for it** (again, you only need to do one, but you can do more)
4. Bonus measures - interesting variables you could also measure:
- The total length of the document (# of words)
- The # of unique words (similar to total length)
- The "tone" of the document
2. Downloads 2019 accounting data (**2019 ccm_cleaned.dta**) from the data folder in the class repo on S&P500 firms (possibly useful in analysis) and adds them to the dataset
1. Save the whole thing to `output/sp500_accting_plus_textrisks.csv`
```{note}
[There is a bunch more on this file/step here.](asgn05_measurerisk)
```
```{tip}
When you are confident the program works, delete your whole `output/` folder on your computer so you have a "fresh start" and then rerun this from scratch.
```
````
````{dropdown} 7. Create **explore_ugly.ipynb** to see if your risk factors were associated with higher or lower returns around covid.
Try to figure out how to do the analysis below, downloading and intergrating return measures. Play around in this file. No one will look at it. It's a safe space.
If you find issues with your risk measurements or come up with improvements you think you should make, go back and work on the previous file more.
You can and should use this file to figure out what you want to include in the final report and how you want it to appear.
````
````{dropdown} 8. Create **analysis_report.ipynb**
```{important}
This is the main portion of your grade. It should be well formatted and clean in terms of text, code, and output. Don't show extraneous print statements. Treat it like a Word document that happens to have some code (but just enough to do the analysis and show outputs). I've included more thoughts in the next dropdown.
```
```{tip}
First compute the returns for the 3/9-3/13 week. This will give you a dataset with one row per firm, and one number per row (the return for that week). Then merge this into the analysis dataset. Rinse and repeat if you try for the other return measures I describe below.
```
1. Load `output/sp500_accting_plus_textrisks.csv`
1. Explain and describe to readers your risk measurements
- How were they measured? (Mechanical description)
- Why did you choose them and what do you hope they capture? (Economic reasoning)
- What are their statistical properties? (Do you have values for most/all firms, they should have variation within them, are they correlated with any accounting measures)
1. **Validation checks and discussion of the risk measurements** **This step (validating the measurement) is very important in production quality analysis!***
- Discuss briefly whether these measurements are likely "valid" in the sense they capture what you hope.
- Present some evidence they do capture your hopes. There are many ways to do this, and depend on the data you have and the risks you're measuring.
- You might print out a few examples of matches.
- One option is to show sentences that will correctly be caught by the search, and correctly not caught. And how easy is it for your search to find a sentence that matches the search but shouldn't.. (Hopefully: not too easy!) How easy is it for your search to miss a sentence that it should match...
- One option is to output the list of firms that have high scores, or the industries that have high and low scores. Does the output make sense?
1. Describe the _final_ sample for your tests, the set of observations where you have all the data you need.
- This includes summary stats,the number of firms, and other things EDA would turn up
- Are there any caveats about the sample and/or data? If so, mention them and briefly discuss possible issues they raise with the analysis.
1. Explore the correlation between your risk values and stock returns around key dates for the onset of covid.
- Stock returns are in the class's data folder ("2019-2020-stock_rets cleaned.zip")
- Get the firm's returns for the week of Mar 9 - Mar 13, 2020 (the cumulative return for the week)
- Bonus: repeat the analysis but use the cumulative returns from Feb 23-Mar 23 as the "collapse period"
- Bonus: repeat the analysis but use Mar 24 as the "stimmy day" (stimulus was announced) ... how does this change your results, and is it doing so in a predictable way?
- Bonus: repeat the analysis, but use firm accounting variables: Some of these probably indicate that a firm should be more [resilient to the crisis](https://privpapers.ssrn.com/sol3/papers.cfm?abstract_id=3597838)!
- Present your findings visually and follow the lessons on effective visualization!
- You should write brief summaries of your findings.
1. Bonus: Explore the risk-return relationship, but use regressions so that you can control for firm traits and market returns. Does this change your results?
- Don't worry about printing these regressions out "pretty", just try them if you want!
1. Bonus: Use **alpha** as y, not returns, in your plots and/or regressions. This will likely change the results.
- Step 1: Separately, for each firm, [estimate the beta and factor loadings](https://ledatascifi.github.io/ledatascifi-2022/content/05/05c_factorloadings.html) of each firm's returns in **2019**. Save that data.
- Step 2: For firm i on date t, alpha(i,t) = ret(i,t) - beta(of firm i)*mkt_return(t) - SMB(of firm i)*SMB_port_ret(t) - HML(of firm i)*HML_port_ret(t)
- _SMB_port_ret(t) is the return on the SMB portfolio on date t, which you can get from the Fama-French datasets!_
- Just present the findings if you do this. Don't worry about explaining it - but it might make more sense in a few weeks!
```{note}
If you want to do any regressions, let me know. I'll give you a few pointers.
```
````
````{dropdown} 9. Finalize and polish
Unlike previous assignments, how clean your code and report are will factor into your grade. Additionally, your README file should be nice!
**Edit the readme file - it should be "publication ready"**
- Make the readme file informative and professional.
- Inform readers of the order in which files should be run. And warn users that this folder will download X files of X MB or GB.
- Change the title of it (not the filename, the title at the top)
- Describe the purpose of this repo (what this repo is analyzing) and the key inputs
- List any necessary packages (might a reader need to `pip install` anything?) or steps a visitor will need to run to make it work on their computer
**The `analysis_report` file should be written and formatted like an executive report.**
- There is no "page expectation" or "page limit". Aim to provide sufficient analysis and explanation, but in a concise and clear way. Bullet points are fine in places, but you should have a few places with paragraph-style discussion, especially where you explain why you chose the specific risks, the way you defined them, and what issues you think they have (which points the way forward on "extensions").
- In other words: You will be graded on how much this looks like a professional report. Just "dumping" endless printouts is not as valuable as well-tailored tables and figures. High quality and concise reporting is an A1 emphasis. **Here, pretty, smart, and effective tables and visualizations will receive higher grades.**
- **The teaching team will _not_ read your measure_risk file other than to comment on code style.** So:
1. Any details in that file on search terms and descriptive information on your text-based measures should be copied into your analysis file (with appropriate adjustments to suit how a report would be presented).
2. Make the measurement code easy to read, because we will grade the code style.
````
## Cheers!
**Give yourself a big round of applause at this point!**
Your code is probably very flexible and powerful at this point. If you have the appetite + a larger list of EDGAR files to download + a large enough hard drive + and time, then you could download more than 100GB of 10-K filings and run textual analysis across 20+ years of data for all publicly traded firms.
Seriously: You are in the ball park of pulling off any analysis you want that needs to harness the power of these filings. These four studies are variously provocative, great, and (in one case) mine:
- [Check this claim: Identifying changes in 10-K/Q filings can generate a 20% alpha](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=1658471)
- [Prof. Hanley measured emerging risks in the financial sector](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2792943)
- [Build a unique list of competitors for each firm (really powerful!)](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=1520062)
- [I used 10-K text to identify public rivals of startup firms](https://ssrn.com/abstract=3245839)
| github_jupyter |
# MHKiT Tidal Module
The following example will familiarize the user with the [MHKiT tidal module](https://mhkit-software.github.io/MHKiT/mhkit-python/api.tidal.html) by stepping through the calculation of the velocity duration curve. The data file used in this example is stored in the [\\\\MHKiT\\\\examples\\\\data](https://github.com/MHKiT-Software/MHKiT-Python/tree/master/examples/data) directory.
Start by importing the necessary MHKiT module.
```
from mhkit import tidal
```
## Loading Data from NOAA-Currents
This example uses 1 year of data from the NOAA-Currents sites. A map of available currents stations is available at https://tidesandcurrents.noaa.gov/map/. The tidal io module includes two functions to import data: `request_noaa_data` which pulls data from the website, and `read_noaa_json` which loads a JSON file. The request function can save the JSON file for later use.
For simplicity, this example loads data from a JSON file into a pandas DataFrame. This data contains 1 year of 6 minute averaged data from the Southampton Shoal Channel LB 6 (Station Number: s08010) in San Francisco Bay. The data includes 6 minute averaged direction [degrees] and speed [cm/s] indexed by time. The DataFrame key names returned by NOAA are 'd' for direction and 's' for speed. Since MHKIT uses SI units, speed is converted to m/s.
```
# Load tidal data, South Hampton Shoal LB 6
data, metadata = tidal.io.read_noaa_json('data/tidal/s08010.json')
# Convert discharge data from cm/s to m/s
data.s = data.s / 100
# Print data
print(data)
```
The data can also be obtained using the function `request_noaa_data` in the tidal IO module.
To use this function, we need a station number, parameter type, start date, and end date.
The station number can be found on the NOAA tides and currents website linked above.
The IEC standard recommends 1 year of 10-minute direction and velocity data. The request function allows users to easily pull any timeframe of data although NOAA limits any one pull to 30 days.
The following code, which has been commented out for this demonstration, can be used to pull data from the NOAA website. This function can be used to save data to a JSON for later use.
```
#data, metadata = tidal.io.request_noaa_data(station='s08010', parameter='currents',
# start_date='20161101', end_date='20180401',
# proxy=None, write_json=`data/s08010.json`)
```
## Principal Flow Directions
As an initial check on the data, a velocity plot can be created to identify data gaps. To consider the velocity in one of the principal flow directions we apply the `principal_flow_directions` function. This function returns 2 directions (in degrees) corresponding to the flood and ebb directions of the tidal site. Principal flow directions are calculated based on the highest frequency directions. These directions are often close to 180 degrees apart but are not required to be.
The `plot_current_timeseries` function plots velocity in either direction using the speed timeseries.
```
# Specify histogram bin width for directions to calculate the principal flow directions
width_direction = 1 # in degrees
# Compute two principal flow directions
direction1, direction2 = tidal.resource.principal_flow_directions(data.d, width_direction)
# Set flood and ebb directions based on site knowledge
flood = direction1 # Flow into
ebb = direction2 # Flow out
```
The time series of current data can be plotted using the `plot_current_timeseries` function, which can include either the flood or ebb directions.
```
ax = tidal.graphics.plot_current_timeseries(data.d, data.s, flood)
```
The plot above shows missing data for most of early and mid-2017. The IEC standard recommends a minimum of 1 year of 10 minute averaged data (See IEC 201 for full description). For the demonstration, this dataset is sufficient. To look at a specific month we can slice the dataset before passing to the plotting function.
```
# Slice December of 2017 out of the full dataset
dec17_data = data.loc['2017-12-01':'2017-12-31']
# Plot December of 2017 as current timeseries
ax = tidal.graphics.plot_current_timeseries(dec17_data.d, dec17_data.s, flood)
```
## Joint Probability Distribution
Direction and velocity can be viewed as a joint probability distribution on a polar plot. This plot helps visually show the flood and ebb directions and the frequency of particular directional velocities.
```
# Set the joint probability bin widths
width_direction = 1 # in degrees
width_velocity = 0.1 # in m/s
# Plot the joint probability distribution
ax = tidal.graphics.plot_joint_probability_distribution(data.d, data.s, \
width_direction, width_velocity, metadata=metadata, flood=flood, ebb=ebb)
```
## Rose plot
A rose plot shows the same information as the joint probability distribution but the probability is now the r-axis, and the velocity is the contour value. As compared to a joint probability distribution plot, a rose plot can be more readable when using larger bins sizes.
```
# Define bin sizes
width_direction = 10 # in degrees
width_velocity = 0.25 # in m/s
# Create a rose plot
ax = tidal.graphics.plot_rose(data.d, data.s, width_direction, \
width_velocity, metadata=metadata, flood=flood, ebb=ebb)
```
## Velocity Duration Curve
The velocity duration curve shows the probability of achieving a particular velocity value. After computing the exceedance probability, the rank order of velocity values can be plotted as follows.
```
# Calculate exceedance probability of data
data['F'] = tidal.resource.exceedance_probability(data.s)
# Plot the velocity duration curve (VDC)
ax = tidal.graphics.plot_velocity_duration_curve(data.s, data.F)
```
| github_jupyter |
# Name(s)
**Sarah Kurdoghlian**
**Instructions:** This is an individual assignment. Complete the following code and push to get your score.
I am providing the autograder answers locally so you may test your code before pushing. I will be reviewing your submissions, and if I find you are circumventing the autograder in any manner, you will receive a 0 on this assignment and your case will be reported to the honor board for review. i.e., approach the assignment in a genuine manner and you have nothing to worry about.
**Question 1.**
When will new material be available each week?
You can answer the question by defining an anonymous function. This creates a function that I can test using pytest. You don't have to worry about the details. You just need to answer the question by changing the string argument that is currently set to "D". I know this is a bit weird, but I want you to get used to submitting code as early as possible.
```
# Nothing to modify in this cell
def question_1(answer):
answers = {
"A": "Monday morning",
"B": "Sunday night",
"C": "Monday evening",
"D": "I don't know"
}
try:
return answers[answer]
except:
return "Not a valid answer"
# YOUR SOLUTION HERE
# Sample incorrect answer
answer_question_1 = lambda: question_1("C")
```
**Question 2.**
Do I need to buy the textbook?
```
# Nothing to modify in this cell
def question_2(answer):
answers = {
"A": "No",
"B": "Maybe",
"C": "Yes. You will struggle with some of the chapters without the textbook",
}
try:
return answers[answer]
except:
return "Not a valid answer"
# YOUR SOLUTION HERE
# Sample incorrect answer
answer_question_2 = lambda: question_2("C")
```
**Question 3.**
Are these any required times that I be online?
```
# Nothing to modify in this cell
def question_3(answer):
answers = {
"A": "Yes",
"B": "No"
}
try:
return answers[answer]
except:
return "Not a valid answer"
# YOUR SOLUTION HERE
# Sample incorrect answer
answer_question_3 = lambda: question_3("A")
```
**Question 4.**
What software will I use to complete the assignments?
```
# Nothing to modify in this cell
def question_4(answer):
answers = {
"A": "Java",
"B": "Netbeans",
"C": "Anaconda"
}
try:
return answers[answer]
except:
return "Not a valid answer"
# YOUR SOLUTION HERE
# Sample incorrect answer
answer_question_4 = lambda: question_4("C")
```
**Question 5.**
Do I need to participate in this class or can I just do the labs and assignments?
```
# Nothing to modify in this cell
def question_5(answer):
answers = {
"A": "Yes. If you want to get anything higher than a C, you'll need to do more than the labs and assignments",
"B": "No",
}
try:
return answers[answer]
except:
return "Not a valid answer"
# YOUR SOLUTION HERE
# Sample incorrect answer
answer_question_5 = lambda: question_5("A")
# Don't forget to push!
```
| github_jupyter |
# Linear Regression
<img src="https://raw.githubusercontent.com/glazec/practicalAI/master/images/logo.png" width=150>
In this lesson we will learn about linear regression. We will first understand the basic math behind it and then implement it in Python. We will also look at ways of interpreting the linear model.
# Overview
<img src="https://raw.githubusercontent.com/glazec/practicalAI/master/images/linear.png" width=250>
$\hat{y} = XW$
*where*:
* $\hat{y}$ = prediction | $\in \mathbb{R}^{NX1}$ ($N$ is the number of samples)
* $X$ = inputs | $\in \mathbb{R}^{NXD}$ ($D$ is the number of features)
* $W$ = weights | $\in \mathbb{R}^{DX1}$
* **Objective:** Use inputs $X$ to predict the output $\hat{y}$ using a linear model. The model will be a line of best fit that minimizes the distance between the predicted and target outcomes. Training data $(X, y)$ is used to train the model and learn the weights $W$ using stochastic gradient descent (SGD).
* **Advantages:**
* Computationally simple.
* Highly interpretable.
* Can account for continuous and categorical features.
* **Disadvantages:**
* The model will perform well only when the data is linearly separable (for classification).
* Usually not used for classification and only for regression.
* **Miscellaneous:** You can also use linear regression for binary classification tasks where if the predicted continuous value is above a threshold, it belongs to a certain class. But we will cover better techniques for classification is future lessons and will focus on linear regression for continuos regression tasks only.
# Training
*Steps*:
1. Randomly initialize the model's weights $W$.
2. Feed inputs $X$ into the model to receive the predictions $\hat{y}$.
3. Compare the predictions $\hat{y}$ with the actual target values $y$ with the objective (cost) function to determine loss $J$. A common objective function for linear regression is mean squarred error (MSE). This function calculates the difference between the predicted and target values and squares it. (the $\frac{1}{2}$ is just for convenicing the derivative operation).
* $MSE = J(\theta) = \frac{1}{2}\sum_{i}(\hat{y}_i - y_i)^2$
4. Calculate the gradient of loss $J(\theta)$ w.r.t to the model weights.
* $J(\theta) = \frac{1}{2}\sum_{i}(\hat{y}_i - y_i)^2 = \frac{1}{2}\sum_{i}(X_iW - y_i)^2 $
* $\frac{\partial{J}}{\partial{W}} = X(\hat{y} - y)$
4. Apply backpropagation to update the weights $W$ using a learning rate $\alpha$ and an optimization technique (ie. stochastic gradient descent). The simplified intuition is that the gradient tells you the direction for how to increase something so subtracting it will help you go the other way since we want to decrease loss $J(\theta)$.
* $W = W- \alpha\frac{\partial{J}}{\partial{W}}$
5. Repeat steps 2 - 4 until model performs well.
# Data
We're going to create some simple dummy data to apply linear regression on.
```
from argparse import Namespace
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Arguments
args = Namespace(
seed=1234,
data_file="sample_data.csv",
num_samples=100,
train_size=0.75,
test_size=0.25,
num_epochs=100,
)
# Set seed for reproducability
np.random.seed(args.seed)
# Generate synthetic data
def generate_data(num_samples):
X = np.array(range(num_samples))
y = 3.65*X + 10
return X, y
# Generate random (linear) data
X, y = generate_data(args.num_samples)
data = np.vstack([X, y]).T
df = pd.DataFrame(data, columns=['X', 'y'])
df.head()
# Scatter plot
plt.title("Generated data")
plt.scatter(x=df["X"], y=df["y"])
plt.show()
```
# Scikit-learn implementation
**Note**: The `LinearRegression` class in Scikit-learn uses the normal equation to solve the fit. However, we are going to use Scikit-learn's `SGDRegressor` class which uses stochastic gradient descent. We want to use this optimization approach because we will be using this for the models in subsequent lessons.
```
# Import packages
from sklearn.linear_model.stochastic_gradient import SGDRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# Create data splits
X_train, X_test, y_train, y_test = train_test_split(
df["X"].values.reshape(-1, 1), df["y"], test_size=args.test_size,
random_state=args.seed)
print ("X_train:", X_train.shape)
print ("y_train:", y_train.shape)
print ("X_test:", X_test.shape)
print ("y_test:", y_test.shape)
```
We need to standardize our data (zero mean and unit variance) in order to properly use SGD and optimize quickly.
```
# Standardize the data (mean=0, std=1) using training data
X_scaler = StandardScaler().fit(X_train)
y_scaler = StandardScaler().fit(y_train.values.reshape(-1,1))
# Apply scaler on training and test data
standardized_X_train = X_scaler.transform(X_train)
standardized_y_train = y_scaler.transform(y_train.values.reshape(-1,1)).ravel()
standardized_X_test = X_scaler.transform(X_test)
standardized_y_test = y_scaler.transform(y_test.values.reshape(-1,1)).ravel()
# Check
print ("mean:", np.mean(standardized_X_train, axis=0),
np.mean(standardized_y_train, axis=0)) # mean should be ~0
print ("std:", np.std(standardized_X_train, axis=0),
np.std(standardized_y_train, axis=0)) # std should be 1
# Initialize the model
lm = SGDRegressor(loss="squared_loss", penalty="none", max_iter=args.num_epochs)
# Train
lm.fit(X=standardized_X_train, y=standardized_y_train)
# Predictions (unstandardize them)
pred_train = (lm.predict(standardized_X_train) * np.sqrt(y_scaler.var_)) + y_scaler.mean_
pred_test = (lm.predict(standardized_X_test) * np.sqrt(y_scaler.var_)) + y_scaler.mean_
```
# Evaluation
There are several evaluation techniques to see how well our model performed.
```
import matplotlib.pyplot as plt
# Train and test MSE
train_mse = np.mean((y_train - pred_train) ** 2)
test_mse = np.mean((y_test - pred_test) ** 2)
print ("train_MSE: {0:.2f}, test_MSE: {1:.2f}".format(train_mse, test_mse))
```
Besides MSE, when we only have one feature, we can visually inspect the model.
```
# Figure size
plt.figure(figsize=(15,5))
# Plot train data
plt.subplot(1, 2, 1)
plt.title("Train")
plt.scatter(X_train, y_train, label="y_train")
plt.plot(X_train, pred_train, color="red", linewidth=1, linestyle="-", label="lm")
plt.legend(loc='lower right')
# Plot test data
plt.subplot(1, 2, 2)
plt.title("Test")
plt.scatter(X_test, y_test, label="y_test")
plt.plot(X_test, pred_test, color="red", linewidth=1, linestyle="-", label="lm")
plt.legend(loc='lower right')
# Show plots
plt.show()
```
# Inference
```
# Feed in your own inputs
X_infer = np.array((0, 1, 2), dtype=np.float32)
standardized_X_infer = X_scaler.transform(X_infer.reshape(-1, 1))
pred_infer = (lm.predict(standardized_X_infer) * np.sqrt(y_scaler.var_)) + y_scaler.mean_
print (pred_infer)
df.head(3)
```
# Interpretability
Linear regression offers the great advantage of being highly interpretable. Each feature has a coefficient which signifies it's importance/impact on the output variable y. We can interpret our coefficient as follows: By increasing X by 1 unit, we increase y by $W$ (~3.65) units.
**Note**: Since we standardized our inputs and outputs for gradient descent, we need to apply an operation to our coefficients and intercept to interpret them. See proof below.
```
# Unstandardize coefficients
coef = lm.coef_ * (y_scaler.scale_/X_scaler.scale_)
intercept = lm.intercept_ * y_scaler.scale_ + y_scaler.mean_ - np.sum(coef*X_scaler.mean_)
print (coef) # ~3.65
print (intercept) # ~10
```
### Proof for unstandardizing coefficients:
Note that both X and y were standardized.
$\frac{\mathbb{E}[y] - \hat{y}}{\sigma_y} = W_0 + \sum_{j=1}^{k}W_jz_j$
$z_j = \frac{x_j - \bar{x}_j}{\sigma_j}$
$ \hat{y}_{scaled} = \frac{\hat{y}_{unscaled} - \bar{y}}{\sigma_y} = \hat{W_0} + \sum_{j=1}^{k} \hat{W}_j (\frac{x_j - \bar{x}_j}{\sigma_j}) $
$\hat{y}_{unscaled} = \hat{W}_0\sigma_y + \bar{y} - \sum_{j=1}^{k} \hat{W}_j(\frac{\sigma_y}{\sigma_j})\bar{x}_j + \sum_{j=1}^{k}(\frac{\sigma_y}{\sigma_j})x_j $
# Regularization
Regularization helps decrease over fitting. Below is L2 regularization (ridge regression). There are many forms of regularization but they all work to reduce overfitting in our models. With L2 regularization, we are penalizing the weights with large magnitudes by decaying them. Having certain weights with high magnitudes will lead to preferential bias with the inputs and we want the model to work with all the inputs and not just a select few. There are also other types of regularization like L1 (lasso regression) which is useful for creating sparse models where some feature cofficients are zeroed out, or elastic which combines L1 and L2 penalties.
**Note**: Regularization is not just for linear regression. You can use it to regualr any model's weights including the ones we will look at in future lessons.
* $ J(\theta) = = \frac{1}{2}\sum_{i}(X_iW - y_i)^2 + \frac{\lambda}{2}\sum\sum W^2$
* $ \frac{\partial{J}}{\partial{W}} = X (\hat{y} - y) + \lambda W $
* $W = W- \alpha\frac{\partial{J}}{\partial{W}}$
where:
* $\lambda$ is the regularzation coefficient
```
# Initialize the model with L2 regularization
lm = SGDRegressor(loss="squared_loss", penalty='l2', alpha=1e-2,
max_iter=args.num_epochs)
# Train
lm.fit(X=standardized_X_train, y=standardized_y_train)
# Predictions (unstandardize them)
pred_train = (lm.predict(standardized_X_train) * np.sqrt(y_scaler.var_)) + y_scaler.mean_
pred_test = (lm.predict(standardized_X_test) * np.sqrt(y_scaler.var_)) + y_scaler.mean_
# Train and test MSE
train_mse = np.mean((y_train - pred_train) ** 2)
test_mse = np.mean((y_test - pred_test) ** 2)
print ("train_MSE: {0:.2f}, test_MSE: {1:.2f}".format(
train_mse, test_mse))
```
Regularization didn't help much with this specific example because our data is generation from a perfect linear equation but for realistic data, regularization can help our model generalize well.
```
# Unstandardize coefficients
coef = lm.coef_ * (y_scaler.scale_/X_scaler.scale_)
intercept = lm.intercept_ * y_scaler.scale_ + y_scaler.mean_ - (coef*X_scaler.mean_)
print (coef) # ~3.65
print (intercept) # ~10
```
# Categorical variables
In our example, the feature was a continuous variable but what if we also have features that are categorical? One option is to treat the categorical variables as one-hot encoded variables. This is very easy to do with Pandas and once you create the dummy variables, you can use the same steps as above to train your linear model.
```
# Create data with categorical features
cat_data = pd.DataFrame(['a', 'b', 'c', 'a'], columns=['favorite_letter'])
cat_data.head()
dummy_cat_data = pd.get_dummies(cat_data)
dummy_cat_data.head()
```
Now you can concat this with your continuous features and train the linear model.
# TODO
- polynomial regression
- simple example with normal equation method (sklearn.linear_model.LinearRegression) with pros and cons vs. SGD linear regression
| github_jupyter |
<a href="https://colab.research.google.com/gist/qbeer/370770dacb737a35fb06725b69a13c05/02_blank.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Unsupervised learning & clustering
----
### 1. Reading data
The worldbank_jobs_2016.tsv (can be found in the same folder with this notebook) file contains the Jobs (and other) data for the 2016 year, downloaded from The World Bank's webpage.
- Look at the data in any text editor. Build up an overall sense how the data is built up and how the missing values are represented.
- Read the file into a pandas dataframe and tell pandas the delimiter (or separator) that separates the columns and which special pattern means if a value is missing.
- Keep only those rows, which represents countries, at the end there are some useless rows (with missing country code).
- The data is in a long format. Convert it into a wide format, where each row is a single country (with country code) and the column names are the features i.e. the Series Codes, the values in the columns are the measured values of the 2016 [YR 2016 column]. (eg the first column is 'EG.CFT.ACCS.ZS', the second is 'EG.ELC.ACCS.ZS'. Order of the columns does not matter)! Try to use the pivot method.
- Check that the features are in numeric format (dtypes), this will be needed for modeling!
#### 1/a. Data loading, NaN row removal
```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys
import os
import seaborn as sns
#tabulator separated file, which has missing values that pandas inserts as NaNs
worldbank_data = pd.read_csv("02_dataset_worldbank_jobs_2016.tsv", delimiter="\t", na_values='..')
print(worldbank_data.columns)
print(pd.unique(worldbank_data["Country Name"])) #let's see if these are like actual countries
print(pd.unique(worldbank_data["Country Code"])) # country code could have been used to remove bad rows
worldbank_data1 = worldbank_data[:-5] #last 5 rows to be removed
print(~worldbank_data1.isna())
print(worldbank_data1.isna().sum()) #this simply tells how many nans are in the data, remaining
#may become handy
features = {n : c for (n, c) in zip(worldbank_data['Series Code'],worldbank_data['Series Name'])}
```
So it seems like that only the end has that couple rows that is unneeded. With the country code, that can be removed. The last 5 rows had to be removed. Due to only these rows being not data rows, they could be removed by just simply counting them.
After a quick revision, I see something like ".." in data which are NaNs actually -> fixed it, pandas.read_csv can handle predefined
#### 1/b. Long to wide dataformat
```
worldbank_data_wide = worldbank_data1.pivot(index="Country Name", columns="Series Code", values = "2016 [YR2016]") #my actual first successful pivot... i can feel its strength!
display(worldbank_data_wide) #display as intelligent print
```
#### 1/c. Numeric Dataformat
Don't really know whats going on here, but I am going to look into the value formats
```
type(worldbank_data_wide.loc["Hungary"][0]) == np.float64
```
Okey, let's go through the whole data...
```
array_copy = np.array(worldbank_data_wide).T #copy and transpose
array_f_str_count = np.zeros(array_copy.shape[0])
for i,j in enumerate(array_copy): #i am too used to for i in range(x_min,x_max): for j in range(y_min,y_max):
array_f_str_count[i] = sum(1 for value in j if type(value)==str)
display(array_f_str_count) #so they seem like they are in the correct format
```
I don't think I need a conversion to numeric, but I will do it just get to know it.
```
for column in worldbank_data_wide.columns:
worldbank_data_wide[column] = pd.to_numeric(worldbank_data_wide[column])
```
<font size="4"> My guess is that the many ".." are messing with datatypes and I added them as a NaN format to read_csv to load it as NaN, which is in float64, which is numeric. I really like how pleasently smart and easy it is.</font>
-----
### 2. Data preprocessing and inspection
- Visualize the missing values!
- Keep only those countries which has less than 60 missing features in the original table.
- After this drop all features which have missing values for the remaining countries. (Imputation would also work but may introduce a bias because there is less data for less developed countries generally.)
- How many counties and features do we have left?
- Read the kept features' descriptions. In the original table the Series Name describe the meaning of the features. What do you think, based only on these information, which counties are the most similar to Hungary? And Greece?
#### 2/a. Visualizing missing data
```
plt.figure(figsize=(166/15, 217/15))
im = plt.imshow(worldbank_data_wide.isna(), aspect='auto')
plt.show()
```
Okey, seems like there is a lot of missing data present. ONTO THE SORTING!
#### 2/b. Dropping rows with more than 60 missing values
pandas dropna helps me out here!
```
worldbank_data_wide_c = worldbank_data_wide.dropna(axis='rows', thresh=(166-60))
worldbank_data_wide_c
plt.figure(figsize=(166/15, 217/15))
plt.title("Countries with less than 60 missing values", fontsize=24)
im = plt.imshow(worldbank_data_wide_c.isna(), aspect='auto')
plt.show()
```
#### 2/c. Dropping features
```
worldbank_data_wide_cnf = worldbank_data_wide_c.dropna(axis="columns", thresh=110) #where to draw the threshhold is a mystery
plt.figure(figsize=(166/15, 217/15))
plt.title("Filtered countries and features", fontsize=24)
im = plt.imshow(worldbank_data_wide_cnf.isna(), aspect='auto')
plt.show()
```
So, it looks mostly clean. I had to try different threshholds to see which one is good to remove most of the NaNs but won't remove all of them.
`NOTE`: yes, fill NaNs with something - the mean of each column. NaN values stop PCA due to the no comparison, hence filling in is required. Means involve bias, but I removed most of the means, so minimal bias is inserted.
```
worldbank_data_wide_cnf1 = worldbank_data_wide_cnf.fillna(worldbank_data_wide_cnf.mean())
```
#### 2/d. Closest country to Hungary and Greece.
My initial thought is to measure the Hamming distance with each country, but that not just seems to be way obvious and some stuff doesn't doesnt scale in a linear way.
```
#display(worldbank_data_wide_cnf.loc['Hungary'])
#display(worldbank_data_wide_cnf.loc['Greece'])
#display(worldbank_data_wide_cnf.index[0])
dist1 = np.zeros(len(worldbank_data_wide_cnf.index))
#go through data
"""
for i in worldbank_data_wide_cnf.index:
#country name is i
partial_sum = 0
for j in range(0,len(worldbank_data_wide_cnf.loc[country_name])):
if country_name != "Hungary":
partial_sum += np.abs(worldbank_data_wide_cnf.loc[i][j] - worldbank_data_wide_cnf.loc["Hungary"][j]) / worldbank_data_wide_cnf[worldbank_data_wide_cnf.columns[j]]
#calculate distance and then normalize it
print(partial_sum)
"""
country1 = "Hungary"
country2 = "Greece"
#for j in range(0,len(worldbank_data_wide_cnf.loc[country_name])):
#partial_sum += np.abs(worldbank_data_wide_cnf.loc[country1][j] - worldbank_data_wide_cnf.loc[country2][j]) / np.max(np.abs(worldbank_data_wide_cnf[worldbank_data_wide_cnf.columns[j]][j]))
#print((worldbank_data_wide_cnf.loc[country1][0] - worldbank_data_wide_cnf.loc[country2][0]) / np.max(np.abs(worldbank_data_wide_cnf[worldbank_data_wide_cnf.columns[j]][j])))
for j in range(0,len(worldbank_data_wide_cnf1.loc[country_name])):
print(np.max(np.abs(worldbank_data_wide_cnf1[worldbank_data_wide_cnf1.columns[j]][j])))
print(np.max(np.abs(worldbank_data_wide_cnf1[worldbank_data_wide_cnf1.columns[j]][j])))
#worldbank_data_wide_cnf[worldbank_data_wide_cnf.columns[9]][9]
```
Okey, I can't see it through, but I feel that I am inches close.
------
### 3. PCA
- Perform PCA with 3 principal components on the filtered, imputed data (from now on, data refers to the filtered, imputed dataset)
- Plot the three embedded 2D combination next to each other (0 vs 1, 0 vs 2 and 1 vs 2)
- It seems that the embedding is really dominated by a single direction. Normalize the data (each feature should have zero mean and unit variance after normalization) and re-do the PCA and the plotting (do not delete the previous plots, just make new ones).
- Give some explaination for the second principal component: Look at the coefficients of the features which were use the calculate that principal component. For the features with the largest coefficient (in absolute value) look up the Series Name for the Code.
```
#stuff from sklearn, have to get to know it better
from sklearn import decomposition
from sklearn.manifold import TSNE
from sklearn.cluster import KMeans
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler
#as i was normalazing earlier the sums, it good to have a function that normalazes input data
def norm_data(x):
#I DONT LIKE BURNING
x = pd.DataFrame(StandardScaler().fit_transform(x), index=worldbank_data_wide_cnf1.index, columns=worldbank_data_wide_cnf1.columns)
return x
#lets do a pca
def PCA(data):
#do pca -> return data
pca = decomposition.PCA(n_components=3) #burning in 3d
#TypeError: float() argument must be a string or a number, not 'method' - some idiot with xxx.mean without ()
pca.fit(data)
data_pca = pca.transform(data)
#and to see for impactful the PCA features
ex_var = np.var(data_pca, axis=0)
ex_var_ratio = ex_var/np.sum(ex_var)
return pca, data_pca, ex_var_ratio
def get_impactful_features(pca, features,f_num):
pca_basis = pca.components_
pc_f_idx = []
pc_f = []
for pc in range(pca_basis.shape[0]):
pc_current = pca_basis[pc]
pc_n_f_idx = []
pc_n_f = []
for i in range(f_num):
f_idx = np.where(np.abs(pc_current) == sorted(np.abs(pc_current))[::-1][i])[0][0]
pc_n_f_idx.append(f_idx)
pc_n_f.append(list(features.keys())[f_idx])
pc_f_idx.append(pc_n_f_idx)
pc_f.append(pc_n_f)
return pc_f_idx, pc_f
#great help https://towardsdatascience.com/pca-clearly-explained-how-when-why-to-use-it-and-feature-importance-a-guide-in-python-7c274582c37e
```
#### 3/a. Unscaled (No normalization)
```
pca, data_pca, ex_var_ration = PCA(data=worldbank_data_wide_cnf1)
print("Ration [{:.3f} {:.3f} {:.3f} ]\t Weight of the three features: {:.3f}".format(*ex_var_ration, sum(ex_var_ration))) #YES WE HAVE THEEEEM
fig, ax = plt.subplots(1,3, figsize=(15,5))
ax[0].scatter(data_pca[:,0], data_pca[:,1])
ax[1].scatter(data_pca[:,1], data_pca[:,2])
ax[2].scatter(data_pca[:,0], data_pca[:,2])
ax[0].set_xlabel("First PC", fontsize=19)
ax[1].set_xlabel("Second PC", fontsize=19)
ax[2].set_xlabel("First PC", fontsize=19)
ax[0].set_ylabel("Second PC", fontsize=19)
ax[1].set_ylabel("Third PC", fontsize=19)
ax[2].set_ylabel("Third PC", fontsize=19)
for i in range(3):
ax[i].grid(True)
fig.tight_layout()
plt.show()
```
#### 3/b. Scaled (Normalization)
```
worldbank_wide_cnf1_norm = norm_data(worldbank_data_wide_cnf1)
pca_s, data_pca_s, ex_var_ration_s = PCA(data=worldbank_wide_cnf1_norm)
print("Ration [{:.3f} {:.3f} {:.3f} ]\t Weight of the three features: {:.3f}".format(*ex_var_ration_s, sum(ex_var_ration_s))) #YES WE HAVE THEEEEM
fig, ax = plt.subplots(1,3, figsize=(15,5))
ax[0].scatter(data_pca_s[:,0], data_pca_s[:,1])
ax[1].scatter(data_pca_s[:,1], data_pca_s[:,2])
ax[2].scatter(data_pca_s[:,0], data_pca_s[:,2])
ax[0].set_xlabel("First PC", fontsize=19)
ax[1].set_xlabel("Second PC", fontsize=19)
ax[2].set_xlabel("First PC", fontsize=19)
ax[0].set_ylabel("Second PC", fontsize=19)
ax[1].set_ylabel("Third PC", fontsize=19)
ax[2].set_ylabel("Third PC", fontsize=19)
for i in range(3):
ax[i].grid(True)
fig.tight_layout()
plt.show()
```
OKEY! So a scaling could be very meaningful! And shows how impactful some features really are, due to some overshadowing. Let's see why this change exists! I moved the dict with upper, but i still have to get what it is...
```
pc_f_idx, pc_f = get_impactful_features(pca, features, 5)
pc_f = np.array(pc_f)
k = list(features.keys())
v = list(features.values())
for i in range(pc_f.shape[1]):
print('{} : {}'.format(i,v[k.index(str(pc_f[1,i]))]))
```
So the second PC is related to employment rates... Not suprise that this is the second PC
<font size="4"> This is where I stop. Due to illness, I am much slower... </font>
-----
### 4. T-SNE
- Perform T-SNE on the scaled data with 2 components
- Plot the embeddings results. Add a text label for each point to make it possible to interpret the results. It will not be possible to read all, but try to make it useful, see the attached image as an example!
- Highlight Hungary, Greece, Norway, China, Russia (HUN, GRC, NOR, CHN, RUS)! Which countries are the closest one to Hungary and Greece?
-------
### 5. Hierarchical and K-Means clustering
- Perform hierarchical clustering on the filtered and scaled data (hint: use seaborn)
- Try to plot in a way that all country's name is visible
- Perform K-Means clustering on the filtered and scaled data with 4 clusters.
- Make a plot with text label for each point as in the previous excersice but use different color for every cluster.
- Write down your impressions that you got from these two plots! Which cluster are China and Hungary in?
----
### Hints:
- On total you can get 10 points for fully completing all tasks.
- Decorate your notebook with questions, explanation etc, make it self contained and understandable!
- Comment your code when necessary!
- Write functions for repetitive tasks!
- Use the pandas package for data loading and handling
- Use matplotlib and seaborn for plotting or bokeh and plotly for interactive investigation
- Use the scikit learn package for almost everything
- Use for loops only if it is really necessary!
- Code sharing is not allowed between students! Sharing code will result in zero points.
- If you use code found on web, it is OK, but, make its source clear!
| github_jupyter |
```
%matplotlib notebook
import control as c
import ipywidgets as w
import numpy as np
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.animation as animation
display(HTML('<script> $(document).ready(function() { $("div.input").hide(); }); </script>'))
```
## Control design for a 1DoF mass-spring-damper system
The following example is a control design task for a mass-spring-damper system, a typical second-order model. The structure consists of a sliding mass (friction is ignored), connected to a reference point with an infinitely expandable string-damper pair.<br><br>
<img src="Images/mbk.png" width="40%" />
<br>
Its equation of motion can be stated as:
<br>
$$m\cdot\ddot{x}+b\cdot\dot{x}+k\cdot{x}=F$$
<br>
After the Laplace transformation of the differential equation, the transfer function can be expressed as:
<br>
$$G(s)=\frac{1}{m\cdot s^2 +b\cdot s + k}$$
<br>
Your task is to choose a controller type, and tune it to acceptable levels of performance!
<b>First, choose a system model!</b><br>
Toggle between different realistic models with randomly preselected values (buttons *Model 1* - *Model 6*). By clicking the *Preset* button default, valid predetermined controller parameters are set and cannot be tuned further.
```
# Figure definition
fig1, ((f1_ax1), (f1_ax2)) = plt.subplots(2, 1)
fig1.set_size_inches((9.8, 5))
fig1.set_tight_layout(True)
f1_line1, = f1_ax1.plot([], [])
f1_line2, = f1_ax2.plot([], [])
f1_ax1.grid(which='both', axis='both', color='lightgray')
f1_ax2.grid(which='both', axis='both', color='lightgray')
f1_ax1.autoscale(enable=True, axis='both', tight=True)
f1_ax2.autoscale(enable=True, axis='both', tight=True)
f1_ax1.set_title('Bode magnitude plot', fontsize=11)
f1_ax1.set_xscale('log')
f1_ax1.set_xlabel(r'$f\/$[Hz]', labelpad=0, fontsize=10)
f1_ax1.set_ylabel(r'$A\/$[dB]', labelpad=0, fontsize=10)
f1_ax1.tick_params(axis='both', which='both', pad=0, labelsize=8)
f1_ax2.set_title('Bode phase plot', fontsize=11)
f1_ax2.set_xscale('log')
f1_ax2.set_xlabel(r'$f\/$[Hz]', labelpad=0, fontsize=10)
f1_ax2.set_ylabel(r'$\phi\/$[°]', labelpad=0, fontsize=10)
f1_ax2.tick_params(axis='both', which='both', pad=0, labelsize=8)
# System parameters
def build_base_model(m, k, b):
W_sys = c.tf([1], [m, b, k])
print('System transfer function:')
print(W_sys)
# System analysis
poles = c.pole(W_sys) # Poles
print('System poles:\n')
print(poles)
global f1_line1, f1_line2
f1_ax1.lines.remove(f1_line1)
f1_ax2.lines.remove(f1_line2)
mag, phase, omega = c.bode_plot(W_sys, Plot=False) # Bode-plot
f1_line1, = f1_ax1.plot(omega/2/np.pi, 20*np.log10(mag), lw=1, color='blue')
f1_line2, = f1_ax2.plot(omega/2/np.pi, phase*180/np.pi, lw=1, color='blue')
f1_ax1.relim()
f1_ax2.relim()
f1_ax1.autoscale_view()
f1_ax2.autoscale_view()
# GUI widgets
typeSelect = w.ToggleButtons(
options=[('Model 1', 0), ('Model 2', 1), ('Model 3', 2), ('Model 4', 3), ('Model 5', 4), ('Model 6', 5), ('Preset', -1)],
value =-1, description='System: ', layout=w.Layout(width='60%'))
m_slider = w.FloatLogSlider(value=0.5, base=10, min=-3, max=3, description='m [kg] :', continuous_update=False,
layout=w.Layout(width='auto', flex='5 5 auto'))
k_slider = w.FloatLogSlider(value=100, base=10, min=-2, max=4, description='k [N/m] :', continuous_update=False,
layout=w.Layout(width='auto', flex='5 5 auto'))
b_slider = w.FloatLogSlider(value=50, base=10, min=-2, max=4, description='b [Ns/m] :', continuous_update=False,
layout=w.Layout(width='auto', flex='5 5 auto'))
input_data = w.interactive_output(build_base_model, {'m':m_slider, 'k':k_slider, 'b':b_slider})
def update_sliders(index):
global m_slider, k_slider, b_slider
mval = [0.05, 0.1, 0.25, 0.5, 1, 5, 0.25]
kval = [1.25, 10, 100, 10, 50, 1000, 50]
bval = [1, 0.5, 2, 10, 10, 20, 1]
m_slider.value = mval[index]
k_slider.value = kval[index]
b_slider.value = bval[index]
if index == -1:
m_slider.disabled = True
k_slider.disabled = True
b_slider.disabled = True
else:
m_slider.disabled = False
k_slider.disabled = False
b_slider.disabled = False
input_data2 = w.interactive_output(update_sliders, {'index':typeSelect})
display(typeSelect, input_data2)
display(w.HBox([m_slider, k_slider, b_slider]), input_data)
```
Depending on your selection, the system is either under- or overdamped.
<br>
<b>Select an appropriate controller configuration! Which one is the best for your system? Why?<br>
Set up your controller for the fastest settling time with at most 25% overshoot!</b>
You can turn on/off each of the I and D components, and if D is active, you can apply the first-order filter as well, based on the derivating time constant.
```
# PID position control
fig2, ((f2_ax1, f2_ax2, f2_ax3), (f2_ax4, f2_ax5, f2_ax6)) = plt.subplots(2, 3)
fig2.set_size_inches((9.8, 5))
fig2.set_tight_layout(True)
f2_line1, = f2_ax1.plot([], [])
f2_line2, = f2_ax2.plot([], [])
f2_line3, = f2_ax3.plot([], [])
f2_line4, = f2_ax4.plot([], [])
f2_line5, = f2_ax5.plot([], [])
f2_line6, = f2_ax6.plot([], [])
f2_ax1.grid(which='both', axis='both', color='lightgray')
f2_ax2.grid(which='both', axis='both', color='lightgray')
f2_ax3.grid(which='both', axis='both', color='lightgray')
f2_ax4.grid(which='both', axis='both', color='lightgray')
f2_ax5.grid(which='both', axis='both', color='lightgray')
f2_ax6.grid(which='both', axis='both', color='lightgray')
f2_ax1.autoscale(enable=True, axis='both', tight=True)
f2_ax2.autoscale(enable=True, axis='both', tight=True)
f2_ax3.autoscale(enable=True, axis='both', tight=True)
f2_ax4.autoscale(enable=True, axis='both', tight=True)
f2_ax5.autoscale(enable=True, axis='both', tight=True)
f2_ax6.autoscale(enable=True, axis='both', tight=True)
f2_ax1.set_title('Closed loop step response', fontsize=9)
f2_ax1.set_xlabel(r'$t\/$[s]', labelpad=0, fontsize=8)
f2_ax1.set_ylabel(r'$x\/$[m]', labelpad=0, fontsize=8)
f2_ax1.tick_params(axis='both', which='both', pad=0, labelsize=6)
f2_ax2.set_title('Nyquist diagram', fontsize=9)
f2_ax2.set_xlabel(r'Re', labelpad=0, fontsize=8)
f2_ax2.set_ylabel(r'Im', labelpad=0, fontsize=8)
f2_ax2.tick_params(axis='both', which='both', pad=0, labelsize=6)
f2_ax3.set_title('Bode magniture plot', fontsize=9)
f2_ax3.set_xscale('log')
f2_ax3.set_xlabel(r'$f\/$[Hz]', labelpad=0, fontsize=8)
f2_ax3.set_ylabel(r'$A\/$[dB]', labelpad=0, fontsize=8)
f2_ax3.tick_params(axis='both', which='both', pad=0, labelsize=6)
f2_ax4.set_title('Closed loop impulse response', fontsize=9)
f2_ax4.set_xlabel(r'$t\/$[s]', labelpad=0, fontsize=8)
f2_ax4.set_ylabel(r'$x\/$[m]', labelpad=0, fontsize=8)
f2_ax4.tick_params(axis='both', which='both', pad=0, labelsize=6)
f2_ax5.set_title('Load transfer step response', fontsize=9)
f2_ax5.set_xlabel(r'$t\/$[s]', labelpad=0, fontsize=8)
f2_ax5.set_ylabel(r'$x\/$[m]', labelpad=0, fontsize=8)
f2_ax5.tick_params(axis='both', which='both', pad=0, labelsize=6)
f2_ax6.set_title('Bode phase plot', fontsize=9)
f2_ax6.set_xscale('log')
f2_ax6.set_xlabel(r'$f\/$[Hz]', labelpad=0, fontsize=8)
f2_ax6.set_ylabel(r'$\phi\/$[°]', labelpad=0, fontsize=8)
f2_ax6.tick_params(axis='both', which='both', pad=0, labelsize=6)
def position_control(Kp, Ti, Td, Fd, Ti0, Td0, Fd0, m, k, b):
W_sys = c.tf([1], [m, b, k])
# PID Controller
P = Kp # Proportional term
I = Kp / Ti # Integral term
D = Kp * Td # Derivative term
Td_f = Td / Fd # Derivative term filter
W_PID = c.parallel(c.tf([P], [1]),
c.tf([I * Ti0], [1 * Ti0, 1 * (not Ti0)]),
c.tf([D * Td0, 0], [Td_f * Td0 * Fd0, 1])) # PID controller in time constant format
W_open = c.series(W_PID, W_sys) # Open loop with two integrators added for position output
W_closed = c.feedback(W_open, 1, -1) # Closed loop with negative feedback
W_load = c.feedback(W_sys, W_PID, -1) # Transfer function of the load based errors
# Display
global f2_line1, f2_line2, f2_line3, f2_line4, f2_line5, f2_line6
f2_ax1.lines.remove(f2_line1)
f2_ax2.lines.remove(f2_line2)
f2_ax3.lines.remove(f2_line3)
f2_ax4.lines.remove(f2_line4)
f2_ax5.lines.remove(f2_line5)
f2_ax6.lines.remove(f2_line6)
tout, yout = c.step_response(W_closed)
f2_line1, = f2_ax1.plot(tout, yout, lw=1, color='blue')
_, _, ob = c.nyquist_plot(W_open, Plot=False) # Small resolution plot to determine bounds
real, imag, freq = c.nyquist_plot(W_open, omega=np.logspace(np.log10(ob[0]), np.log10(ob[-1]), 1000), Plot=False)
f2_line2, = f2_ax2.plot(real, imag, lw=1, color='blue')
mag, phase, omega = c.bode_plot(W_open, Plot=False)
f2_line3, = f2_ax3.plot(omega/2/np.pi, 20*np.log10(mag), lw=1, color='blue')
f2_line6, = f2_ax6.plot(omega/2/np.pi, phase*180/np.pi, lw=1, color='blue')
tout, yout = c.impulse_response(W_closed)
f2_line4, = f2_ax4.plot(tout, yout, lw=1, color='blue')
tout, yout = c.step_response(W_load)
f2_line5, = f2_ax5.plot(tout, yout, lw=1, color='blue')
f2_ax1.relim()
f2_ax2.relim()
f2_ax3.relim()
f2_ax4.relim()
f2_ax5.relim()
f2_ax6.relim()
f2_ax1.autoscale_view()
f2_ax2.autoscale_view()
f2_ax3.autoscale_view()
f2_ax4.autoscale_view()
f2_ax5.autoscale_view()
f2_ax6.autoscale_view()
def update_controller(index):
global Kp_slider, Ti_slider, Td_slider, Fd_slider, Ti_button, Td_button, Fd_button
if index == -1:
Kp_slider.value = 100
Td_slider.value = 0.05
Fd_slider.value = 10
Ti_button.value = False
Td_button.value = True
Fd_button.value = True
Kp_slider.disabled = True
Ti_slider.disabled = True
Td_slider.disabled = True
Fd_slider.disabled = True
Ti_button.disabled = True
Td_button.disabled = True
Fd_button.disabled = True
else:
Kp_slider.disabled = False
Ti_slider.disabled = False
Td_slider.disabled = False
Fd_slider.disabled = False
Ti_button.disabled = False
Td_button.disabled = False
Fd_button.disabled = False
# GUI widgets
Kp_slider = w.FloatLogSlider(value=0.5, base=10, min=-1, max=4, description='Kp:', continuous_update=False,
layout=w.Layout(width='auto', flex='5 5 auto'))
Ti_slider = w.FloatLogSlider(value=0.0035, base=10, min=-4, max=1, description='', continuous_update=False,
layout=w.Layout(width='auto', flex='5 5 auto'))
Td_slider = w.FloatLogSlider(value=1, base=10, min=-4, max=1, description='', continuous_update=False,
layout=w.Layout(width='auto', flex='5 5 auto'))
Fd_slider = w.FloatLogSlider(value=1, base=10, min=0, max=3, description='', continuous_update=False,
layout=w.Layout(width='auto', flex='5 5 auto'))
Ti_button = w.ToggleButton(value=True, description='Ti',
layout=w.Layout(width='auto', flex='1 1 0%'))
Td_button = w.ToggleButton(value=False, description='Td',
layout=w.Layout(width='auto', flex='1 1 0%'))
Fd_button = w.ToggleButton(value=False, description='Fd',
layout=w.Layout(width='auto', flex='1 1 0%'))
input_data = w.interactive_output(position_control, {'Kp': Kp_slider, 'Ti': Ti_slider, 'Td': Td_slider,
'Fd': Fd_slider, 'Ti0' : Ti_button, 'Td0': Td_button,
'Fd0': Fd_button, 'm':m_slider, 'k':k_slider, 'b':b_slider})
w.interactive_output(update_controller, {'index': typeSelect})
display(w.HBox([Kp_slider, Ti_button, Ti_slider, Td_button, Td_slider, Fd_button, Fd_slider]), input_data)
```
In the following simulation, you can observe the movement of your system based on your controller setup. You can create reference signals and even apply some disturbance and see how the system reacts.
<b>Is your configuration suitable for signal-following? Readjust your controller so that it can follow a sine wave acceptably!</b>
<br><br>
<i>(The animations are scaled to fit the frame through the whole simulation. Because of this, unstable solutions might not seem to move until the very last second.)</i>
```
# Simulation data
anim_fig = plt.figure()
anim_fig.set_size_inches((9.8, 6))
anim_fig.set_tight_layout(True)
anim_ax1 = anim_fig.add_subplot(211)
anim_ax2 = anim_ax1.twinx()
frame_count=1000
l1 = anim_ax1.plot([], [], lw=1, color='blue')
l2 = anim_ax1.plot([], [], lw=2, color='red')
l3 = anim_ax2.plot([], [], lw=1, color='grey')
line1 = l1[0]
line2 = l2[0]
line3 = l3[0]
anim_ax1.legend(l1+l2+l3, ['Reference [m]', 'Output [m]', 'Load [N]'], loc=1)
anim_ax1.set_title('Time response simulation', fontsize=12)
anim_ax1.set_xlabel(r'$t\/$[s]', labelpad=0, fontsize=10)
anim_ax1.set_ylabel(r'$x\/$[m]', labelpad=0, fontsize=10)
anim_ax1.tick_params(axis='both', which='both', pad=0, labelsize=8)
anim_ax2.set_ylabel(r'$F\/$[N]', labelpad=0, fontsize=10)
anim_ax2.tick_params(axis='both', which='both', pad=0, labelsize=8)
anim_ax1.grid(which='both', axis='both', color='lightgray')
T_plot = []
X_plot = []
L_plot = []
R_plot = []
# Scene data
scene_ax = anim_fig.add_subplot(212)
scene_ax.set_xlim((-3, 4))
scene_ax.set_ylim((-0.5, 1.5))
scene_ax.axis('off')
scene_ax.plot([-2.5, -2.3, -2.3, -0.3, -2.3, -2.3, -0.3], [0.75, 0.75, 0.9, 0.9, 0.9, 0.6, 0.6], lw=2, color='blue', zorder=0)
scene_ax.plot([-2.5, -2.3], [0.25, 0.25], lw=2, color='red', zorder=0)
scene_ax.plot([-2.5, -2.5], [1.25, -0.25], lw=4, color='gray', zorder=2)
scene_ax.text(-1.3, 1, 'b', fontsize=14, color='blue', va='bottom', zorder=5)
scene_ax.text(-1.3, 0, 'k', fontsize=14, color='red', va='top', zorder=5)
b_line, = scene_ax.plot([], [], lw=2, color='blue')
k_line, = scene_ax.plot([], [], lw=2, color='red')
m_text = scene_ax.text(1.75, 0.5, 'm', fontsize=14, color='green', va='center', ha='center', zorder=5)
m_box = patches.Rectangle((1, 0), 1.5, 1, lw=2, color='green', fill=False, zorder=10)
scene_ax.add_patch(m_box)
x_arrow = scene_ax.arrow(1.75, -0.5, 0, 0.25, color='blue', head_width=0.1,
length_includes_head=True, lw=1, fill=False, zorder=5)
r_arrow = scene_ax.arrow(1.75, -0.5, 0, 0.25, color='red', head_width=0.1,
length_includes_head=True, lw=1, fill=False, zorder=5)
base_arrow = x_arrow.xy
pos_var = []
ref_var = []
#Simulation function
def simulation(Kp, Ti, Td, Fd, Ti0, Td0, Fd0, m, k, b, T, dt, X, Xf, Xa, Xo, L, Lf, La, Lo):
# Controller
P = Kp # Proportional term
I = Kp / Ti # Integral term
D = Kp * Td # Derivative term
Td_f = Td / Fd # Derivative term filter
W_PID = c.parallel(c.tf([P], [1]),
c.tf([I * Ti0], [1 * Ti0, 1 * (not Ti0)]),
c.tf([D * Td0, 0], [Td_f * Td0 * Fd0, 1])) # PID controller
# System
W_sys = c.tf([1], [m, b, k])
# Model
W_open = c.series(W_PID, W_sys) # Open loop with two integrators added for position output
W_closed = c.feedback(W_open, 1, -1) # Closed loop with negative feedback
W_load = c.feedback(W_sys, W_PID, -1) # Transfer function of the load based errors
# Reference and disturbance signals
T_sim = np.arange(0, T, dt, dtype=np.float64)
if X == 0: # Constant reference
X_sim = np.full_like(T_sim, Xa * Xo)
elif X == 1: # Sine wave reference
X_sim = (np.sin(2 * np.pi * Xf * T_sim) + Xo) * Xa
elif X == 2: # Square wave reference
X_sim = (np.sign(np.sin(2 * np.pi * Xf * T_sim)) + Xo) * Xa
if L == 0: # Constant load
L_sim = np.full_like(T_sim, La * Lo)
elif L == 1: # Sine wave load
L_sim = (np.sin(2 * np.pi * Lf * T_sim) + Lo) * La
elif L == 2: # Square wave load
L_sim = (np.sign(np.sin(2 * np.pi * Lf * T_sim)) + Lo) * La
elif L_type.value == 3: # Noise form load
L_sim = np.interp(T_sim, np.linspace(0, T, int(T * Lf) + 2),
np.random.normal(loc=(Lo * La), scale=La, size=int(T * Lf) + 2))
# System response
Tx, youtx, xoutx = c.forced_response(W_closed, T_sim, X_sim)
Tl, youtl, xoutl = c.forced_response(W_load, T_sim, L_sim)
R_sim = np.nan_to_num(youtx + youtl)
# Display
XR_max = max(np.amax(np.absolute(np.concatenate((X_sim, R_sim)))), Xa)
L_max = max(np.amax(np.absolute(L_sim)), La)
anim_ax1.set_xlim((0, T))
anim_ax1.set_ylim((-1.2 * XR_max, 1.2 * XR_max))
anim_ax2.set_ylim((-1.5 * L_max, 1.5 * L_max))
global T_plot, X_plot, L_plot, R_plot, pos_var, ref_var
T_plot = np.linspace(0, T, frame_count, dtype=np.float32)
X_plot = np.interp(T_plot, T_sim, X_sim)
L_plot = np.interp(T_plot, T_sim, L_sim)
R_plot = np.interp(T_plot, T_sim, R_sim)
pos_var = R_plot/XR_max
ref_var = X_plot/XR_max
def anim_init():
line1.set_data([], [])
line2.set_data([], [])
line3.set_data([], [])
b_line.set_data([], [])
k_line.set_data([], [])
x_arrow.set_xy(base_arrow)
r_arrow.set_xy(base_arrow)
m_text.set_position((1.75, 0.5))
m_box.set_xy((1, 0))
return (line1, line2, line3, m_text, m_box, b_line, k_line,)
def animate(i):
line1.set_data(T_plot[0:i], X_plot[0:i])
line2.set_data(T_plot[0:i], R_plot[0:i])
line3.set_data(T_plot[0:i], L_plot[0:i])
b_line.set_data([-1.3, -1.3, -1.3, 1]+pos_var[i], [0.66, 0.84, 0.75, 0.75])
k_line.set_data(np.append(np.array([0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 22])*(pos_var[i]+2)/20-2.3, pos_var[i]+1),
[0.25, 0.34, 0.16, 0.34, 0.16, 0.34, 0.16, 0.34, 0.16, 0.34, 0.16, 0.34, 0.25, 0.25])
x_arrow.set_xy(base_arrow+[ref_var[i], 0])
r_arrow.set_xy(base_arrow+[pos_var[i], 0])
m_text.set_position((pos_var[i]+1.75, 0.5))
m_box.set_x(pos_var[i]+1)
return (line1, line2, line3, m_text, m_box, b_line, k_line,)
anim = animation.FuncAnimation(anim_fig, animate, init_func=anim_init,
frames=frame_count, interval=10, blit=True,
repeat=True)
# Controllers
T_slider = w.FloatLogSlider(value=10, base=10, min=-0.7, max=1, step=0.01,
description='Duration [s]:', continuous_update=False,
orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto'))
dt_slider = w.FloatLogSlider(value=0.1, base=10, min=-3, max=-1, step=0.01,
description='Timestep [s]:', continuous_update=False,
orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto'))
X_type = w.Dropdown(options=[('Constant', 0), ('Sine', 1), ('Square', 2)], value=1,
description='Reference: ', continuous_update=False, layout=w.Layout(width='auto', flex='3 3 auto'))
Xf_slider = w.FloatLogSlider(value=0.5, base=10, min=-2, max=2, step=0.01,
description='Frequency [Hz]:', continuous_update=False,
orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto'))
Xa_slider = w.FloatLogSlider(value=1, base=10, min=-2, max=2, step=0.01,
description='Amplitude [m]:', continuous_update=False,
orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto'))
Xo_slider = w.FloatSlider(value=0, min=-10, max=10, description='Offset/Ampl:', continuous_update=False,
orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto'))
L_type = w.Dropdown(options=[('Constant', 0), ('Sine', 1), ('Square', 2), ('Noise', 3)], value=2,
description='Load: ', continuous_update=False, layout=w.Layout(width='auto', flex='3 3 auto'))
Lf_slider = w.FloatLogSlider(value=1, base=10, min=-2, max=2, step=0.01,
description='Frequency [Hz]:', continuous_update=False,
orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto'))
La_slider = w.FloatLogSlider(value=0.1, base=10, min=-2, max=2, step=0.01,
description='Amplitude [N]:', continuous_update=False,
orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto'))
Lo_slider = w.FloatSlider(value=0, min=-10, max=10, description='Offset/Ampl:', continuous_update=False,
orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto'))
input_data = w.interactive_output(simulation, {'Kp': Kp_slider, 'Ti': Ti_slider, 'Td': Td_slider,
'Fd': Fd_slider, 'Ti0' : Ti_button, 'Td0': Td_button,
'Fd0': Fd_button,
'm':m_slider, 'k':k_slider, 'b':b_slider,
'T': T_slider, 'dt': dt_slider,
'X': X_type, 'Xf': Xf_slider, 'Xa': Xa_slider, 'Xo': Xo_slider,
'L': L_type, 'Lf': Lf_slider, 'La': La_slider, 'Lo': Lo_slider})
display(w.HBox([w.HBox([T_slider, dt_slider], layout=w.Layout(width='25%')),
w.Box([], layout=w.Layout(width='5%')),
w.VBox([X_type, w.HBox([Xf_slider, Xa_slider, Xo_slider])], layout=w.Layout(width='30%')),
w.Box([], layout=w.Layout(width='5%')),
w.VBox([L_type, w.HBox([Lf_slider, La_slider, Lo_slider])], layout=w.Layout(width='30%'))],
layout=w.Layout(width='100%', justify_content='center')), input_data)
```
The duration parameter controls the simulated timeframe and does not affect the runtime of the animation. In contrast, the timestep controls the model sampling and can refine the results in exchange for higher computational resources.
| github_jupyter |
```
import pickle
import datetime as dt
import matplotlib.pyplot as plt
from flowmeterAnalysis import readFiles
homeDir = 'P:\\PW-WATER SERVICES\\TECHNICAL SERVICES\\Anna'
pickleLocation = homeDir + '\\2018\\Python Objects\\'
with open(pickleLocation + 'flowDict.pickle', 'rb') as handle:
flowDict = pickle.load(handle)
fmname = 'BC32'
#[dt.datetime(2018,1,1):dt.datetime(2018,2,1)]
Q = readFiles.reorganizeByTime(
df = flowDict[fmname],
colVal = 'Q (MGD)')
import matplotlib
font = {'family' : 'DejaVu Sans',
'weight' : 'normal',
'size' : 11}
matplotlib.rc('font', **font)
colors = {1: 'xkcd:windows blue',
2: 'xkcd:perrywinkle',
3: 'xkcd:pale olive',
4: 'xkcd:faded green',
5: 'xkcd:saffron',
6: 'xkcd:faded orange',
7: 'xkcd:yellow ochre',
8: 'xkcd:brown orange',
9: 'xkcd:greyish pink',
10: 'xkcd:rose red',
11: 'xkcd:purple red',
12: 'xkcd:dusty purple'}
import pandas as pd
datecols = pd.to_datetime(Q.columns)
fig,ax = plt.subplots(figsize = (12, 12/1.68))
ax.fill_between(range(1,len(Q.columns) + 1),
Q.min(),
Q.max(),
alpha = 0.5,
facecolor='xkcd:light grey')
ax.plot(range(1,len(Q.columns) + 1),
Q.median(),
linewidth = 0.75,
color = 'xkcd:grey')
prevLim = 0
monthList = list(set(pd.to_datetime(Q.columns).month))
labels = []
labelColor = []
newlabels = []
for month in monthList:
q = Q.loc[:,datecols.month == month]
ax.plot(range(prevLim + 1,prevLim + len(q.columns) + 1),
q.median().values,
linewidth = 0,
marker = '.',
markersize = 6,
color = colors[month])
prevLim += q.columns[-1].day
# create labels
newlabels.append(datecols[datecols.month == month]
.day[datecols[datecols.month == month]
.dayofweek == 0])
labels.extend(newlabels[-1])
#for monthLabels in newlabels:
# for idx, day in enumerate(newlabels[-1]):
# plt.gca().get_xticklabels()[idx].set_color(colors[month])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_color('xkcd:grey')
ax.spines['left'].set_color('xkcd:grey')
yticks = [Q.min().min(),
Q.quantile(0.25).mean(),
Q.mean().mean(),
Q.median().mean(),
Q.quantile(0.75).mean(),
Q.max().max()]
plt.yticks(ticks = yticks,
color = 'xkcd:dark grey')
plt.xticks(
ticks = range(1,len(Q.columns) + 1,7),
labels = labels)
ax.set_xlabel('Day of Month')
ax.set_ylabel('Gross Q (MGD)')
ax.set_title(fmname)
startIdx = 0
for month, monthLabels in zip(monthList, newlabels):
for idx in range(startIdx, startIdx + len(monthLabels)):
plt.gca().get_xticklabels()[idx].set_color(colors[month])
startIdx += len(monthLabels)
plt.tight_layout()
plt.savefig('H:\\Weather Reports\\grossQ_2018_' + fmname + '.png')
font = {'family' : 'DejaVu Sans',
'weight' : 'normal',
'size' : 9}
matplotlib.rc('font', **font)
rain = [0.84, 4.20, 3.26, 15.82]
color = ['#afc9e5','xkcd:grey','xkcd:windows blue','#afc9e5']
month = 1
fig, ax = plt.subplots(figsize = (2,2))
ax.bar(x = range(1,len(rain)+1),
height = rain,
color = color)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_color('xkcd:grey')
ax.spines['left'].set_visible(False)
plt.xticks(ticks = range(1,len(rain)+1),
labels = [])
plt.yticks(rain)
ax.yaxis.grid(True,
color='white',
linewidth = 1)
for idx, rainTotal in enumerate(rain):
plt.gca().get_yticklabels()[idx].set_color(color[idx])
plt.tight_layout()
font = {'family' : 'DejaVu Sans',
'weight' : 'normal',
'size' : 22}
color = {
1 : ['#afc9e5','xkcd:grey','xkcd:windows blue','#afc9e5'],
2 : ['#d2d1f5','xkcd:grey','xkcd:perrywinkle','#d2d1f5'],
3 : ['#e3eacc','xkcd:grey','xkcd:pale olive','#e3eacc'],
4 : ['#cae0c7','xkcd:grey','xkcd:faded green','#cae0c7'],
5 : ['#fee09c','xkcd:grey','xkcd:saffron','#fee09c'],
6 : ['#f9d4b7','xkcd:grey','xkcd:faded orange','#f9d4b7'],
7 : ['#ead79b','xkcd:grey','xkcd:yellow ochre','#ead79b'],
8 : ['#e3c399','xkcd:grey','xkcd:brown orange','#e3c399'],
9 : ['#e9d1d4','xkcd:grey','xkcd:greyish pink','#e9d1d4'],
10 : ['#e599b1','xkcd:grey','xkcd:rose red','#e599b1'],
11 : ['#d699b5','xkcd:grey','xkcd:purple red','#d699b5'],
12 : ['#d3bfcf','xkcd:grey','xkcd:dusty purple','#d3bfcf']
}
# YEAR 2018
# could just leave min, max, and normal and INSERT list.insert(num,pos) the actual rain total?
# should I also add the 24-hr max?...no?
rain = {
1 : [0.84, 4.20, 3.26, 15.82],
2 : [0.84, 4.67, 6.11, 15.82],
3 : [0.88, 4.81, 4.86, 13.28],
4 : [0.35, 3.36, 6.53, 11.86],
5 : [0.30, 3.67, 4.45, 9.94],
6 : [0.16, 3.95, 3.86, 11.21],
7 : [0.56, 5.27, 8.04, 17.71],
8 : [0.02, 3.90, 7.59, 10.02],
9 : [0.04, 4.47, 1.48, 14.26],
10 : [0.00, 3.41, 4.75, 11.04],
11 : [0.18, 4.1, 7.27, 15.72],
12 : [0.60, 3.9, 11.83, 12.94],
}
fig, ax = plt.subplots(
nrows = 1,
ncols = 12,
figsize = (12,2),
sharey = True)
for idx, month in enumerate(rain):
ax[idx].bar(x = range(1,len(rain[month])+1),
height = rain[month],
color = color[month])
ax[idx].spines['top'].set_visible(False)
ax[idx].spines['right'].set_visible(False)
ax[idx].spines['bottom'].set_color('xkcd:grey')
ax[idx].spines['left'].set_visible(False)
for rainVal in rain[month]:
ax[idx].plot(
[1,len(rain[month])+1],
[rainVal, rainVal],
color = 'white',
linewidth = 1)
plt.sca(ax[idx])
plt.xticks(ticks = range(1,len(rain[month])+1),
labels = ['m','N','T','M'])
ax[0].set_ylabel('Rain (in)')
plt.yticks(
ticks = [0,5,10,15],
color = 'xkcd:grey')
plt.tight_layout()
plt.savefig('H:\\Weather Reports\\rainbar.png')
```
| github_jupyter |
# TensorFlow Tutorial #01
# Simple Linear Model
by [Magnus Erik Hvass Pedersen](http://www.hvass-labs.org/)
/ [GitHub](https://github.com/Hvass-Labs/TensorFlow-Tutorials) / [Videos on YouTube](https://www.youtube.com/playlist?list=PL9Hr9sNUjfsmEu1ZniY0XpHSzl5uihcXZ)
## Introduction
This tutorial demonstrates the basic workflow of using TensorFlow with a simple linear model. After loading the so-called MNIST data-set with images of hand-written digits, we define and optimize a simple mathematical model in TensorFlow. The results are then plotted and discussed.
You should be familiar with basic linear algebra, Python and the Jupyter Notebook editor. It also helps if you have a basic understanding of Machine Learning and classification.
## Imports
```
%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
```
This was developed using Python 3.6.1 (Anaconda) and TensorFlow version:
```
tf.__version__
np.__version__
```
## Load Data
The MNIST data-set is about 12 MB and will be downloaded automatically if it is not located in the given path.
```
from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets("data/MNIST/", one_hot=True)
```
The MNIST data-set has now been loaded and consists of 70.000 images and associated labels (i.e. classifications of the images). The data-set is split into 3 mutually exclusive sub-sets. We will only use the training and test-sets in this tutorial.
```
print("Size of:")
print("- Training-set:\t\t{}".format(len(data.train.labels)))
print("- Test-set:\t\t{}".format(len(data.test.labels)))
print("- Validation-set:\t{}".format(len(data.validation.labels)))
```
### One-Hot Encoding
The data-set has been loaded as so-called One-Hot encoding. This means the labels have been converted from a single number to a vector whose length equals the number of possible classes. All elements of the vector are zero except for the $i$'th element which is one and means the class is $i$. For example, the One-Hot encoded labels for the first 5 images in the test-set are:
```
data.test.labels[0:5, :]
```
We also need the classes as single numbers for various comparisons and performance measures, so we convert the One-Hot encoded vectors to a single number by taking the index of the highest element. Note that the word 'class' is a keyword used in Python so we need to use the name 'cls' instead.
```
data.test.cls = np.array([label.argmax() for label in data.test.labels])
```
We can now see the class for the first five images in the test-set. Compare these to the One-Hot encoded vectors above. For example, the class for the first image is 7, which corresponds to a One-Hot encoded vector where all elements are zero except for the element with index 7.
```
data.test.cls[0:5]
```
### Data dimensions
The data dimensions are used in several places in the source-code below. In computer programming it is generally best to use variables and constants rather than having to hard-code specific numbers every time that number is used. This means the numbers only have to be changed in one single place. Ideally these would be inferred from the data that has been read, but here we just write the numbers.
```
# We know that MNIST images are 28 pixels in each dimension.
img_size = 28
# Images are stored in one-dimensional arrays of this length.
img_size_flat = img_size * img_size
# Tuple with height and width of images used to reshape arrays.
img_shape = (img_size, img_size)
# Number of classes, one class for each of 10 digits.
num_classes = 10
img_shape
```
### Helper-function for plotting images
Function used to plot 9 images in a 3x3 grid, and writing the true and predicted classes below each image.
```
def plot_images(images, cls_true, cls_pred=None):
assert len(images) == len(cls_true) == 9
# Create figure with 3x3 sub-plots.
fig, axes = plt.subplots(3, 3)
fig.subplots_adjust(hspace=0.3, wspace=0.3)
for i, ax in enumerate(axes.flat):
# Plot image.
ax.imshow(images[i].reshape(img_shape), cmap='binary')
# Show true and predicted classes.
if cls_pred is None:
xlabel = "True: {0}".format(cls_true[i])
else:
xlabel = "True: {0}, Pred: {1}".format(cls_true[i], cls_pred[i])
ax.set_xlabel(xlabel)
# Remove ticks from the plot.
ax.set_xticks([])
ax.set_yticks([])
# Ensure the plot is shown correctly with multiple plots
# in a single Notebook cell.
plt.show()
```
### Plot a few images to see if data is correct
```
# Get the first images from the test-set.
images = data.test.images[0:9]
# Get the true classes for those images.
cls_true = data.test.cls[0:9]
# Plot the images and labels using our helper-function above.
plot_images(images=images, cls_true=cls_true)
```
## TensorFlow Graph
The entire purpose of TensorFlow is to have a so-called computational graph that can be executed much more efficiently than if the same calculations were to be performed directly in Python. TensorFlow can be more efficient than NumPy because TensorFlow knows the entire computation graph that must be executed, while NumPy only knows the computation of a single mathematical operation at a time.
TensorFlow can also automatically calculate the gradients that are needed to optimize the variables of the graph so as to make the model perform better. This is because the graph is a combination of simple mathematical expressions so the gradient of the entire graph can be calculated using the chain-rule for derivatives.
TensorFlow can also take advantage of multi-core CPUs as well as GPUs - and Google has even built special chips just for TensorFlow which are called TPUs (Tensor Processing Units) and are even faster than GPUs.
A TensorFlow graph consists of the following parts which will be detailed below:
* Placeholder variables used to change the input to the graph.
* Model variables that are going to be optimized so as to make the model perform better.
* The model which is essentially just a mathematical function that calculates some output given the input in the placeholder variables and the model variables.
* A cost measure that can be used to guide the optimization of the variables.
* An optimization method which updates the variables of the model.
In addition, the TensorFlow graph may also contain various debugging statements e.g. for logging data to be displayed using TensorBoard, which is not covered in this tutorial.
### Placeholder variables
Placeholder variables serve as the input to the graph that we may change each time we execute the graph. We call this feeding the placeholder variables and it is demonstrated further below.
First we define the placeholder variable for the input images. This allows us to change the images that are input to the TensorFlow graph. This is a so-called tensor, which just means that it is a multi-dimensional vector or matrix. The data-type is set to `float32` and the shape is set to `[None, img_size_flat]`, where `None` means that the tensor may hold an arbitrary number of images with each image being a vector of length `img_size_flat`.
```
x = tf.placeholder(tf.float32, [None, img_size_flat])
img_size_flat
```
Next we have the placeholder variable for the true labels associated with the images that were input in the placeholder variable `x`. The shape of this placeholder variable is `[None, num_classes]` which means it may hold an arbitrary number of labels and each label is a vector of length `num_classes` which is 10 in this case.
```
y_true = tf.placeholder(tf.float32, [None, num_classes])
```
Finally we have the placeholder variable for the true class of each image in the placeholder variable `x`. These are integers and the dimensionality of this placeholder variable is set to `[None]` which means the placeholder variable is a one-dimensional vector of arbitrary length.
```
y_true_cls = tf.placeholder(tf.int64, [None])
```
### Variables to be optimized
Apart from the placeholder variables that were defined above and which serve as feeding input data into the model, there are also some model variables that must be changed by TensorFlow so as to make the model perform better on the training data.
The first variable that must be optimized is called `weights` and is defined here as a TensorFlow variable that must be initialized with zeros and whose shape is `[img_size_flat, num_classes]`, so it is a 2-dimensional tensor (or matrix) with `img_size_flat` rows and `num_classes` columns.
```
weights = tf.Variable(tf.zeros([img_size_flat, num_classes]))
```
The second variable that must be optimized is called `biases` and is defined as a 1-dimensional tensor (or vector) of length `num_classes`.
```
biases = tf.Variable(tf.zeros([num_classes]))
```
### Model
This simple mathematical model multiplies the images in the placeholder variable `x` with the `weights` and then adds the `biases`.
The result is a matrix of shape `[num_images, num_classes]` because `x` has shape `[num_images, img_size_flat]` and `weights` has shape `[img_size_flat, num_classes]`, so the multiplication of those two matrices is a matrix with shape `[num_images, num_classes]` and then the `biases` vector is added to each row of that matrix.
Note that the name `logits` is typical TensorFlow terminology, but other people may call the variable something else.
```
logits = tf.matmul(x, weights) + biases
```
Now `logits` is a matrix with `num_images` rows and `num_classes` columns, where the element of the $i$'th row and $j$'th column is an estimate of how likely the $i$'th input image is to be of the $j$'th class.
However, these estimates are a bit rough and difficult to interpret because the numbers may be very small or large, so we want to normalize them so that each row of the `logits` matrix sums to one, and each element is limited between zero and one. This is calculated using the so-called softmax function and the result is stored in `y_pred`.
```
y_pred = tf.nn.softmax(logits)
```
The predicted class can be calculated from the `y_pred` matrix by taking the index of the largest element in each row.
```
y_pred_cls = tf.argmax(y_pred, axis=1)
```
### Cost-function to be optimized
To make the model better at classifying the input images, we must somehow change the variables for `weights` and `biases`. To do this we first need to know how well the model currently performs by comparing the predicted output of the model `y_pred` to the desired output `y_true`.
The cross-entropy is a performance measure used in classification. The cross-entropy is a continuous function that is always positive and if the predicted output of the model exactly matches the desired output then the cross-entropy equals zero. The goal of optimization is therefore to minimize the cross-entropy so it gets as close to zero as possible by changing the `weights` and `biases` of the model.
TensorFlow has a built-in function for calculating the cross-entropy. Note that it uses the values of the `logits` because it also calculates the softmax internally.
```
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,
labels=y_true)
```
We have now calculated the cross-entropy for each of the image classifications so we have a measure of how well the model performs on each image individually. But in order to use the cross-entropy to guide the optimization of the model's variables we need a single scalar value, so we simply take the average of the cross-entropy for all the image classifications.
```
cost = tf.reduce_mean(cross_entropy)
```
### Optimization method
Now that we have a cost measure that must be minimized, we can then create an optimizer. In this case it is the basic form of Gradient Descent where the step-size is set to 0.5.
Note that optimization is not performed at this point. In fact, nothing is calculated at all, we just add the optimizer-object to the TensorFlow graph for later execution.
```
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(cost)
```
### Performance measures
We need a few more performance measures to display the progress to the user.
This is a vector of booleans whether the predicted class equals the true class of each image.
```
correct_prediction = tf.equal(y_pred_cls, y_true_cls)
```
This calculates the classification accuracy by first type-casting the vector of booleans to floats, so that False becomes 0 and True becomes 1, and then calculating the average of these numbers.
```
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
```
## TensorFlow Run
### Create TensorFlow session
Once the TensorFlow graph has been created, we have to create a TensorFlow session which is used to execute the graph.
```
session = tf.Session()
```
### Initialize variables
The variables for `weights` and `biases` must be initialized before we start optimizing them.
```
session.run(tf.global_variables_initializer())
```
### Helper-function to perform optimization iterations
There are 50.000 images in the training-set. It takes a long time to calculate the gradient of the model using all these images. We therefore use Stochastic Gradient Descent which only uses a small batch of images in each iteration of the optimizer.
```
batch_size = 100
```
Function for performing a number of optimization iterations so as to gradually improve the `weights` and `biases` of the model. In each iteration, a new batch of data is selected from the training-set and then TensorFlow executes the optimizer using those training samples.
```
def optimize(num_iterations):
for i in range(num_iterations):
# Get a batch of training examples.
# x_batch now holds a batch of images and
# y_true_batch are the true labels for those images.
x_batch, y_true_batch = data.train.next_batch(batch_size)
# Put the batch into a dict with the proper names
# for placeholder variables in the TensorFlow graph.
# Note that the placeholder for y_true_cls is not set
# because it is not used during training.
feed_dict_train = {x: x_batch,
y_true: y_true_batch}
# Run the optimizer using this batch of training data.
# TensorFlow assigns the variables in feed_dict_train
# to the placeholder variables and then runs the optimizer.
session.run(optimizer, feed_dict=feed_dict_train)
```
### Helper-functions to show performance
Dict with the test-set data to be used as input to the TensorFlow graph. Note that we must use the correct names for the placeholder variables in the TensorFlow graph.
```
feed_dict_test = {x: data.test.images,
y_true: data.test.labels,
y_true_cls: data.test.cls}
```
Function for printing the classification accuracy on the test-set.
```
def print_accuracy():
# Use TensorFlow to compute the accuracy.
acc = session.run(accuracy, feed_dict=feed_dict_test)
# Print the accuracy.
print("Accuracy on test-set: {0:.1%}".format(acc))
```
Function for printing and plotting the confusion matrix using scikit-learn.
```
def print_confusion_matrix():
# Get the true classifications for the test-set.
cls_true = data.test.cls
# Get the predicted classifications for the test-set.
cls_pred = session.run(y_pred_cls, feed_dict=feed_dict_test)
# Get the confusion matrix using sklearn.
cm = confusion_matrix(y_true=cls_true,
y_pred=cls_pred)
# Print the confusion matrix as text.
print(cm)
# Plot the confusion matrix as an image.
plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
# Make various adjustments to the plot.
plt.tight_layout()
plt.colorbar()
tick_marks = np.arange(num_classes)
plt.xticks(tick_marks, range(num_classes))
plt.yticks(tick_marks, range(num_classes))
plt.xlabel('Predicted')
plt.ylabel('True')
# Ensure the plot is shown correctly with multiple plots
# in a single Notebook cell.
plt.show()
```
Function for plotting examples of images from the test-set that have been mis-classified.
```
def plot_example_errors():
# Use TensorFlow to get a list of boolean values
# whether each test-image has been correctly classified,
# and a list for the predicted class of each image.
correct, cls_pred = session.run([correct_prediction, y_pred_cls],
feed_dict=feed_dict_test)
# Negate the boolean array.
incorrect = (correct == False)
# Get the images from the test-set that have been
# incorrectly classified.
images = data.test.images[incorrect]
# Get the predicted classes for those images.
cls_pred = cls_pred[incorrect]
# Get the true classes for those images.
cls_true = data.test.cls[incorrect]
# Plot the first 9 images.
plot_images(images=images[0:9],
cls_true=cls_true[0:9],
cls_pred=cls_pred[0:9])
```
### Helper-function to plot the model weights
Function for plotting the `weights` of the model. 10 images are plotted, one for each digit that the model is trained to recognize.
```
def plot_weights():
# Get the values for the weights from the TensorFlow variable.
w = session.run(weights)
# Get the lowest and highest values for the weights.
# This is used to correct the colour intensity across
# the images so they can be compared with each other.
w_min = np.min(w)
w_max = np.max(w)
# Create figure with 3x4 sub-plots,
# where the last 2 sub-plots are unused.
fig, axes = plt.subplots(3, 4)
fig.subplots_adjust(hspace=0.3, wspace=0.3)
for i, ax in enumerate(axes.flat):
# Only use the weights for the first 10 sub-plots.
if i<10:
# Get the weights for the i'th digit and reshape it.
# Note that w.shape == (img_size_flat, 10)
image = w[:, i].reshape(img_shape)
# Set the label for the sub-plot.
ax.set_xlabel("Weights: {0}".format(i))
# Plot the image.
ax.imshow(image, vmin=w_min, vmax=w_max, cmap='seismic')
# Remove ticks from each sub-plot.
ax.set_xticks([])
ax.set_yticks([])
# Ensure the plot is shown correctly with multiple plots
# in a single Notebook cell.
plt.show()
```
## Performance before any optimization
The accuracy on the test-set is 9.8%. This is because the model has only been initialized and not optimized at all, so it always predicts that the image shows a zero digit, as demonstrated in the plot below, and it turns out that 9.8% of the images in the test-set happens to be zero digits.
```
print_accuracy()
plot_example_errors()
```
## Performance after 1 optimization iteration
Already after a single optimization iteration, the model has increased its accuracy on the test-set to 40.7% up from 9.8%. This means that it mis-classifies the images about 6 out of 10 times, as demonstrated on a few examples below.
```
optimize(num_iterations=1)
print_accuracy()
plot_example_errors()
```
The weights can also be plotted as shown below. Positive weights are red and negative weights are blue. These weights can be intuitively understood as image-filters.
For example, the weights used to determine if an image shows a zero-digit have a positive reaction (red) to an image of a circle, and have a negative reaction (blue) to images with content in the centre of the circle.
Similarly, the weights used to determine if an image shows a one-digit react positively (red) to a vertical line in the centre of the image, and react negatively (blue) to images with content surrounding that line.
Note that the weights mostly look like the digits they're supposed to recognize. This is because only one optimization iteration has been performed so the weights are only trained on 100 images. After training on several thousand images, the weights become more difficult to interpret because they have to recognize many variations of how digits can be written.
```
plot_weights()
```
## Performance after 10 optimization iterations
```
# We have already performed 1 iteration.
optimize(num_iterations=9)
print_accuracy()
plot_example_errors()
plot_weights()
```
## Performance after 1000 optimization iterations
After 1000 optimization iterations, the model only mis-classifies about one in ten images. As demonstrated below, some of the mis-classifications are justified because the images are very hard to determine with certainty even for humans, while others are quite obvious and should have been classified correctly by a good model. But this simple model cannot reach much better performance and more complex models are therefore needed.
```
# We have already performed 10 iterations.
optimize(num_iterations=990)
print_accuracy()
plot_example_errors()
```
The model has now been trained for 1000 optimization iterations, with each iteration using 100 images from the training-set. Because of the great variety of the images, the weights have now become difficult to interpret and we may doubt whether the model truly understands how digits are composed from lines, or whether the model has just memorized many different variations of pixels.
```
plot_weights()
```
We can also print and plot the so-called confusion matrix which lets us see more details about the mis-classifications. For example, it shows that images actually depicting a 5 have sometimes been mis-classified as all other possible digits, but mostly either 3, 6 or 8.
```
print_confusion_matrix()
```
We are now done using TensorFlow, so we close the session to release its resources.
```
# This has been commented out in case you want to modify and experiment
# with the Notebook without having to restart it.
# session.close()
```
## Exercises
These are a few suggestions for exercises that may help improve your skills with TensorFlow. It is important to get hands-on experience with TensorFlow in order to learn how to use it properly.
You may want to backup this Notebook before making any changes.
* Change the learning-rate for the optimizer.
* Change the optimizer to e.g. `AdagradOptimizer` or `AdamOptimizer`.
* Change the batch-size to e.g. 1 or 1000.
* How do these changes affect the performance?
* Do you think these changes will have the same effect (if any) on other classification problems and mathematical models?
* Do you get the exact same results if you run the Notebook multiple times without changing any parameters? Why or why not?
* Change the function `plot_example_errors()` so it also prints the `logits` and `y_pred` values for the mis-classified examples.
* Use `sparse_softmax_cross_entropy_with_logits` instead of `softmax_cross_entropy_with_logits`. This may require several changes to multiple places in the source-code. Discuss the advantages and disadvantages of using the two methods.
* Remake the program yourself without looking too much at this source-code.
* Explain to a friend how the program works.
## License (MIT)
Copyright (c) 2016 by [Magnus Erik Hvass Pedersen](http://www.hvass-labs.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| github_jupyter |
<a href="https://colab.research.google.com/github/kartikgill/The-GAN-Book/blob/main/Skill-07/W-GAN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Importing useful Libraries
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook
%matplotlib inline
import tensorflow
print (tensorflow.__version__)
```
# Download and show data
```
from tensorflow.keras.datasets import fashion_mnist, mnist
(trainX, trainY), (testX, testY) = mnist.load_data()
print('Training data shapes: X=%s, y=%s' % (trainX.shape, trainY.shape))
print('Testing data shapes: X=%s, y=%s' % (testX.shape, testY.shape))
for k in range(9):
plt.figure(figsize=(9, 6))
for j in range(9):
i = np.random.randint(0, 10000)
plt.subplot(990 + 1 + j)
plt.imshow(trainX[i], cmap='gray_r')
#plt.title(trainY[i])
plt.axis('off')
plt.show()
#Ten classes
set(trainY)
```
# Data Normalization
```
trainX = [(image-127.5)/127.5 for image in trainX]
testX = [(image-127.5)/127.5 for image in testX]
trainX = np.reshape(trainX, (60000, 28, 28, 1))
testX = np.reshape(testX, (10000, 28, 28, 1))
print (trainX.shape, testX.shape, trainY.shape, testY.shape)
```
# Define Generator Model
```
random_input = tensorflow.keras.layers.Input(shape = 100)
x = tensorflow.keras.layers.Dense(7*7*128)(random_input)
x = tensorflow.keras.layers.Reshape((7, 7, 128))(x)
x = tensorflow.keras.layers.Conv2DTranspose(filters=128, kernel_size=(3,3), strides=2, padding='same')(x)
x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x)
x = tensorflow.keras.layers.Activation('relu')(x)
x = tensorflow.keras.layers.Conv2DTranspose(filters=128, kernel_size=(3,3), strides=2, padding='same')(x)
x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x)
x = tensorflow.keras.layers.Activation('relu')(x)
x = tensorflow.keras.layers.Conv2DTranspose(filters=128, kernel_size=(3,3), padding='same')(x)
x = tensorflow.keras.layers.Activation('relu')(x)
x = tensorflow.keras.layers.Conv2DTranspose(filters=1, kernel_size=(4,4), padding='same')(x)
generated_image = tensorflow.keras.layers.Activation('tanh')(x)
generator_network = tensorflow.keras.models.Model(inputs=random_input, outputs=generated_image)
generator_network.summary()
```
# Define Critic
```
image_input = tensorflow.keras.layers.Input(shape=(28, 28, 1))
x = tensorflow.keras.layers.Conv2D(filters=64, kernel_size=(3,3), strides=2, padding='same')(image_input)
x = tensorflow.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tensorflow.keras.layers.Dropout(0.25)(x)
x = tensorflow.keras.layers.Conv2D(filters=128, kernel_size=(3,3), strides=2, padding='same')(x)
x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x)
x = tensorflow.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tensorflow.keras.layers.Dropout(0.25)(x)
x = tensorflow.keras.layers.Conv2D(filters=128, kernel_size=(3,3), strides=2, padding='same')(x)
x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x)
x = tensorflow.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tensorflow.keras.layers.Dropout(0.25)(x)
x = tensorflow.keras.layers.Conv2D(filters=256, kernel_size=(3,3), padding='same')(x)
x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x)
x = tensorflow.keras.layers.LeakyReLU(alpha=0.2)(x)
x = tensorflow.keras.layers.Dropout(0.25)(x)
x = tensorflow.keras.layers.Flatten()(x)
# No activation in final layer
c_out = tensorflow.keras.layers.Dense(1)(x)
critic_network = tensorflow.keras.models.Model(inputs=image_input, outputs=c_out)
print (critic_network.summary())
```
# Define Wasserstein Loss
```
# custom loss function
def wasserstein_loss(y_true, y_pred):
return tensorflow.keras.backend.mean(y_true * y_pred)
```
# Compiling Critic Network
```
RMSprop_optimizer = tensorflow.keras.optimizers.RMSprop(lr=0.00005)
critic_network.compile(loss=wasserstein_loss, optimizer=RMSprop_optimizer, metrics=['accuracy'])
```
# Define Wasserstein GAN (W-GAN)
```
critic_network.trainable=False
g_output = generator_network(random_input)
c_output = critic_network(g_output)
wgan_model = tensorflow.keras.models.Model(inputs = random_input, outputs = c_output)
wgan_model.summary()
```
# Compiling WGAN
```
wgan_model.compile(loss=wasserstein_loss, optimizer=RMSprop_optimizer)
```
# Define Data Generators
```
indices = [i for i in range(0, len(trainX))]
def get_random_noise(batch_size, noise_size):
random_values = np.random.randn(batch_size*noise_size)
random_noise_batches = np.reshape(random_values, (batch_size, noise_size))
return random_noise_batches
def get_fake_samples(generator_network, batch_size, noise_size):
random_noise_batches = get_random_noise(batch_size, noise_size)
fake_samples = generator_network.predict_on_batch(random_noise_batches)
return fake_samples
def get_real_samples(batch_size):
random_indices = np.random.choice(indices, size=batch_size)
real_images = trainX[np.array(random_indices),:]
return real_images
def show_generator_results(generator_network):
for k in range(7):
plt.figure(figsize=(9, 6))
random_noise_batches = get_random_noise(7, noise_size)
fake_samples = generator_network.predict_on_batch(random_noise_batches)
for j in range(7):
i = j
plt.subplot(770 + 1 + j)
plt.imshow(((fake_samples[i,:,:,-1])/2.0)+0.5, cmap='gray_r')
plt.axis('off')
plt.show()
return
```
# Training W-GAN
```
epochs = 500
batch_size = 64
steps = 500
noise_size = 100
for i in range(0, epochs):
if (i%1 == 0):
op = show_generator_results(generator_network)
#print (op)
for j in range(steps):
# With Number of Critics=5
for _ in range(5):
fake_samples = get_fake_samples(generator_network, batch_size//2, noise_size)
real_samples = get_real_samples(batch_size=batch_size//2)
fake_y = np.ones((batch_size//2, 1))
real_y = -1 * np.ones((batch_size//2, 1))
# Updating Critic weights
critic_network.trainable=True
loss_c_real = critic_network.train_on_batch(real_samples, real_y)
loss_c_fake = critic_network.train_on_batch(fake_samples, fake_y)
loss_c = np.add(loss_c_real, loss_c_fake)/2.0
# Clip critic weights
for l in critic_network.layers:
weights = l.get_weights()
weights = [np.clip(w, -0.01, 0.01) for w in weights]
l.set_weights(weights)
if False:
print ("C_real_loss: %.3f, C_fake_loss: %.3f, C_loss: %.3f"%(loss_c_real[0], loss_c_fake[0], loss_c[0]))
noise_batches = get_random_noise(batch_size, noise_size)
wgan_input = noise_batches
# Make the Discriminator belive that these are real samples and calculate loss to train the generator
wgan_output = -1 * np.ones((batch_size, 1))
# Updating Generator weights
critic_network.trainable=False
loss_g = wgan_model.train_on_batch(wgan_input, wgan_output)
if j%50 == 0:
print ("Epoch:%.0f, Step:%.0f, C-Loss:%.6f, G-Loss:%.6f"%(i,j,loss_c[0] ,loss_g))
```
# Results
```
for i in range(2):
show_generator_results(generator_network)
print("-"*100)
```
| github_jupyter |
# Dummy Variables Exercise
In this exercise, you'll create dummy variables from the projects data set. The idea is to transform categorical data like this:
| Project ID | Project Category |
|------------|------------------|
| 0 | Energy |
| 1 | Transportation |
| 2 | Health |
| 3 | Employment |
into new features that look like this:
| Project ID | Energy | Transportation | Health | Employment |
|------------|--------|----------------|--------|------------|
| 0 | 1 | 0 | 0 | 0 |
| 1 | 0 | 1 | 0 | 0 |
| 2 | 0 | 0 | 1 | 0 |
| 3 | 0 | 0 | 0 | 1 |
(Note if you were going to use this data with a model influenced by multicollinearity, you would want to eliminate one of the columns to avoid redundant information.)
The reasoning behind these transformations is that machine learning algorithms read in numbers not text. Text needs to be converted into numbers. You could assign a number to each category like 1, 2, 3, and 4. But a categorical variable has no inherent order, so you want to reflect this in your features.
Pandas makes it very easy to create dummy variables with the [get_dummies](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html) method. In this exercise, you'll create dummy variables from the World Bank projects data; however, there's a caveat. The World Bank data is not particularly clean, so you'll need to explore and wrangle the data first.
You'll focus on the text values in the sector variables.
Run the code cells below to read in the World Bank projects data set and then to filter out the data for text variables.
# Check Category Data
```
import pandas as pd
import numpy as np
# read in the projects data set and do basic wrangling
projects = pd.read_csv('./data/projects_data.csv', dtype=str)
projects.drop('Unnamed: 56', axis=1, inplace=True)
projects['totalamt'] = pd.to_numeric(projects['totalamt'].str.replace(',', ''))
projects['countryname'] = projects['countryname'].str.split(';', expand=True)[0]
projects['boardapprovaldate'] = pd.to_datetime(projects['boardapprovaldate'])
# keep the project name, lending, sector and theme data
sector = projects.copy()
sector = sector[['project_name', 'lendinginstr', 'sector1', 'sector2', 'sector3', 'sector4', 'sector5', 'sector',
'mjsector1', 'mjsector2', 'mjsector3', 'mjsector4', 'mjsector5',
'mjsector', 'theme1', 'theme2', 'theme3', 'theme4', 'theme5', 'theme ',
'goal', 'financier', 'mjtheme1name', 'mjtheme2name', 'mjtheme3name',
'mjtheme4name', 'mjtheme5name']]
# output percentage of values that are missing
100 * sector.isnull().sum() / sector.shape[0]
uniquesectors1 = list(sector['sector1'].sort_values().unique())
uniquesectors1[0:10]
print('Number of unique values in sector1:', len(uniquesectors1))
```
# Clean Category Data
3060 different categories is quite a lot! Remember that with dummy variables, if you have n categorical values, you need n - 1 new variables! That means 3059 extra columns!
There are a few issues with this 'sector1' variable. First, there are values labeled '!$!0'. These should be substituted with NaN.
Furthermore, each sector1 value ends with a ten or eleven character string like '!$!49!$!EP'. Some sectors show up twice in the list like:
'Other Industry; Trade and Services!$!70!$!YZ',
'Other Industry; Trade and Services!$!63!$!YZ',
But it seems like those are actually the same sector. You'll need to remove everything past the exclamation point.
Many values in the sector1 variable start with the term '(Historic)'. Try removing that phrase as well.
### replace() method
With pandas, you can use the replace() method to search for text and replace parts of a string with another string. If you know the exact string you're looking for, the replace() method is straight forward. For example, say you wanted to remove the string '(Trial)' from this data:
| data |
|--------------------------|
| '(Trial) Banking' |
| 'Banking' |
| 'Farming' |
| '(Trial) Transportation' |
You could use `df['data'].replace('(Trial'), '')` to replace (Trial) with an empty string.
### regular expressions
What about this data?
| data |
|------------------------------------------------|
| 'Other Industry; Trade and Services?$ab' |
| 'Other Industry; Trade and Services?ceg' |
This type of data is trickier. In this case, there's a pattern where you want to remove a string that starts with an exclamation point and then has an unknown number of characters after it. When you need to match patterns of character, you can use [regular expressions](https://en.wikipedia.org/wiki/Regular_expression).
The replace method can take a regular expression. So
df['data'].replace('?.+', regex=True) where '?.+' means find a set of characters that starts with a question mark is then followed by one or more characters. You can see a [regular expression cheat sheet](https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285) here.
Fix these issues in the code cell below.
```
# TODO: In the sector1 variable, replace the string '!$10' with nan
# Put the results back into the sector1 variable
# HINT: you can use the pandas replace() method and numpy.nan
sector['sector1'] = sector['sector1'].replace('!$10', np.nan)
# TODO: In the sector1 variable, remove the last 10 or 11 characters from the sector1 variable.
# HINT: There is more than one way to do this. To do it with one line of code,
# you can use the replace method with a regex expression '!.+'
# That regex expression looks for a string with an exclamation
# point followed by one or more characters
sector['sector1'] = sector['sector1'].replace('!.+', '', regex=True)
# TODO: Remove the string '(Historic)' from the sector1 variable
# HINT: You can use the replace method
#sector['sector1'] = sector['sector1'].replace('(Historic)', '', regex=True)
sector['sector1'] = sector['sector1'].replace('^(\(Historic\))', '', regex=True)
print('Number of unique sectors after cleaning:', len(list(sector['sector1'].unique())))
print('Percentage of null values after cleaning:', 100 * sector['sector1'].isnull().sum() / sector['sector1'].shape[0])
```
Now there are 156 unique categorical values. That's better than 3060. If you were going to use this data with a supervised learning machine model, you could try converting these 156 values to dummy variables. You'd still have to train and test a model to see if those are good features.
You could try to consolidate similar categories together, which is what the challenge exercise in part 4 is about.
There are also still many entries with NaN values. How could you fill these in?
You might try to determine an appropriate category from the 'project_name' or 'lendinginstr' variables. If you make dummy variables including NaN values, then you could consider a feature with all zeros to represent NaN. Or you could delete these records from the data set. Pandas will ignore NaN values by default. That means, for a given row, all dummy variables will have a value of 0 if the sector1 value was NaN.
Don't forget about the bigger context! This data is being prepared for a machine learning algorithm. Whatever techniques you use to engineer new features, you'll need to use those when running your model on new data. So if your new data does not contain a sector1 value, you'll have to run whatever feature engineering processes you did on your training set.
# Get Dummies
In this next exercise, use the pandas pd.get_dummies() method to create dummy variables. Then use the concat() method to concatenate the dummy variables to a dataframe that contains the project totalamt variable and the project year from the boardapprovaldate.
```
# TODO: Create dummy variables from the sector1 data. Put the results into a dataframe called dummies
# Hint: Use the get_dummies method
dummies = pd.get_dummies(sector['sector1'])
# TODO: Create a new dataframe called df by
# filtering the projects data for the totalamt and
# the year from boardapprovaldate
projects['year'] = projects['boardapprovaldate'].dt.year
df = projects[['totalamt','year']]
# TODO: Concatenate the results of dummies and projects
# into a single data frame
df_final = pd.concat([df, dummies], axis=1)
df_final.head()
```
| github_jupyter |
<div class="alert alert-block alert-info" style="margin-top: 20px">
<a href="https://cocl.us/topNotebooksPython101Coursera">
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/TopAd.png" width="750" align="center">
</a>
</div>
<a href="https://cognitiveclass.ai/">
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/CCLog.png" width="200" align="center">
</a>
<h1>1D <code>Numpy</code> in Python</h1>
<p><strong>Welcome!</strong> This notebook will teach you about using <code>Numpy</code> in the Python Programming Language. By the end of this lab, you'll know what <code>Numpy</code> is and the <code>Numpy</code> operations.</p>
<h2>Table of Contents</h2>
<div class="alert alert-block alert-info" style="margin-top: 20px">
<ul>
<li><a href="pre">Preparation</a></li>
<li>
<a href="numpy">What is Numpy?</a>
<ul>
<li><a href="type">Type</a></li>
<li><a href="val">Assign Value</a></li>
<li><a href="slice">Slicing</a></li>
<li><a href="list">Assign Value with List</a></li>
<li><a href="other">Other Attributes</a></li>
</ul>
</li>
<li>
<a href="op">Numpy Array Operations</a>
<ul>
<li><a href="add">Array Addition</a></li>
<li><a href="multi">Array Multiplication</a></li>
<li><a href="prod">Product of Two Numpy Arrays</a></li>
<li><a href="dot">Dot Product</a></li>
<li><a href="cons">Adding Constant to a Numpy Array</a></li>
</ul>
</li>
<li><a href="math">Mathematical Functions</a></li>
<li><a href="lin">Linspace</a></li>
</ul>
<p>
Estimated time needed: <strong>30 min</strong>
</p>
</div>
<hr>
<h2 id="pre">Preparation</h2>
```
# Import the libraries
import time
import sys
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Plotting functions
def Plotvec1(u, z, v):
ax = plt.axes()
ax.arrow(0, 0, *u, head_width=0.05, color='r', head_length=0.1)
plt.text(*(u + 0.1), 'u')
ax.arrow(0, 0, *v, head_width=0.05, color='b', head_length=0.1)
plt.text(*(v + 0.1), 'v')
ax.arrow(0, 0, *z, head_width=0.05, head_length=0.1)
plt.text(*(z + 0.1), 'z')
plt.ylim(-2, 2)
plt.xlim(-2, 2)
def Plotvec2(a,b):
ax = plt.axes()
ax.arrow(0, 0, *a, head_width=0.05, color ='r', head_length=0.1)
plt.text(*(a + 0.1), 'a')
ax.arrow(0, 0, *b, head_width=0.05, color ='b', head_length=0.1)
plt.text(*(b + 0.1), 'b')
plt.ylim(-2, 2)
plt.xlim(-2, 2)
```
Create a Python List as follows:
```
# Create a python list
a = ["0", 1, "two", "3", 4]
```
We can access the data via an index:
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%205/Images/NumOneList.png" width="660" />
We can access each element using a square bracket as follows:
```
# Print each element
print("a[0]:", a[0])
print("a[1]:", a[1])
print("a[2]:", a[2])
print("a[3]:", a[3])
print("a[4]:", a[4])
```
<hr>
<h2 id="numpy">What is Numpy?</h2>
A numpy array is similar to a list. It's usually fixed in size and each element is of the same type. We can cast a list to a numpy array by first importing numpy:
```
# import numpy library
import numpy as np
```
We then cast the list as follows:
```
# Create a numpy array
a = np.array([0, 1, 2, 3, 4])
a
```
Each element is of the same type, in this case integers:
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%205/Images/NumOneNp.png" width="500" />
As with lists, we can access each element via a square bracket:
```
# Print each element
print("a[0]:", a[0])
print("a[1]:", a[1])
print("a[2]:", a[2])
print("a[3]:", a[3])
print("a[4]:", a[4])
```
<h3 id="type">Type</h3>
If we check the type of the array we get <b>numpy.ndarray</b>:
```
# Check the type of the array
other = np.array([[6,4,2],[7,6,3]])
type(other)
other.shape
```
As numpy arrays contain data of the same type, we can use the attribute "dtype" to obtain the Data-type of the array’s elements. In this case a 64-bit integer:
```
# Check the type of the values stored in numpy array
a.dtype
```
We can create a numpy array with real numbers:
```
# Create a numpy array
b = np.array([3.1, 11.02, 6.2, 213.2, 5.2])
```
When we check the type of the array we get <b>numpy.ndarray</b>:
```
# Check the type of array
type(b)
```
If we examine the attribute <code>dtype</code> we see float 64, as the elements are not integers:
```
# Check the value type
b.dtype
```
<h3 id="val">Assign value</h3>
We can change the value of the array, consider the array <code>c</code>:
```
# Create numpy array
c = np.array([20, 1, 2, 3, 4])
c
```
We can change the first element of the array to 100 as follows:
```
# Assign the first element to 100
c[0] = 100
c
```
We can change the 5th element of the array to 0 as follows:
```
# Assign the 5th element to 0
c[4] = 0
c
```
<h3 id="slice">Slicing</h3>
Like lists, we can slice the numpy array, and we can select the elements from 1 to 3 and assign it to a new numpy array <code>d</code> as follows:
```
# Slicing the numpy array
d = c[1:4]
d
```
We can assign the corresponding indexes to new values as follows:
```
# Set the fourth element and fifth element to 300 and 400
c[3:5] = 300, 400
c
```
<h3 id="list">Assign Value with List</h3>
Similarly, we can use a list to select a specific index.
The list ' select ' contains several values:
```
# Create the index list
select = [0, 2, 3]
```
We can use the list as an argument in the brackets. The output is the elements corresponding to the particular index:
```
# Use List to select elements
d = c[select]
type(d)
```
We can assign the specified elements to a new value. For example, we can assign the values to 100 000 as follows:
```
# Assign the specified elements to new value
c[select] = 100000
c
```
<h3 id="other">Other Attributes</h3>
Let's review some basic array attributes using the array <code>a</code>:
```
# Create a numpy array
a = np.array([0, 1, 2, 3, 4])
a
```
The attribute <code>size</code> is the number of elements in the array:
```
# Get the size of numpy array
a.size
```
The next two attributes will make more sense when we get to higher dimensions but let's review them. The attribute <code>ndim</code> represents the number of array dimensions or the rank of the array, in this case, one:
```
# Get the number of dimensions of numpy array
a.ndim
```
The attribute <code>shape</code> is a tuple of integers indicating the size of the array in each dimension:
```
# Get the shape/size of numpy array
a.shape
# Create a numpy array
a = np.array([1, -1, 1, -1])
# Get the mean of numpy array
mean = a.mean()
mean
# Get the standard deviation of numpy array
standard_deviation=a.std()
standard_deviation
# Create a numpy array
b = np.array([-1, 2, 3, 4, 5])
b
# Get the biggest value in the numpy array
max_b = b.max()
max_b
# Get the smallest value in the numpy array
min_b = b.min()
min_b
```
<hr>
<h2 id="op">Numpy Array Operations</h2>
<h3 id="add">Array Addition</h3>
Consider the numpy array <code>u</code>:
```
u = np.array([1, 0])
u
```
Consider the numpy array <code>v</code>:
```
v = np.array([0, 1])
v
```
We can add the two arrays and assign it to z:
```
# Numpy Array Addition
z = u + v
z
```
The operation is equivalent to vector addition:
```
# Plot numpy arrays
Plotvec1(u, z, v)
```
<h3 id="multi">Array Multiplication</h3>
Consider the vector numpy array <code>y</code>:
```
# Create a numpy array
y = np.array([1, 2])
y
```
We can multiply every element in the array by 2:
```
# Numpy Array Multiplication
z = 2 * y
z
```
This is equivalent to multiplying a vector by a scaler:
<h3 id="prod">Product of Two Numpy Arrays</h3>
Consider the following array <code>u</code>:
```
# Create a numpy array
u = np.array([1, 2])
u
```
Consider the following array <code>v</code>:
```
# Create a numpy array
v = np.array([3, 2])
v
```
The product of the two numpy arrays <code>u</code> and <code>v</code> is given by:
```
# Calculate the production of two numpy arrays
z = u * v
z
```
<h3 id="dot">Dot Product</h3>
The dot product of the two numpy arrays <code>u</code> and <code>v</code> is given by:
```
# Calculate the dot product
np.dot(u, v)
```
<h3 id="cons">Adding Constant to a Numpy Array</h3>
Consider the following array:
```
# Create a constant to numpy array
u = np.array([1, 2, 3, -1])
u
```
Adding the constant 1 to each element in the array:
```
# Add the constant to array
u + 1
```
The process is summarised in the following animation:
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%205/Images/NumOneAdd.gif" width="500" />
<hr>
<h2 id="math">Mathematical Functions</h2>
We can access the value of pie in numpy as follows :
```
# The value of pie
np.pi
```
We can create the following numpy array in Radians:
```
# Create the numpy array in radians
x = np.array([0, np.pi/2 , np.pi])
```
We can apply the function <code>sin</code> to the array <code>x</code> and assign the values to the array <code>y</code>; this applies the sine function to each element in the array:
```
# Calculate the sin of each elements
y = np.sin(x)
y
```
<hr>
<h2 id="lin">Linspace</h2>
A useful function for plotting mathematical functions is "linespace". Linespace returns evenly spaced numbers over a specified interval. We specify the starting point of the sequence and the ending point of the sequence. The parameter "num" indicates the Number of samples to generate, in this case 5:
```
# Makeup a numpy array within [-2, 2] and 5 elements
np.linspace(-2, 2, num=5)
```
If we change the parameter <code>num</code> to 9, we get 9 evenly spaced numbers over the interval from -2 to 2:
```
# Makeup a numpy array within [-2, 2] and 9 elements
np.linspace(-2, 2, num=9)
```
We can use the function line space to generate 100 evenly spaced samples from the interval 0 to 2π:
```
# Makeup a numpy array within [0, 2π] and 100 elements
x = np.linspace(0, 2*np.pi, num=100)
```
We can apply the sine function to each element in the array <code>x</code> and assign it to the array <code>y</code>:
```
# Calculate the sine of x list
y = np.sin(x)
# Plot the result
plt.plot(x, y)
```
<hr>
<h2 id="quiz">Quiz on 1D Numpy Array</h2>
Implement the following vector subtraction in numpy: u-v
```
# Write your code below and press Shift+Enter to execute
u = np.array([1, 0])
v = np.array([0, 1])
u-v
```
Double-click __here__ for the solution.
<!-- Your answer is below:
u - v
-->
<hr>
Multiply the numpy array z with -2:
```
# Write your code below and press Shift+Enter to execute
z = np.array([2, 4])
z * -2
```
Double-click __here__ for the solution.
<!-- Your answer is below:
-2 * z
-->
<hr>
Consider the list <code>[1, 2, 3, 4, 5]</code> and <code>[1, 0, 1, 0, 1]</code>, and cast both lists to a numpy array then multiply them together:
```
# Write your code below and press Shift+Enter to execute
np.array([1,2,3,4,5]) * np.array([1,0,1,0,1])
```
Double-click __here__ for the solution.
<!-- Your answer is below:
a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 0, 1, 0, 1])
a * b
-->
<hr>
Convert the list <code>[-1, 1]</code> and <code>[1, 1]</code> to numpy arrays <code>a</code> and <code>b</code>. Then, plot the arrays as vectors using the fuction <code>Plotvec2</code> and find the dot product:
```
# Write your code below and press Shift+Enter to execute
a = np.array([-1,1])
b = np.array([1,1])
Plotvec2(a,b)
np.dot(a,b)
```
Double-click __here__ for the solution.
<!-- Your answer is below:
a = np.array([-1, 1])
b = np.array([1, 1])
Plotvec2(a, b)
print("The dot product is", np.dot(a,b))
-->
<hr>
Convert the list <code>[1, 0]</code> and <code>[0, 1]</code> to numpy arrays <code>a</code> and <code>b</code>. Then, plot the arrays as vectors using the function <code>Plotvec2</code> and find the dot product:
```
# Write your code below and press Shift+Enter to execute
a = np.array([1,0])
b = np.array([0,1])
Plotvec2(a,b)
np.dot(a,b)
```
Double-click __here__ for the solution.
<!--
a = np.array([1, 0])
b = np.array([0, 1])
Plotvec2(a, b)
print("The dot product is", np.dot(a, b))
-->
<hr>
Convert the list <code>[1, 1]</code> and <code>[0, 1]</code> to numpy arrays <code>a</code> and <code>b</code>. Then plot the arrays as vectors using the fuction <code>Plotvec2</code> and find the dot product:
```
# Write your code below and press Shift+Enter to execute
a = np.array([1,1])
b = np.array([0,1])
Plotvec2(a,b)
np.dot(a,b)
```
Double-click __here__ for the solution.
<!--
a = np.array([1, 1])
b = np.array([0, 1])
Plotvec2(a, b)
print("The dot product is", np.dot(a, b))
print("The dot product is", np.dot(a, b))
-->
<hr>
Why are the results of the dot product for <code>[-1, 1]</code> and <code>[1, 1]</code> and the dot product for <code>[1, 0]</code> and <code>[0, 1]</code> zero, but not zero for the dot product for <code>[1, 1]</code> and <code>[0, 1]</code>? <p><i>Hint: Study the corresponding figures, pay attention to the direction the arrows are pointing to.</i></p>
```
# Write your code below and press Shift+Enter to execute
"Because the last ones are not perpendicular."
```
Double-click __here__ for the solution.
<!--
The vectors used for question 4 and 5 are perpendicular. As a result, the dot product is zero.
-->
<hr>
<h2>The last exercise!</h2>
<p>Congratulations, you have completed your first lesson and hands-on lab in Python. However, there is one more thing you need to do. The Data Science community encourages sharing work. The best way to share and showcase your work is to share it on GitHub. By sharing your notebook on GitHub you are not only building your reputation with fellow data scientists, but you can also show it off when applying for a job. Even though this was your first piece of work, it is never too early to start building good habits. So, please read and follow <a href="https://cognitiveclass.ai/blog/data-scientists-stand-out-by-sharing-your-notebooks/" target="_blank">this article</a> to learn how to share your work.
<hr>
<div class="alert alert-block alert-info" style="margin-top: 20px">
<h2>Get IBM Watson Studio free of charge!</h2>
<p><a href="https://cocl.us/bottemNotebooksPython101Coursera"><img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/BottomAd.png" width="750" align="center"></a></p>
</div>
<h3>About the Authors:</h3>
<p><a href="https://www.linkedin.com/in/joseph-s-50398b136/" target="_blank">Joseph Santarcangelo</a> is a Data Scientist at IBM, and holds a PhD in Electrical Engineering. His research focused on using Machine Learning, Signal Processing, and Computer Vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.</p>
Other contributors: <a href="www.linkedin.com/in/jiahui-mavis-zhou-a4537814a">Mavis Zhou</a>
<hr>
<p>Copyright © 2018 IBM Developer Skills Network. This notebook and its source code are released under the terms of the <a href="https://cognitiveclass.ai/mit-license/">MIT License</a>.</p>
| github_jupyter |
```
import graphlab
#input files
dir_csv="/Users/aponsero/Documents/UA_POSTDOC/projects/B2_project/MongoDB_ingest/test_passive_samplers/experiments"
dir_voc="/Users/aponsero/Documents/UA_POSTDOC/projects/B2_project/b2_drought/vocabulary"
file_csv=dir_csv+"/mapped_converted_VOC.csv"
vocabulary_file=dir_voc+"/experiment_controlled_vocabulary.csv"
typology_file=dir_voc+"/experiment_typology.csv"
#output file
out_dir="/Users/aponsero/Documents/UA_POSTDOC/projects/B2_project/MongoDB_ingest/test_passive_samplers/experiments"
json_file=out_dir+"/experiment_leaves.json"
fout = open(json_file, "a")
#experiment type
my_exp_type="VOCs"
my_frame=graphlab.SFrame.read_csv(file_csv, column_type_hints=str)
my_frame
#minimum information checklist
my_typo=graphlab.SFrame.read_csv(typology_file, column_type_hints=str)
minimum_tab=my_typo[(my_typo['Types'] == my_exp_type)]
minimum_fields=minimum_tab['required_fields']
for x in minimum_fields:
if x in my_frame.column_names():
print(x+": OK")
else :
print(x+" : not found")
check = all(elem in my_frame.column_names() for elem in minimum_fields)
if check:
print("The document passes the checklist")
else :
print("Warning : minimum attributes missing !")
my_voc=graphlab.SFrame.read_csv(vocabulary_file, column_type_hints=str)
my_voc
# find the object categories and create type finder
Specimen_description=[]
Experiment_description=[]
Result=[]
File_list=[]
No_object=[]
attribute_types={}
for i in my_frame.column_names():
curr_data=my_voc[(my_voc['Term'] == i)]
section=curr_data['Section_object']
att_type=curr_data['Type']
#add type in attribute_types
attribute_types[i] = att_type[0]
#add the attribute in the object categories
if section[0] == "Specimen_description":
Specimen_description.append(i)
elif section[0] == "Experiment_description":
Experiment_description.append(i)
elif section[0] == "Result":
Result.append(i)
elif section[0] == "File":
File_list.append(i)
else:
No_object.append(i)
print(Specimen_description)
print(Experiment_description)
print(Result)
print(File_list)
print(No_object)
print(attribute_types)
nb_samples=my_frame.shape[0]
for i in range(0,nb_samples):
curr_slice=my_frame[i]
line="{"
#process the specimen description
for i in range(len(Specimen_description)):
Key=Specimen_description[i]
if str(curr_slice[Specimen_description[i]])=="NA" or str(curr_slice[Specimen_description[i]])=="None":
attribute="\"NA\""
else:
if attribute_types[Key]=="int" or attribute_types[Key]=="float" or attribute_types[Key]=="num":
attribute=str(curr_slice[Specimen_description[i]])
elif attribute_types[Key]=="date-time":
attribute="{$date:\""+str(curr_slice[Specimen_description[i]])+"\"}"
else:
attribute="\""+str(curr_slice[Specimen_description[i]])+"\""
line=line+"\""+Key+"\":"+attribute+","
#print("#### "+line)
#process the Experiment description
for i in range(len(Experiment_description)):
Key=Experiment_description[i]
if str(curr_slice[Experiment_description[i]])=="NA" or str(curr_slice[Experiment_description[i]])=="None":
attribute="\"NA\""
else:
if attribute_types[Key]=="int" or attribute_types[Key]=="float" or attribute_types[Key]=="num":
attribute=str(curr_slice[Experiment_description[i]])
elif attribute_types[Key]=="date-time":
attribute="{$date:\""+str(curr_slice[Experiment_description[i]])+"\"}"
else:
attribute="\""+str(curr_slice[Experiment_description[i]])+"\""
line=line+"\""+Key+"\":"+attribute+","
#process the Result
line=line+"\"Result\":{"
for i in range(len(Result)):
Key=Result[i]
if str(curr_slice[Result[i]])=="NA" or str(curr_slice[Result[i]])=="None":
attribute="\"NA\""
else:
if attribute_types[Key]=="int" or attribute_types[Key]=="float" or attribute_types[Key]=="num":
attribute=str(curr_slice[Result[i]])
elif attribute_types[Key]=="date-time":
attribute="{$date:\""+str(curr_slice[Result[i]])+"\"}"
else:
attribute="\""+str(curr_slice[Result[i]])+"\""
line=line+"\""+Key+"\":"+attribute
if i==len(Result)-1:
line=line+"},"
else:
line=line+","
#process file list
line=line+"\"files\":{"
for i in range(len(File_list)):
Key=File_list[i]
if str(curr_slice[File_list[i]])=="NA" or str(curr_slice[File_list[i]])=="None":
attribute="\"NA\""
else:
if attribute_types[Key]=="int" or attribute_types[Key]=="float" or attribute_types[Key]=="num":
attribute=str(curr_slice[File_list[i]])
elif attribute_types[Key]=="date-time":
attribute="{$date:\""+str(curr_slice[File_list[i]])+"\"}"
else:
attribute="\""+str(curr_slice[File_list[i]])+"\""
line=line+"\""+Key+"\":"+attribute
if i==len(File_list)-1:
line=line+"}"
else:
line=line+","
line=line+"}"
fout.write(line+"\n")
print(line)
fout.close()
```
| github_jupyter |
<i>Copyright (c) Microsoft Corporation. All rights reserved.</i>
<i>Licensed under the MIT License.</i>
# Bayesian Personalized Ranking (BPR)
This notebook serves as an introduction to Bayesian Personalized Ranking (BPR) model for implicit feedback. In this tutorial, we focus on learning the BPR model using matrix factorization approach, hence, the model is sometimes also named BPRMF.
The implementation of the model is from [Cornac](https://github.com/PreferredAI/cornac), which is a framework for recommender systems with a focus on models leveraging auxiliary data (e.g., item descriptive text and image, social network, etc).
## 0 Global Settings and Imports
```
import sys
import os
import cornac
import papermill as pm
import scrapbook as sb
import pandas as pd
from recommenders.datasets import movielens
from recommenders.datasets.python_splitters import python_random_split
from recommenders.evaluation.python_evaluation import map_at_k, ndcg_at_k, precision_at_k, recall_at_k
from recommenders.models.cornac.cornac_utils import predict_ranking
from recommenders.utils.timer import Timer
from recommenders.utils.constants import SEED
print("System version: {}".format(sys.version))
print("Cornac version: {}".format(cornac.__version__))
# Select MovieLens data size: 100k, 1m, 10m, or 20m
MOVIELENS_DATA_SIZE = '100k'
# top k items to recommend
TOP_K = 10
# Model parameters
NUM_FACTORS = 200
NUM_EPOCHS = 100
```
## 1 BPR Algorithm
### 1.1 Personalized Ranking from Implicit Feedback
The task of personalized ranking aims at providing each user a ranked list of items (recommendations). This is very common in scenarios where recommender systems are based on implicit user behavior (e.g. purchases, clicks). The available observations are only positive feedback where the non-observed ones are a mixture of real negative feedback and missing values.
One usual approach for item recommendation is directly predicting a preference score $\hat{x}_{u,i}$ given to item $i$ by user $u$. BPR uses a different approach by using item pairs $(i, j)$ and optimizing for the correct ranking given preference of user $u$, thus, there are notions of *positive* and *negative* items. The training data $D_S : U \times I \times I$ is defined as:
$$D_S = \{(u, i, j) \mid i \in I^{+}_{u} \wedge j \in I \setminus I^{+}_{u}\}$$
where user $u$ is assumed to prefer $i$ over $j$ (i.e. $i$ is a *positive item* and $j$ is a *negative item*).
### 1.2 Objective Function
From the Bayesian perspective, BPR maximizes the posterior probability over the model parameters $\Theta$ by optimizing the likelihood function $p(i >_{u} j | \Theta)$ and the prior probability $p(\Theta)$.
$$p(\Theta \mid >_{u}) \propto p(i >_{u} j \mid \Theta) \times p(\Theta)$$
The joint probability of the likelihood over all users $u \in U$ can be simplified to:
$$ \prod_{u \in U} p(>_{u} \mid \Theta) = \prod_{(u, i, j) \in D_S} p(i >_{u} j \mid \Theta) $$
The individual probability that a user $u$ prefers item $i$ to item $j$ can be defined as:
$$ p(i >_{u} j \mid \Theta) = \sigma (\hat{x}_{uij}(\Theta)) $$
where $\sigma$ is the logistic sigmoid:
$$ \sigma(x) = \frac{1}{1 + e^{-x}} $$
The preference scoring function $\hat{x}_{uij}(\Theta)$ could be an arbitrary real-valued function of the model parameter $\Theta$. Thus, it makes BPR a general framework for modeling the relationship between triplets $(u, i, j)$ where different model classes like matrix factorization could be used for estimating $\hat{x}_{uij}(\Theta)$.
For the prior, one of the common pratices is to choose $p(\Theta)$ following a normal distribution, which results in a nice form of L2 regularization in the final log-form of the objective function.
$$ p(\Theta) \sim N(0, \Sigma_{\Theta}) $$
To reduce the complexity of the model, all parameters $\Theta$ are assumed to be independent and having the same variance, which gives a simpler form of the co-variance matrix $\Sigma_{\Theta} = \lambda_{\Theta}I$. Thus, there are less number of hyperparameters to be determined.
The final objective of the maximum posterior estimator:
$$ J = \sum_{(u, i, j) \in D_S} \text{ln } \sigma(\hat{x}_{uij}) - \lambda_{\Theta} ||\Theta||^2 $$
where $\lambda_\Theta$ are the model specific regularization paramerters.
### 1.3 Learning with Matrix Factorization
#### Stochastic Gradient Descent
As the defined objective function is differentible, gradient descent based method for optimization is naturally adopted. The gradient of the objective $J$ with respect to the model parameters:
$$
\begin{align}
\frac{\partial J}{\partial \Theta} & = \sum_{(u, i, j) \in D_S} \frac{\partial}{\partial \Theta} \text{ln} \ \sigma(\hat{x}_{uij}) - \lambda_{\Theta} \frac{\partial}{\partial \Theta} ||\Theta||^2 \\
& \propto \sum_{(u, i, j) \in D_S} \frac{-e^{-\hat{x}_{uij}}}{1 + e^{-\hat{x}_{uij}}} \cdot \frac{\partial}{\partial \Theta} \hat{x}_{uij} - \lambda_{\Theta} \Theta
\end{align}
$$
Due to slow convergence of full gradient descent, we prefer using stochastic gradient descent to optimize the BPR model. For each triplet $(u, i, j) \in D_S$, the update rule for the parameters:
$$ \Theta \leftarrow \Theta + \alpha \Big( \frac{e^{-\hat{x}_{uij}}}{1 + e^{-\hat{x}_{uij}}} \cdot \frac{\partial}{\partial \Theta} \hat{x}_{uij} + \lambda_\Theta \Theta \Big) $$
#### Matrix Factorization for Preference Approximation
As mentioned earlier, the preference scoring function $\hat{x}_{uij}(\Theta)$ could be approximated by any real-valued function. First, the estimator $\hat{x}_{uij}$ is decomposed into:
$$ \hat{x}_{uij} = \hat{x}_{ui} - \hat{x}_{uj} $$
The problem of estimating $\hat{x}_{ui}$ is a standard collaborative filtering formulation, where matrix factorization approach has shown to be very effective. The prediction formula can written as dot product between user feature vector $w_u$ and item feature vector $h_i$:
$$ \hat{x}_{ui} = \langle w_u , h_i \rangle = \sum_{f=1}^{k} w_{uf} \cdot h_{if} $$
The derivatives of matrix factorization with respect to the model parameters are:
$$
\frac{\partial}{\partial \theta} \hat{x}_{uij} =
\begin{cases}
(h_{if} - h_{jf}) & \text{if } \theta = w_{uf} \\
w_{uf} & \text{if } \theta = h_{if} \\
-w_{uf} & \text{if } \theta = h_{jf} \\
0 & \text{else}
\end{cases}
$$
In theory, any kernel can be used to estimate $\hat{x}_{ui}$ besides the dot product $ \langle \cdot , \cdot \rangle $. For example, k-Nearest-Neighbor (kNN) has also been shown to achieve good performance.
#### Analogies to AUC optimization
By optimizing the objective function of BPR model, we effectively maximizing [AUC](https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5) measurement. To keep the notebook focused, please refer to the [paper](https://arxiv.org/ftp/arxiv/papers/1205/1205.2618.pdf) for details of the analysis (Section 4.1.1).
## 2 Cornac implementation of BPR
BPR is implemented in the [Cornac](https://cornac.readthedocs.io/en/latest/index.html) framework as part of the model collections.
* Detailed documentations of the BPR model in Cornac can be found [here](https://cornac.readthedocs.io/en/latest/models.html#bayesian-personalized-ranking-bpr).
* Source codes of the BPR implementation is available on the Cornac Github repository, which can be found [here](https://github.com/PreferredAI/cornac/blob/master/cornac/models/bpr/recom_bpr.pyx).
## 3 Cornac BPR movie recommender
### 3.1 Load and split data
To evaluate the performance of item recommendation, we adopted the provided `python_random_split` tool for the consistency. Data is randomly split into training and test sets with the ratio of 75/25.
Note that Cornac also cover different [built-in schemes](https://cornac.readthedocs.io/en/latest/eval_methods.html) for model evaluation.
```
data = movielens.load_pandas_df(
size=MOVIELENS_DATA_SIZE,
header=["userID", "itemID", "rating"]
)
data.head()
train, test = python_random_split(data, 0.75)
```
### 3.2 Cornac Dataset
To work with models implemented in Cornac, we need to construct an object from [Dataset](https://cornac.readthedocs.io/en/latest/data.html#module-cornac.data.dataset) class.
Dataset Class in Cornac serves as the main object that the models will interact with. In addition to data transformations, Dataset provides a bunch of useful iterators for looping through the data, as well as supporting different negative sampling techniques.
```
train_set = cornac.data.Dataset.from_uir(train.itertuples(index=False), seed=SEED)
print('Number of users: {}'.format(train_set.num_users))
print('Number of items: {}'.format(train_set.num_items))
```
### 3.3 Train the BPR model
The BPR has a few important parameters that we need to consider:
- `k`: controls the dimension of the latent space (i.e. the size of the vectors $w_u$ and $h_i$ ).
- `max_iter`: defines the number of iterations of the SGD procedure.
- `learning_rate`: controls the step size $\alpha$ in the gradient update rules.
- `lambda_reg`: controls the L2-Regularization $\lambda$ in the objective function.
Note that different values of `k` and `max_iter` will affect the training time.
We will here set `k` to 200, `max_iter` to 100, `learning_rate` to 0.01, and `lambda_reg` to 0.001. To train the model, we simply need to call the `fit()` method.
```
bpr = cornac.models.BPR(
k=NUM_FACTORS,
max_iter=NUM_EPOCHS,
learning_rate=0.01,
lambda_reg=0.001,
verbose=True,
seed=SEED
)
with Timer() as t:
bpr.fit(train_set)
print("Took {} seconds for training.".format(t))
```
### 3.4 Prediction and Evaluation
Now that our model is trained, we can produce the ranked lists for recommendation. Every recommender models in Cornac provide `rate()` and `rank()` methods for predicting item rated value as well as item ranked list for a given user. To make use of the current evaluation schemes, we will through `predict()` and `predict_ranking()` functions inside `cornac_utils` to produce the predictions.
Note that BPR model is effectively designed for item ranking. Hence, we only measure the performance using ranking metrics.
```
with Timer() as t:
all_predictions = predict_ranking(bpr, train, usercol='userID', itemcol='itemID', remove_seen=True)
print("Took {} seconds for prediction.".format(t))
all_predictions.head()
k = 10
eval_map = map_at_k(test, all_predictions, col_prediction='prediction', k=k)
eval_ndcg = ndcg_at_k(test, all_predictions, col_prediction='prediction', k=k)
eval_precision = precision_at_k(test, all_predictions, col_prediction='prediction', k=k)
eval_recall = recall_at_k(test, all_predictions, col_prediction='prediction', k=k)
print("MAP:\t%f" % eval_map,
"NDCG:\t%f" % eval_ndcg,
"Precision@K:\t%f" % eval_precision,
"Recall@K:\t%f" % eval_recall, sep='\n')
# Record results with papermill for tests
sb.glue("map", eval_map)
sb.glue("ndcg", eval_ndcg)
sb.glue("precision", eval_precision)
sb.glue("recall", eval_recall)
```
## References
1. Rendle, S., Freudenthaler, C., Gantner, Z., & Schmidt-Thieme, L. (2009, June). BPR: Bayesian personalized ranking from implicit feedback. https://arxiv.org/ftp/arxiv/papers/1205/1205.2618.pdf
2. Pan, R., Zhou, Y., Cao, B., Liu, N. N., Lukose, R., Scholz, M., & Yang, Q. (2008, December). One-class collaborative filtering. https://cseweb.ucsd.edu/classes/fa17/cse291-b/reading/04781145.pdf
3. **Cornac** - A Comparative Framework for Multimodal Recommender Systems. https://cornac.preferred.ai/
| github_jupyter |
# Day 13 - Prime number factors
* https://adventofcode.com/2020/day/13
For part 1, we need to find the next multiple of a bus ID that's equal to or greater than our earliest departure time. The bus IDs, which determine their frequency, are all prime numbers, of course.
We can calculate the next bus departure $t$ for a given ID $b$ on or after earliest departure time $T$ as $t = b * \lceil T / b \rceil$ ($b$ multiplied by the ceiling of the division of $T$ by $b$).
```
import math
def parse_bus_ids(line: str) -> list[int]:
return [int(b) for b in line.split(",") if b[0] != "x"]
def parse_input(lines: str) -> [int, list[int]]:
return int(lines[0]), parse_bus_ids(lines[1])
def earliest_departure(earliest: int, bus_ids: list[int]) -> tuple[int, int]:
t, bid = min((bid * math.ceil(earliest / bid), bid) for bid in bus_ids)
return t - earliest, bid
test_earliest, test_bus_ids = parse_input(["939", "7,13,x,x,59,x,31,19"])
assert earliest_departure(test_earliest, test_bus_ids) == (5, 59)
import aocd
data = aocd.get_data(day=13, year=2020).splitlines()
earliest, bus_ids = parse_input(data)
wait_time, bus_id = earliest_departure(earliest, bus_ids)
print("Part 1:", wait_time * bus_id)
```
## Part 2: Chinese remainder theorem.
For part 2, we need to use the [Chinese remainder theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem); this theorem was first introduced by the Chinese mathematician Sun-tzu (quote from the Wikipedia article):
> There are certain things whose number is unknown. If we count them by threes, we have two left over; by fives, we have three left over; and by sevens, two are left over. How many things are there?
We need to find a number that if counted in prime number steps, have an offset left over, where the offset is the prime number minus the index in the bus ids list, modulo the bus id (the matching time stamp lies X minutes *before* the next bus departs).
I only remembered about the theorem as it was also applicable to [Advent of Code 2017, day 13](../2017/Day%2013.ipynb) (although I didn't know it at the time).
I adapted the [Rossetta Stone Python implementation](https://rosettacode.org/wiki/Chinese_remainder_theorem#Python) for this:
```
from functools import reduce
from operator import mul
from typing import Optional
def solve_chinese_remainder(bus_times: list[Optional[int]]) -> int:
product = reduce(mul, (bid for bid in filter(None, bus_times)))
summed = sum(
((bid - i) % bid) * mul_inv((factor := product // bid), bid) * factor
for i, bid in enumerate(bus_times)
if bid is not None
)
return summed % product
def mul_inv(a: int, b: int) -> int:
if b == 1: return 1
b0, x0, x1 = b, 0, 1
while a > 1:
q = a // b
a, b = b, a % b
x0, x1 = x1 - q * x0, x0
if x1 < 0:
x1 += b0
return x1
def parse_bus_times(line: str) -> list[Optional[int]]:
return [None if bus_id == "x" else int(bus_id) for bus_id in line.split(",")]
tests = {
"7,13,x,x,59,x,31,19": 1068781,
"17,x,13,19": 3417,
"67,7,59,61": 754018,
"67,x,7,59,61": 779210,
"67,7,x,59,61": 1261476,
"1789,37,47,1889": 1202161486,
}
for times, expected in tests.items():
assert solve_chinese_remainder(parse_bus_times(times)) == expected
print("Part 2:", solve_chinese_remainder(parse_bus_times(data[1])))
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.