text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
##### Copyright 2018 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# テンソルと演算
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/customization/basics"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/ja/tutorials/customization/basics.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/ja/tutorials/customization/basics.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
Note: これらのドキュメントは私たちTensorFlowコミュニティが翻訳したものです。コミュニティによる 翻訳は**ベストエフォート**であるため、この翻訳が正確であることや[英語の公式ドキュメント](https://www.tensorflow.org/?hl=en)の 最新の状態を反映したものであることを保証することはできません。 この翻訳の品質を向上させるためのご意見をお持ちの方は、GitHubリポジトリ[tensorflow/docs](https://github.com/tensorflow/docs)にプルリクエストをお送りください。 コミュニティによる翻訳やレビューに参加していただける方は、 [docs-ja@tensorflow.org メーリングリスト](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ja)にご連絡ください。
これは、下記の手法を示す TensorFlow の入門チュートリアルです。
* 必要なパッケージのインポート
* テンソルの作成と使用
* GPUによる高速化の使用
* `tf.data.Dataset`のデモ
```
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta1
```
## TensorFlowのインポート
はじめに、`tensorflow` モジュールをインポートします。TensorFlow 2.0 では、eager execution が既定でオンとなっています。
これにより、TensorFlow のフロントエンドがよりインタラクティブになります。詳細は後述します。
```
import tensorflow as tf
```
## テンソル
テンソルは多次元配列です。NumPy の `ndarray` オブジェクトと同様に、`tf.Tensor` にはデータ型と形状があります。これに加えて、`tf.Tensor` は( GPU のような)アクセラレータのメモリに置くことができます。TensorFlow には、`tf.Tensor` を使用し生成するたくさんの演算([tf.add](https://www.tensorflow.org/api_docs/python/tf/add), [tf.matmul](https://www.tensorflow.org/api_docs/python/tf/matmul), [tf.linalg.inv](https://www.tensorflow.org/api_docs/python/tf/linalg/inv) など)のライブラリが存在します。これらの演算では、ネイティブな Python データ型が自動変換されます。例を示します。
```
print(tf.add(1, 2))
print(tf.add([1, 2], [3, 4]))
print(tf.square(5))
print(tf.reduce_sum([1, 2, 3]))
# Operator overloading is also supported
print(tf.square(2) + tf.square(3))
```
それぞれの`tf.Tensor`には、形状とデータ型があります。
```
x = tf.matmul([[1]], [[2, 3]])
print(x)
print(x.shape)
print(x.dtype)
```
NumPy 配列と `tf.Tensor` の間のもっとも明確な違いは
1. テンソルは( GPU や TPU などの)アクセラレータメモリを使用できる
2. テンソルは変更不可
### NumPy互換性
TensorFlow の`tf.Tensor`と NumPy の `ndarray` 間の変換は簡単です。
* TensorFlow の演算により NumPy の ndarray は自動的にテンソルに変換される
* NumPy の演算によりテンソルは自動的に NumPy の ndarray に変換される
テンソルは `.numpy()` メソッドを使って明示的に NumPy の ndarray に変換されます。NumPy のndarray と `tf.Tensor` はその下敷きとなるメモリ上の表現が、できるかぎり共通化されているので、通常この変換のコストは小さいです。しかし、NumPy 配列はホスト側のメモリに置かれる一方、`tf.Tensor` はGPU のメモリに置かれる可能性もあるため、下層の表現をいつも共通化できるとは限りません。また、変換にはGPU からホスト側メモリへのコピーも関わってきます。
```
import numpy as np
ndarray = np.ones([3, 3])
print("TensorFlow演算によりnumpy配列は自動的にテンソルに変換される")
tensor = tf.multiply(ndarray, 42)
print(tensor)
print("またNumPy演算によりテンソルは自動的にnumpy配列に変換される")
print(np.add(tensor, 1))
print(".numpy()メソッドによりテンソルは明示的にnumpy配列に変換される")
print(tensor.numpy())
```
## GPU による高速化
TensorFlow の演算の多くは、GPU を計算に使用することで高速化されます。TensorFlow は演算に注釈をつけなくとも、自動的に GPU と CPU のどちらかを選択し、必要であればテンソルを GPU メモリと CPU メモリの間でコピーして実行します。演算で生成されたテンソルは通常演算を実行したデバイスのメモリに置かれます。例を見てみましょう。
```
x = tf.random.uniform([3, 3])
print("利用できるGPUはあるか: "),
print(tf.test.is_gpu_available())
print("テンソルはGPU #0にあるか: "),
print(x.device.endswith('GPU:0'))
```
### デバイス名
`Tensor.device` プロパティにより、そのテンソルの内容を保持しているデバイスの完全な名前文字列を得ることができます。この名前には、プログラムを実行中のホストのネットワークアドレスや、ホスト上のデバイスについての詳細がエンコードされています。この情報は、TensorFlow プログラムの分散実行に必要なものです。テンソルがホスト上の `N` 番目のGPUにある場合、文字列の最後は `GPU:<N>` となります。
### 明示的デバイス配置
TensorFlowでいう**配置**は、個々の演算を実行するためにどのようにデバイスにアサイン(配置)されるかを指します。前述のとおり、明示的な示唆がなければ、TensorFlow は演算を実行するデバイスを自動的に決め、必要であればテンソルをそのデバイスにコピーします。しかし、`tf.device` コンテキストマネジャーを使うことで、TensorFlow の演算を特定のデバイスに配置することができます。例を見てみましょう。
```
import time
def time_matmul(x):
start = time.time()
for loop in range(10):
tf.matmul(x, x)
result = time.time()-start
print("10 loops: {:0.2f}ms".format(1000*result))
# CPUでの実行を強制
print("On CPU:")
with tf.device("CPU:0"):
x = tf.random.uniform([1000, 1000])
assert x.device.endswith("CPU:0")
time_matmul(x)
# GPU #0があればその上での実行を強制
if tf.test.is_gpu_available():
print("On GPU:")
with tf.device("GPU:0"): # 2番めのGPUなら GPU:1, 3番目なら GPU:2 など
x = tf.random.uniform([1000, 1000])
assert x.device.endswith("GPU:0")
time_matmul(x)
```
## データセット
このセクションでは [`tf.data.Dataset` API](https://www.tensorflow.org/guide/datasets) を使って、モデルにデータを供給するためのパイプラインを構築します。`tf.data.Dataset` APIは、単純で再利用可能な部品をもとに、モデルの訓練あるいは評価ループにデータを供給する高性能で複雑な入力パイプラインを構築するために使われます。
### ソース`Dataset`の作成
[Dataset.from_tensors](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensors) や[Dataset.from_tensor_slices](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices) といったファクトリー関数または [TextLineDataset](https://www.tensorflow.org/api_docs/python/tf/data/TextLineDataset) あるいは[TFRecordDataset](https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset) のようなファイルを読み込むオブジェクトを使って、 **元となる**データセットを作成しましょう。詳しくは、[TensorFlow Dataset guide](https://www.tensorflow.org/guide/datasets#reading_input_data) を参照してください。
```
ds_tensors = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])
# CSVファイルを作成
import tempfile
_, filename = tempfile.mkstemp()
with open(filename, 'w') as f:
f.write("""Line 1
Line 2
Line 3
""")
ds_file = tf.data.TextLineDataset(filename)
```
### 変換の適用
[map](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map), [batch](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#batch), [shuffle](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle) などの変換関数を使って、データセットレコードに変換を適用します。
```
ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2)
```
### イテレート
`tf.data.Dataset` オブジェクトは、中のレコードを繰り返し利用するためのイテレーションをサポートします。
```
print('ds_tensors の要素:')
for x in ds_tensors:
print(x)
print('\nds_file の要素:')
for x in ds_file:
print(x)
```
| github_jupyter |
# Plagiarism Detection: PyTorch Model
Now that I've created training and test data, I'm ready to define and train a model. The goal is to train a binary classification model that learns to label an answer file as either plagiarized or not, based on the features.
This task will be broken down into a few discrete steps:
* Upload the data to S3.
* Define a binary classification model and a training script.
* Train the model and deploy it.
* Evaluate the deployed classifier.
## Load Data to S3
```
import pandas as pd
import numpy as np
import boto3
import sagemaker
import os
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# session and role
sagemaker_session = sagemaker.Session()
role = sagemaker.get_execution_role()
# create an S3 bucket
bucket = sagemaker_session.default_bucket()
data_dir = 'plagiarism_data'
# set prefix, a descriptive name for a directory
prefix = 'plagiarism_detector'
# upload all data to S3
input_data = sagemaker_session.upload_data(path = data_dir, bucket=bucket, key_prefix=prefix)
train = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None)
train.head()
```
### Test cell
```
# confirm that data is in S3 bucket
empty_check = []
for obj in boto3.resource('s3').Bucket(bucket).objects.all():
empty_check.append(obj.key)
print(obj.key)
assert len(empty_check) !=0, 'S3 bucket is empty.'
print('Test passed!')
```
## Modeling
```
# directory can be changed to: source_sklearn or source_pytorch
!pygmentize source_pytorch/train.py
```
### Define a PyTorch estimator
```
from sagemaker.pytorch import PyTorch
estimator = PyTorch(entry_point="train.py",
source_dir="source_pytorch",
role=role,
train_instance_count=1,
train_instance_type='ml.c4.xlarge',
sagemaker_session = sagemaker_session,
framework_version='1.0',
hyperparameters={
'input_features': 2,
'hidden_dim': 20,
'output_dim': 1,
'epochs': 50
})
```
### Train the estimator
```
estimator.fit({'training': input_data})
```
## Deploy the trained model
```
from sagemaker.pytorch import PyTorchModel
# Create a model from the trained estimator data
# And point to the prediction script
model = PyTorchModel(model_data=estimator.model_data,
role = role,
framework_version='1.0',
entry_point='predict.py',
source_dir='source_pytorch')
# deploy the model to create a predictor
predictor = model.deploy(initial_instance_count=1, instance_type='ml.c4.xlarge')
```
## Evaluating The Model
```
# read in test data, assuming it is stored locally
test_data = pd.read_csv(os.path.join(data_dir, "test.csv"), header=None, names=None)
# labels are in the first column
test_y = test_data.iloc[:,0]
test_x = test_data.iloc[:,1:]
```
### Determine the accuracy of the model
```
test_y_preds = np.squeeze(np.round(predictor.predict(test_x)))
# test that your model generates the correct number of labels
assert len(test_y_preds)==len(test_y), 'Unexpected number of predictions.'
print('Test passed!')
# Second: calculate the test accuracy
accuracy = accuracy_score(test_y, test_y_preds)
print(accuracy)
## print out the array of predicted and true labels, if you want
print('\nPredicted class labels: ')
print(test_y_preds)
print('\nTrue class labels: ')
print(test_y.values)
# Third: classification report
print(classification_report(test_y, test_y_preds))
```
----
## Clean up Resources
```
# Accepts a predictor endpoint as input
# And deletes the endpoint by name
def delete_endpoint(predictor):
try:
boto3.client('sagemaker').delete_endpoint(EndpointName=predictor.endpoint)
print('Deleted {}'.format(predictor.endpoint))
except:
print('Already deleted: {}'.format(predictor.endpoint))
# delete the predictor endpoint
delete_endpoint(predictor)
```
### Deleting S3 bucket
```
# deleting bucket
bucket_to_delete = boto3.resource('s3').Bucket(bucket)
bucket_to_delete.objects.all().delete()
```
---
## Further Directions
* Train a classifier to predict the *category* (1-3) of plagiarism and not just plagiarized (1) or not (0).
* Utilize a different and larger dataset to see if this model can be extended to other types of plagiarism.
* Use language or character-level analysis to find different (and more) similarity features.
* Write a complete pipeline function that accepts a source text and submitted text file, and classifies the submitted text as plagiarized or not.
* Use API Gateway and a lambda function to deploy your model to a web application.
| github_jupyter |
##### Copyright 2020 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# The Functional API
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/keras/functional"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/snapshot-keras/site/en/guide/keras/functional.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/keras-team/keras-io/blob/master/guides/functional_api.py"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/keras/functional.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
## Setup
```
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
```
## Introduction
The Keras *functional API* is a way to create models that are more flexible
than the `tf.keras.Sequential` API. The functional API can handle models
with non-linear topology, shared layers, and even multiple inputs or outputs.
The main idea is that a deep learning model is usually
a directed acyclic graph (DAG) of layers.
So the functional API is a way to build *graphs of layers*.
Consider the following model:
```
(input: 784-dimensional vectors)
↧
[Dense (64 units, relu activation)]
↧
[Dense (64 units, relu activation)]
↧
[Dense (10 units, softmax activation)]
↧
(output: logits of a probability distribution over 10 classes)
```
This is a basic graph with three layers.
To build this model using the functional API, start by creating an input node:
```
inputs = keras.Input(shape=(784,))
```
The shape of the data is set as a 784-dimensional vector.
The batch size is always omitted since only the shape of each sample is specified.
If, for example, you have an image input with a shape of `(32, 32, 3)`,
you would use:
```
# Just for demonstration purposes.
img_inputs = keras.Input(shape=(32, 32, 3))
```
The `inputs` that is returned contains information about the shape and `dtype`
of the input data that you feed to your model.
Here's the shape:
```
inputs.shape
```
Here's the dtype:
```
inputs.dtype
```
You create a new node in the graph of layers by calling a layer on this `inputs`
object:
```
dense = layers.Dense(64, activation="relu")
x = dense(inputs)
```
The "layer call" action is like drawing an arrow from "inputs" to this layer
you created.
You're "passing" the inputs to the `dense` layer, and you get `x` as the output.
Let's add a few more layers to the graph of layers:
```
x = layers.Dense(64, activation="relu")(x)
outputs = layers.Dense(10)(x)
```
At this point, you can create a `Model` by specifying its inputs and outputs
in the graph of layers:
```
model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model")
```
Let's check out what the model summary looks like:
```
model.summary()
```
You can also plot the model as a graph:
```
keras.utils.plot_model(model, "my_first_model.png")
```
And, optionally, display the input and output shapes of each layer
in the plotted graph:
```
keras.utils.plot_model(model, "my_first_model_with_shape_info.png", show_shapes=True)
```
This figure and the code are almost identical. In the code version,
the connection arrows are replaced by the call operation.
A "graph of layers" is an intuitive mental image for a deep learning model,
and the functional API is a way to create models that closely mirrors this.
## Training, evaluation, and inference
Training, evaluation, and inference work exactly in the same way for models
built using the functional API as for `Sequential` models.
The `Model` class offers a built-in training loop (the `fit()` method)
and a built-in evaluation loop (the `evaluate()` method). Note
that you can easily [customize these loops](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit/)
to implement training routines beyond supervised learning
(e.g. [GANs](/examples/generative/dcgan_overriding_train_step/)).
Here, load the MNIST image data, reshape it into vectors,
fit the model on the data (while monitoring performance on a validation split),
then evaluate the model on the test data:
```
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype("float32") / 255
x_test = x_test.reshape(10000, 784).astype("float32") / 255
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=keras.optimizers.RMSprop(),
metrics=["accuracy"],
)
history = model.fit(x_train, y_train, batch_size=64, epochs=2, validation_split=0.2)
test_scores = model.evaluate(x_test, y_test, verbose=2)
print("Test loss:", test_scores[0])
print("Test accuracy:", test_scores[1])
```
For further reading, see the [training and evaluation](https://www.tensorflow.org/guide/keras/train_and_evaluate/) guide.
## Save and serialize
Saving the model and serialization work the same way for models built using
the functional API as they do for `Sequential` models. The standard way
to save a functional model is to call `model.save()`
to save the entire model as a single file. You can later recreate the same model
from this file, even if the code that built the model is no longer available.
This saved file includes the:
- model architecture
- model weight values (that were learned during training)
- model training config, if any (as passed to `compile`)
- optimizer and its state, if any (to restart training where you left off)
```
model.save("path_to_my_model")
del model
# Recreate the exact same model purely from the file:
model = keras.models.load_model("path_to_my_model")
```
For details, read the model [serialization & saving](
https://www.tensorflow.org/guide/keras/save_and_serialize/) guide.
## Use the same graph of layers to define multiple models
In the functional API, models are created by specifying their inputs
and outputs in a graph of layers. That means that a single
graph of layers can be used to generate multiple models.
In the example below, you use the same stack of layers to instantiate two models:
an `encoder` model that turns image inputs into 16-dimensional vectors,
and an end-to-end `autoencoder` model for training.
```
encoder_input = keras.Input(shape=(28, 28, 1), name="img")
x = layers.Conv2D(16, 3, activation="relu")(encoder_input)
x = layers.Conv2D(32, 3, activation="relu")(x)
x = layers.MaxPooling2D(3)(x)
x = layers.Conv2D(32, 3, activation="relu")(x)
x = layers.Conv2D(16, 3, activation="relu")(x)
encoder_output = layers.GlobalMaxPooling2D()(x)
encoder = keras.Model(encoder_input, encoder_output, name="encoder")
encoder.summary()
x = layers.Reshape((4, 4, 1))(encoder_output)
x = layers.Conv2DTranspose(16, 3, activation="relu")(x)
x = layers.Conv2DTranspose(32, 3, activation="relu")(x)
x = layers.UpSampling2D(3)(x)
x = layers.Conv2DTranspose(16, 3, activation="relu")(x)
decoder_output = layers.Conv2DTranspose(1, 3, activation="relu")(x)
autoencoder = keras.Model(encoder_input, decoder_output, name="autoencoder")
autoencoder.summary()
```
Here, the decoding architecture is strictly symmetrical
to the encoding architecture, so the output shape is the same as
the input shape `(28, 28, 1)`.
The reverse of a `Conv2D` layer is a `Conv2DTranspose` layer,
and the reverse of a `MaxPooling2D` layer is an `UpSampling2D` layer.
## All models are callable, just like layers
You can treat any model as if it were a layer by invoking it on an `Input` or
on the output of another layer. By calling a model you aren't just reusing
the architecture of the model, you're also reusing its weights.
To see this in action, here's a different take on the autoencoder example that
creates an encoder model, a decoder model, and chains them in two calls
to obtain the autoencoder model:
```
encoder_input = keras.Input(shape=(28, 28, 1), name="original_img")
x = layers.Conv2D(16, 3, activation="relu")(encoder_input)
x = layers.Conv2D(32, 3, activation="relu")(x)
x = layers.MaxPooling2D(3)(x)
x = layers.Conv2D(32, 3, activation="relu")(x)
x = layers.Conv2D(16, 3, activation="relu")(x)
encoder_output = layers.GlobalMaxPooling2D()(x)
encoder = keras.Model(encoder_input, encoder_output, name="encoder")
encoder.summary()
decoder_input = keras.Input(shape=(16,), name="encoded_img")
x = layers.Reshape((4, 4, 1))(decoder_input)
x = layers.Conv2DTranspose(16, 3, activation="relu")(x)
x = layers.Conv2DTranspose(32, 3, activation="relu")(x)
x = layers.UpSampling2D(3)(x)
x = layers.Conv2DTranspose(16, 3, activation="relu")(x)
decoder_output = layers.Conv2DTranspose(1, 3, activation="relu")(x)
decoder = keras.Model(decoder_input, decoder_output, name="decoder")
decoder.summary()
autoencoder_input = keras.Input(shape=(28, 28, 1), name="img")
encoded_img = encoder(autoencoder_input)
decoded_img = decoder(encoded_img)
autoencoder = keras.Model(autoencoder_input, decoded_img, name="autoencoder")
autoencoder.summary()
```
As you can see, the model can be nested: a model can contain sub-models
(since a model is just like a layer).
A common use case for model nesting is *ensembling*.
For example, here's how to ensemble a set of models into a single model
that averages their predictions:
```
def get_model():
inputs = keras.Input(shape=(128,))
outputs = layers.Dense(1)(inputs)
return keras.Model(inputs, outputs)
model1 = get_model()
model2 = get_model()
model3 = get_model()
inputs = keras.Input(shape=(128,))
y1 = model1(inputs)
y2 = model2(inputs)
y3 = model3(inputs)
outputs = layers.average([y1, y2, y3])
ensemble_model = keras.Model(inputs=inputs, outputs=outputs)
```
## Manipulate complex graph topologies
### Models with multiple inputs and outputs
The functional API makes it easy to manipulate multiple inputs and outputs.
This cannot be handled with the `Sequential` API.
For example, if you're building a system for ranking customer issue tickets by
priority and routing them to the correct department,
then the model will have three inputs:
- the title of the ticket (text input),
- the text body of the ticket (text input), and
- any tags added by the user (categorical input)
This model will have two outputs:
- the priority score between 0 and 1 (scalar sigmoid output), and
- the department that should handle the ticket (softmax output
over the set of departments).
You can build this model in a few lines with the functional API:
```
num_tags = 12 # Number of unique issue tags
num_words = 10000 # Size of vocabulary obtained when preprocessing text data
num_departments = 4 # Number of departments for predictions
title_input = keras.Input(
shape=(None,), name="title"
) # Variable-length sequence of ints
body_input = keras.Input(shape=(None,), name="body") # Variable-length sequence of ints
tags_input = keras.Input(
shape=(num_tags,), name="tags"
) # Binary vectors of size `num_tags`
# Embed each word in the title into a 64-dimensional vector
title_features = layers.Embedding(num_words, 64)(title_input)
# Embed each word in the text into a 64-dimensional vector
body_features = layers.Embedding(num_words, 64)(body_input)
# Reduce sequence of embedded words in the title into a single 128-dimensional vector
title_features = layers.LSTM(128)(title_features)
# Reduce sequence of embedded words in the body into a single 32-dimensional vector
body_features = layers.LSTM(32)(body_features)
# Merge all available features into a single large vector via concatenation
x = layers.concatenate([title_features, body_features, tags_input])
# Stick a logistic regression for priority prediction on top of the features
priority_pred = layers.Dense(1, name="priority")(x)
# Stick a department classifier on top of the features
department_pred = layers.Dense(num_departments, name="department")(x)
# Instantiate an end-to-end model predicting both priority and department
model = keras.Model(
inputs=[title_input, body_input, tags_input],
outputs=[priority_pred, department_pred],
)
```
Now plot the model:
```
keras.utils.plot_model(model, "multi_input_and_output_model.png", show_shapes=True)
```
When compiling this model, you can assign different losses to each output.
You can even assign different weights to each loss -- to modulate
their contribution to the total training loss.
```
model.compile(
optimizer=keras.optimizers.RMSprop(1e-3),
loss=[
keras.losses.BinaryCrossentropy(from_logits=True),
keras.losses.CategoricalCrossentropy(from_logits=True),
],
loss_weights=[1.0, 0.2],
)
```
Since the output layers have different names, you could also specify
the loss like this:
```
model.compile(
optimizer=keras.optimizers.RMSprop(1e-3),
loss={
"priority": keras.losses.BinaryCrossentropy(from_logits=True),
"department": keras.losses.CategoricalCrossentropy(from_logits=True),
},
loss_weights=[1.0, 0.2],
)
```
Train the model by passing lists of NumPy arrays of inputs and targets:
```
# Dummy input data
title_data = np.random.randint(num_words, size=(1280, 10))
body_data = np.random.randint(num_words, size=(1280, 100))
tags_data = np.random.randint(2, size=(1280, num_tags)).astype("float32")
# Dummy target data
priority_targets = np.random.random(size=(1280, 1))
dept_targets = np.random.randint(2, size=(1280, num_departments))
model.fit(
{"title": title_data, "body": body_data, "tags": tags_data},
{"priority": priority_targets, "department": dept_targets},
epochs=2,
batch_size=32,
)
```
When calling fit with a `Dataset` object, it should yield either a
tuple of lists like `([title_data, body_data, tags_data], [priority_targets, dept_targets])`
or a tuple of dictionaries like
`({'title': title_data, 'body': body_data, 'tags': tags_data}, {'priority': priority_targets, 'department': dept_targets})`.
For more detailed explanation, refer to the [training and evaluation](https://www.tensorflow.org/guide/keras/train_and_evaluate/) guide.
### A toy ResNet model
In addition to models with multiple inputs and outputs,
the functional API makes it easy to manipulate non-linear connectivity
topologies -- these are models with layers that are not connected sequentially,
which the `Sequential` API cannot handle.
A common use case for this is residual connections.
Let's build a toy ResNet model for CIFAR10 to demonstrate this:
```
inputs = keras.Input(shape=(32, 32, 3), name="img")
x = layers.Conv2D(32, 3, activation="relu")(inputs)
x = layers.Conv2D(64, 3, activation="relu")(x)
block_1_output = layers.MaxPooling2D(3)(x)
x = layers.Conv2D(64, 3, activation="relu", padding="same")(block_1_output)
x = layers.Conv2D(64, 3, activation="relu", padding="same")(x)
block_2_output = layers.add([x, block_1_output])
x = layers.Conv2D(64, 3, activation="relu", padding="same")(block_2_output)
x = layers.Conv2D(64, 3, activation="relu", padding="same")(x)
block_3_output = layers.add([x, block_2_output])
x = layers.Conv2D(64, 3, activation="relu")(block_3_output)
x = layers.GlobalAveragePooling2D()(x)
x = layers.Dense(256, activation="relu")(x)
x = layers.Dropout(0.5)(x)
outputs = layers.Dense(10)(x)
model = keras.Model(inputs, outputs, name="toy_resnet")
model.summary()
```
Plot the model:
```
keras.utils.plot_model(model, "mini_resnet.png", show_shapes=True)
```
Now train the model:
```
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
model.compile(
optimizer=keras.optimizers.RMSprop(1e-3),
loss=keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=["acc"],
)
# We restrict the data to the first 1000 samples so as to limit execution time
# on Colab. Try to train on the entire dataset until convergence!
model.fit(x_train[:1000], y_train[:1000], batch_size=64, epochs=1, validation_split=0.2)
```
## Shared layers
Another good use for the functional API are models that use *shared layers*.
Shared layers are layer instances that are reused multiple times in the same model --
they learn features that correspond to multiple paths in the graph-of-layers.
Shared layers are often used to encode inputs from similar spaces
(say, two different pieces of text that feature similar vocabulary).
They enable sharing of information across these different inputs,
and they make it possible to train such a model on less data.
If a given word is seen in one of the inputs,
that will benefit the processing of all inputs that pass through the shared layer.
To share a layer in the functional API, call the same layer instance multiple times.
For instance, here's an `Embedding` layer shared across two different text inputs:
```
# Embedding for 1000 unique words mapped to 128-dimensional vectors
shared_embedding = layers.Embedding(1000, 128)
# Variable-length sequence of integers
text_input_a = keras.Input(shape=(None,), dtype="int32")
# Variable-length sequence of integers
text_input_b = keras.Input(shape=(None,), dtype="int32")
# Reuse the same layer to encode both inputs
encoded_input_a = shared_embedding(text_input_a)
encoded_input_b = shared_embedding(text_input_b)
```
## Extract and reuse nodes in the graph of layers
Because the graph of layers you are manipulating is a static data structure,
it can be accessed and inspected. And this is how you are able to plot
functional models as images.
This also means that you can access the activations of intermediate layers
("nodes" in the graph) and reuse them elsewhere --
which is very useful for something like feature extraction.
Let's look at an example. This is a VGG19 model with weights pretrained on ImageNet:
```
vgg19 = tf.keras.applications.VGG19()
```
And these are the intermediate activations of the model,
obtained by querying the graph data structure:
```
features_list = [layer.output for layer in vgg19.layers]
```
Use these features to create a new feature-extraction model that returns
the values of the intermediate layer activations:
```
feat_extraction_model = keras.Model(inputs=vgg19.input, outputs=features_list)
img = np.random.random((1, 224, 224, 3)).astype("float32")
extracted_features = feat_extraction_model(img)
```
This comes in handy for tasks like
[neural style transfer](https://keras.io/examples/generative/neural_style_transfer/),
among other things.
## Extend the API using custom layers
`tf.keras` includes a wide range of built-in layers, for example:
- Convolutional layers: `Conv1D`, `Conv2D`, `Conv3D`, `Conv2DTranspose`
- Pooling layers: `MaxPooling1D`, `MaxPooling2D`, `MaxPooling3D`, `AveragePooling1D`
- RNN layers: `GRU`, `LSTM`, `ConvLSTM2D`
- `BatchNormalization`, `Dropout`, `Embedding`, etc.
But if you don't find what you need, it's easy to extend the API by creating
your own layers. All layers subclass the `Layer` class and implement:
- `call` method, that specifies the computation done by the layer.
- `build` method, that creates the weights of the layer (this is just a style
convention since you can create weights in `__init__`, as well).
To learn more about creating layers from scratch, read
[custom layers and models](https://www.tensorflow.org/guide/keras/custom_layers_and_models) guide.
The following is a basic implementation of `tf.keras.layers.Dense`:
```
class CustomDense(layers.Layer):
def __init__(self, units=32):
super(CustomDense, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(self.units,), initializer="random_normal", trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)
model = keras.Model(inputs, outputs)
```
For serialization support in your custom layer, define a `get_config`
method that returns the constructor arguments of the layer instance:
```
class CustomDense(layers.Layer):
def __init__(self, units=32):
super(CustomDense, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(self.units,), initializer="random_normal", trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
def get_config(self):
return {"units": self.units}
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)
model = keras.Model(inputs, outputs)
config = model.get_config()
new_model = keras.Model.from_config(config, custom_objects={"CustomDense": CustomDense})
```
Optionally, implement the class method `from_config(cls, config)` which is used
when recreating a layer instance given its config dictionary.
The default implementation of `from_config` is:
```python
def from_config(cls, config):
return cls(**config)
```
## When to use the functional API
Should you use the Keras functional API to create a new model,
or just subclass the `Model` class directly? In general, the functional API
is higher-level, easier and safer, and has a number of
features that subclassed models do not support.
However, model subclassing provides greater flexibility when building models
that are not easily expressible as directed acyclic graphs of layers.
For example, you could not implement a Tree-RNN with the functional API
and would have to subclass `Model` directly.
For an in-depth look at the differences between the functional API and
model subclassing, read
[What are Symbolic and Imperative APIs in TensorFlow 2.0?](https://blog.tensorflow.org/2019/01/what-are-symbolic-and-imperative-apis.html).
### Functional API strengths:
The following properties are also true for Sequential models
(which are also data structures), but are not true for subclassed models
(which are Python bytecode, not data structures).
#### Less verbose
There is no `super(MyClass, self).__init__(...)`, no `def call(self, ...):`, etc.
Compare:
```python
inputs = keras.Input(shape=(32,))
x = layers.Dense(64, activation='relu')(inputs)
outputs = layers.Dense(10)(x)
mlp = keras.Model(inputs, outputs)
```
With the subclassed version:
```python
class MLP(keras.Model):
def __init__(self, **kwargs):
super(MLP, self).__init__(**kwargs)
self.dense_1 = layers.Dense(64, activation='relu')
self.dense_2 = layers.Dense(10)
def call(self, inputs):
x = self.dense_1(inputs)
return self.dense_2(x)
# Instantiate the model.
mlp = MLP()
# Necessary to create the model's state.
# The model doesn't have a state until it's called at least once.
_ = mlp(tf.zeros((1, 32)))
```
#### Model validation while defining its connectivity graph
In the functional API, the input specification (shape and dtype) is created
in advance (using `Input`). Every time you call a layer,
the layer checks that the specification passed to it matches its assumptions,
and it will raise a helpful error message if not.
This guarantees that any model you can build with the functional API will run.
All debugging -- other than convergence-related debugging --
happens statically during the model construction and not at execution time.
This is similar to type checking in a compiler.
#### A functional model is plottable and inspectable
You can plot the model as a graph, and you can easily access intermediate nodes
in this graph. For example, to extract and reuse the activations of intermediate
layers (as seen in a previous example):
```python
features_list = [layer.output for layer in vgg19.layers]
feat_extraction_model = keras.Model(inputs=vgg19.input, outputs=features_list)
```
#### A functional model can be serialized or cloned
Because a functional model is a data structure rather than a piece of code,
it is safely serializable and can be saved as a single file
that allows you to recreate the exact same model
without having access to any of the original code.
See the [serialization & saving guide](https://www.tensorflow.org/guide/keras/save_and_serialize/).
To serialize a subclassed model, it is necessary for the implementer
to specify a `get_config()`
and `from_config()` method at the model level.
### Functional API weakness:
#### It does not support dynamic architectures
The functional API treats models as DAGs of layers.
This is true for most deep learning architectures, but not all -- for example,
recursive networks or Tree RNNs do not follow this assumption and cannot
be implemented in the functional API.
## Mix-and-match API styles
Choosing between the functional API or Model subclassing isn't a
binary decision that restricts you into one category of models.
All models in the `tf.keras` API can interact with each other, whether they're
`Sequential` models, functional models, or subclassed models that are written
from scratch.
You can always use a functional model or `Sequential` model
as part of a subclassed model or layer:
```
units = 32
timesteps = 10
input_dim = 5
# Define a Functional model
inputs = keras.Input((None, units))
x = layers.GlobalAveragePooling1D()(inputs)
outputs = layers.Dense(1)(x)
model = keras.Model(inputs, outputs)
class CustomRNN(layers.Layer):
def __init__(self):
super(CustomRNN, self).__init__()
self.units = units
self.projection_1 = layers.Dense(units=units, activation="tanh")
self.projection_2 = layers.Dense(units=units, activation="tanh")
# Our previously-defined Functional model
self.classifier = model
def call(self, inputs):
outputs = []
state = tf.zeros(shape=(inputs.shape[0], self.units))
for t in range(inputs.shape[1]):
x = inputs[:, t, :]
h = self.projection_1(x)
y = h + self.projection_2(state)
state = y
outputs.append(y)
features = tf.stack(outputs, axis=1)
print(features.shape)
return self.classifier(features)
rnn_model = CustomRNN()
_ = rnn_model(tf.zeros((1, timesteps, input_dim)))
```
You can use any subclassed layer or model in the functional API
as long as it implements a `call` method that follows one of the following patterns:
- `call(self, inputs, **kwargs)` --
Where `inputs` is a tensor or a nested structure of tensors (e.g. a list of tensors),
and where `**kwargs` are non-tensor arguments (non-inputs).
- `call(self, inputs, training=None, **kwargs)` --
Where `training` is a boolean indicating whether the layer should behave
in training mode and inference mode.
- `call(self, inputs, mask=None, **kwargs)` --
Where `mask` is a boolean mask tensor (useful for RNNs, for instance).
- `call(self, inputs, training=None, mask=None, **kwargs)` --
Of course, you can have both masking and training-specific behavior at the same time.
Additionally, if you implement the `get_config` method on your custom Layer or model,
the functional models you create will still be serializable and cloneable.
Here's a quick example of a custom RNN, written from scratch,
being used in a functional model:
```
units = 32
timesteps = 10
input_dim = 5
batch_size = 16
class CustomRNN(layers.Layer):
def __init__(self):
super(CustomRNN, self).__init__()
self.units = units
self.projection_1 = layers.Dense(units=units, activation="tanh")
self.projection_2 = layers.Dense(units=units, activation="tanh")
self.classifier = layers.Dense(1)
def call(self, inputs):
outputs = []
state = tf.zeros(shape=(inputs.shape[0], self.units))
for t in range(inputs.shape[1]):
x = inputs[:, t, :]
h = self.projection_1(x)
y = h + self.projection_2(state)
state = y
outputs.append(y)
features = tf.stack(outputs, axis=1)
return self.classifier(features)
# Note that you specify a static batch size for the inputs with the `batch_shape`
# arg, because the inner computation of `CustomRNN` requires a static batch size
# (when you create the `state` zeros tensor).
inputs = keras.Input(batch_shape=(batch_size, timesteps, input_dim))
x = layers.Conv1D(32, 3)(inputs)
outputs = CustomRNN()(x)
model = keras.Model(inputs, outputs)
rnn_model = CustomRNN()
_ = rnn_model(tf.zeros((1, 10, 5)))
```
| github_jupyter |
<a href="https://colab.research.google.com/github/tbeucler/2022_ML_Earth_Env_Sci/blob/main/Lab_Notebooks/Week_5_Artificial_Neural_Networks.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# **Welcome to the fifth lab: Artificial Neural Networks and Surrogate Modeling**
For this week's lab, the learning objectives are:
1. Training artificial neural networks using [`Keras`](https://keras.io/)'s sequential and functional Application Programming Interfaces.
2. Normalizing your input data to facilitate deep learning.
3. Implementing callbacks to improve performance and avoid overfitting.
Today's tutorial:
1. Adapts Géron et al.'s Jupyter notebook exercises for chapters [10](https://github.com/ageron/handson-ml2/blob/master/10_neural_nets_with_keras.ipynb) [(License)](https://github.com/ageron/handson-ml2/blob/master/LICENSE) of his book ["Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition"](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/),
2. Adapts three articles on climate modeling from [Gentine et al.](https://agupubs.onlinelibrary.wiley.com/doi/full/10.1029/2018GL078202), [Rasp et al.](https://www.pnas.org/doi/10.1073/pnas.1810286115), and [Beucler et al.](https://arxiv.org/pdf/2112.08440), and Python scripts from [Stephan Rasp](https://github.com/raspstephan/CBRAIN-CAM) and [Tom Beucler](https://github.com/tbeucler/CBRAIN-CAM/blob/master/Climate_Invariant_Guide.ipynb).
If you are struggling with some of the exercises, do not hesitate to:
* Use a direct Internet search, or [stackoverflow](https://stackoverflow.com/)
* Ask your neighbor(s), the teacher, or the TA for help
* Debug your program, e.g. by following [this tutorial](https://swcarpentry.github.io/python-novice-inflammation/11-debugging/index.html)
* Use assertions, e.g. by following [this tutorial](https://swcarpentry.github.io/python-novice-inflammation/10-defensive/index.html)
# Part I: Practice on Simple Datasets
---
Go to notebook [`S5_1_NNs_with_Keras`](https://colab.research.google.com/github/tbeucler/2022_ML_Earth_Env_Sci/blob/main/Lab_Notebooks/S5_1_NNs_with_Keras.ipynb)
---
# Part II: Application to the Emulation of Atmospheric Convection for Climate Modeling
---
Go to notebook [`S5_2_ANNs_for_Climate`](https://colab.research.google.com/github/tbeucler/2022_ML_Earth_Env_Sci/blob/main/Lab_Notebooks/S5_2_ANNs_for_Climate.ipynb)
---
# You're flying high! ⛈🌧 😃 🌧⛈
You've reached the end of week 5's lab. If you're done early, consider:
* Giving feedback on how to improve this notebook (typos, hints, exercises that may be improved/removed/added, etc.) by messaging the teacher and TA(s) on Moodle
* Working on your final project for this course.
**Final Project**
The final project’s goal is to answer a well-defined scientific question by applying one of the ML algorithms introduced in class on an environmental dataset of your choice (e.g., related to your Masters thesis or your PhD research).
* Now that you found a large environmental dataset linked to a scientific question you are passionate about, which machine learning algorithm can you use to address it? Is it a classification, a regression, or a data exploration project?
* How could you format the dataset to facilitate its manipulation in Python?
* If you're still hunting for a dataset of interest, consider browsing the [list of benchmark datasets](http://mldata.pangeo.io/index.html) maintained by [Pangeo](https://pangeo.io/) and [Kaggle](https://www.kaggle.com/datasets).
```
```
| github_jupyter |
```
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pickle
tf.test.is_gpu_available()
def show_images(images, nrof_columns):
batch, width, height, depth = images.shape
nrof_rows = int(np.ceil(batch/nrof_columns))
out = np.zeros((nrof_rows*height, nrof_columns*width, depth), dtype=np.float32)
for i in range(batch):
x = i % nrof_columns
y = i // nrof_columns
out[y*height:(y+1)*height,x*width:(x+1)*width,:] = images[i,:,:,:]
out[0::height,:,:] = 1.0
out[:,0::width,:] = 1.0
out[1::height,:,:] = 1.0
out[:,1::width,:] = 1.0
plt.imshow(out)
with open('hw3-q2.pkl', 'rb') as f:
x = pickle.load(f)
plt.figure(figsize=(16,8))
show_images(x['train'][:32,...]/256, 8)
def softlimit(x, limit=0.1):
return tf.math.log(tf.math.exp(x) + 1.0 + limit)
def dense(x, nrof_units, activation=None, training=True, use_batch_norm=False):
x = tf.compat.v1.layers.Flatten()(x)
x = tf.compat.v1.layers.Dense(units=nrof_units)(x)
if use_batch_norm:
x = tf.compat.v1.layers.BatchNormalization()(x, training=training)
x = x if activation is None else activation(x)
return x
def mlp(x, nrof_units, activation, nrof_layers=1, training=True):
for _ in range(nrof_layers):
x = dense(x, nrof_units=nrof_units, activation=activation, training=training)
return x
def sample(mu, sigma):
epsilon = tf.random.normal(tf.shape(sigma), mean=0.0, stddev=1.0)
return mu + sigma*epsilon
def log_normal(x, mean, log_var, eps=1e-5):
with tf.variable_scope('log_normal'):
c = - 0.5 * np.log(2*np.pi)
return c - log_var/2 - (x - mean)**2 / (2 * tf.math.exp(log_var) + eps)
def get_warmup_temp(epoch, nrof_warmup_epochs):
if nrof_warmup_epochs>0:
temp = np.minimum(1.0, 1.0/nrof_warmup_epochs * (epoch-1))
else:
temp = 1.0
return temp
def gated_shortcut_connection(x):
nrof_filters = 64
b = tf.get_variable('b', shape=(nrof_filters,), dtype=tf.float32)
c = tf.get_variable('c', shape=(nrof_filters,), dtype=tf.float32)
## Add parameter sharing between convolutions!!!!
x_a = tf.layers.conv2d(x, filters=nrof_filters, kernel_size=(4, 4), strides=(1, 1), padding='same', name='conv_a') + b
x_b = tf.layers.conv2d(x, filters=nrof_filters, kernel_size=(4, 4), strides=(1, 1), padding='same', name='conv_b') + c
y = x_a * tf.nn.sigmoid(x_b)
return y
def residual_stack(x, scope):
with tf.variable_scope(scope):
for i in range(5):
x = tf.nn.relu(x)
x = tf.layers.conv2d(x, filters=64, kernel_size=(3, 3), strides=(1, 1), padding='same')
x = tf.nn.relu(x)
x = tf.layers.conv2d(x, filters=64*2, kernel_size=(3, 3), strides=(1, 1), padding='same')
#with tf.variable_scope('gated_shortcut_%d' % i):
# x = gated_shortcut_connection(x)
x = tf.nn.relu(x)
return x
def create_dataset(x, batch_size):
dataset = tf.data.Dataset.from_tensor_slices(x)
dataset = dataset.repeat() # Repeat the dataset indefinitely
dataset = dataset.shuffle(10000) # Shuffle the data
dataset = dataset.batch(batch_size) # Create batches of data
dataset = dataset.prefetch(batch_size) # Prefetch data for faster consumption
iterator = tf.compat.v1.data.make_initializable_iterator(dataset) # Create an iterator over the dataset
return iterator
def vae(x, temp, latent_nrof_channels, is_training):
dbg = dict()
dbg['x'] = x
h = x
with tf.variable_scope('encoder'):
h = tf.layers.conv2d(h, filters=128, kernel_size=(4, 4), strides=(2, 2), padding='same')
h = tf.nn.relu(h)
h = tf.layers.conv2d(h, filters=256, kernel_size=(4, 4), strides=(2, 2), padding='same')
h = tf.nn.relu(h)
h = tf.layers.conv2d(h, filters=256, kernel_size=(3, 3), strides=(1, 1), padding='same')
h = residual_stack(h, 'res_stack')
q_mu = tf.layers.conv2d(h, filters=latent_nrof_channels, kernel_size=(1, 1), strides=(1, 1), padding='same')
q_sigma = softlimit(tf.layers.conv2d(h, filters=latent_nrof_channels, kernel_size=(1, 1), strides=(1, 1), padding='same'))
dbg['q_mu'] = q_mu
dbg['q_sigma'] = q_sigma
with tf.variable_scope('decoder'):
z = sample(q_mu, q_sigma)
dbg['z'] = z
h = z
print('q_mu', q_mu)
print('h', h)
h = tf.layers.conv2d(h, filters=256, kernel_size=(3, 3), strides=(1, 1), padding='same')
h = residual_stack(h, 'res_stack')
h = tf.layers.conv2d_transpose(h, filters=128, kernel_size=(4, 4), strides=(2, 2), padding='same')
h = tf.nn.relu(h)
h = tf.layers.conv2d_transpose(h, filters=128, kernel_size=(4, 4), strides=(2, 2), padding='same')
x_rec_mu = tf.layers.conv2d(h, filters=3, kernel_size=(1, 1), strides=(1, 1), padding='same')
x_rec_sigma = softlimit(tf.layers.conv2d(h, filters=3, kernel_size=(1, 1), strides=(1, 1), padding='same'))
dbg['x_rec_mu'] = x_rec_mu
dbg['x_rec_sigma'] = x_rec_sigma
with tf.variable_scope('rec_loss'):
log_pxz = log_normal(x, x_rec_mu, tf.math.log(x_rec_sigma)*2)
dbg['log_pxz'] = tf.reduce_mean(log_pxz) * np.log2(np.e)
with tf.variable_scope('reg_loss'):
p_mu, p_sigma = tf.zeros_like(q_mu), tf.ones_like(q_sigma)
log_qz = log_normal(z, q_mu, tf.math.log(q_sigma)*2)
log_pz = log_normal(z, p_mu, tf.math.log(p_sigma)*2)
dbg['log_pzx'] = tf.reduce_mean(log_pz - log_qz) * np.log2(np.e)
with tf.variable_scope('elbo'):
print('log_pxz', log_pxz)
print('log_qz', log_qz)
elbo = (tf.reduce_mean(log_pxz) + temp*tf.reduce_mean(log_pz-log_qz)) * np.log2(np.e)
dbg['elbo'] = elbo
loss = -elbo
return loss, dbg
def evaluate(dbg, input_ph, x, batch_size=256):
elbo_list, log_pxz_list, log_pzx_list = [], [], []
nrof_batches = int(np.ceil(x.shape[0] / batch_size))
for i in range(nrof_batches):
batch_start = i*batch_size
batch_end = np.minimum(batch_start+batch_size, x.shape[0])
dbg_ = sess.run(dbg, feed_dict={input_ph:x[batch_start:batch_end,...], temp_ph:1.0})
elbo_list += [ dbg_['elbo'] ]
log_pxz_list += [ dbg_['log_pxz'] ]
log_pzx_list += [ dbg_['log_pzx'] ]
return np.mean(elbo_list), np.mean(log_pxz_list), np.mean(log_pzx_list)
nrof_epochs = 50
batch_size = 128
nrof_warmup_epochs = 10
latent_nrof_channels = 8
tf.set_random_seed(42)
np.random.seed(42)
tf.reset_default_graph()
with tf.Graph().as_default():
train_iterator = create_dataset(x['train'].astype(np.float32)/256, batch_size)
eval_input_ph = tf.placeholder(tf.float32, shape=(None,32,32,3))
temp_ph = tf.placeholder(tf.float32, shape=())
with tf.variable_scope('model', reuse=False):
train_loss, train_dbg = vae(train_iterator.get_next(), temp_ph, latent_nrof_channels=latent_nrof_channels, is_training=True)
with tf.variable_scope('model', reuse=True):
_, eval_dbg = vae(eval_input_ph, temp_ph, latent_nrof_channels=latent_nrof_channels, is_training=False)
optimizer = tf.train.AdamOptimizer(learning_rate=0.0001)
train_op = optimizer.minimize(train_loss)
sess = tf.compat.v1.InteractiveSession()
sess.run(tf.compat.v1.global_variables_initializer())
sess.run(train_iterator.initializer)
nrof_batches = x['train'].shape[0] // batch_size
train_elbo_list, train_log_pxz_list, train_log_pzx_list = [], [], []
eval_elbo_list, eval_log_pxz_list, eval_log_pzx_list = [], [], []
for epoch in range(1, nrof_epochs+1):
temp = get_warmup_temp(epoch, nrof_warmup_epochs)
for i in range(nrof_batches):
_, loss_, dbg_ = sess.run([train_op, train_loss, train_dbg], feed_dict={temp_ph:temp})
train_elbo_list += [ dbg_['elbo'] ]
train_log_pxz_list += [ dbg_['log_pxz'] ]
train_log_pzx_list += [ dbg_['log_pzx'] ]
if i % 25 == 0:
print('train epoch: %4d batch: %4d temp: %7.3f elbo: %7.3f p(x|z): %7.3f p(z|x): %7.3f' % (
epoch, i, temp, dbg_['elbo'], dbg_['log_pxz'], dbg_['log_pzx']))
elbo, log_pxz, log_pzx = evaluate(eval_dbg, eval_input_ph, x['valid'].astype(np.float32)/256)
print('val epoch: %4d elbo: %7.3f p(x|z): %7.3f p(z|x): %7.3f' % (epoch, elbo, log_pxz, log_pzx))
eval_elbo_list += [ elbo ]
eval_log_pxz_list += [ log_pxz ]
eval_log_pzx_list += [ log_pzx ]
elbo, log_pxz, log_pzx = evaluate(eval_dbg, eval_input_ph, x['test'].astype(np.float32)/256)
print('test epoch: %4d elbo: %7.3f p(x|z): %7.3f p(z|x): %7.3f' % (epoch, elbo, log_pxz, log_pzx))
# 30 epochs
#train epoch: 30 batch: 500 temp: 1.000 elbo: 1.657 p(x|z): 1.813 p(z|x): -0.156
#val epoch: 30 elbo: 1.633 p(x|z): 1.789 p(z|x): -0.157
#test epoch: 30 elbo: 1.630 p(x|z): 1.798 p(z|x): -0.168
z_ = np.random.randn(32,8,8,latent_nrof_channels)
x_ = np.zeros((32,32,32,3))
x_rec_ = sess.run(eval_dbg['x_rec_mu'], feed_dict={eval_dbg['z']:z_, eval_dbg['x']:x_})
plt.figure(figsize=(16,8))
show_images(x_rec_, 8)
plt.plot(train_elbo_list)
plt.plot(train_log_pxz_list)
plt.plot(train_log_pzx_list)
plt.ylim((-4.0, 2.0))
plt.title('Training loss [bits/dim]')
plt.xlabel('Training step')
plt.legend(['ELBO', 'p(x|z)', 'p(z|x)'])
_ = plt.ylabel('Negative Log Likelihood')
```
| github_jupyter |
# TF-Slim Walkthrough
This notebook will walk you through the basics of using TF-Slim to define, train and evaluate neural networks on various tasks. It assumes a basic knowledge of neural networks.
## Table of contents
<a href="#Install">Installation and setup</a><br>
<a href='#MLP'>Creating your first neural network with TF-Slim</a><br>
<a href='#ReadingTFSlimDatasets'>Reading Data with TF-Slim</a><br>
<a href='#CNN'>Training a convolutional neural network (CNN)</a><br>
<a href='#Pretained'>Using pre-trained models</a><br>
## Installation and setup
<a id='Install'></a>
Since the stable release of TF 1.0, the latest version of slim has been available as `tf.contrib.slim`.
To test that your installation is working, execute the following command; it should run without raising any errors.
```
python -c "import tensorflow.contrib.slim as slim; eval = slim.evaluation.evaluate_once"
```
Although, to use TF-Slim for image classification (as we do in this notebook), you also have to install the TF-Slim image models library from [here](https://github.com/tensorflow/models/tree/master/slim). Let's suppose you install this into a directory called TF_MODELS. Then you should change directory to TF_MODELS/slim **before** running this notebook, so that these files are in your python path.
To check you've got these two steps to work, just execute the cell below. If it complains about unknown modules, restart the notebook after moving to the TF-Slim models directory.
```
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
import math
import numpy as np
import tensorflow as tf
import time
from datasets import dataset_utils
# Main slim library
from tensorflow.contrib import slim
```
## Creating your first neural network with TF-Slim
<a id='MLP'></a>
Below we give some code to create a simple multilayer perceptron (MLP) which can be used
for regression problems. The model has 2 hidden layers.
The output is a single node.
When this function is called, it will create various nodes, and silently add them to whichever global TF graph is currently in scope. When a node which corresponds to a layer with adjustable parameters (eg., a fully connected layer) is created, additional parameter variable nodes are silently created, and added to the graph. (We will discuss how to train the parameters later.)
We use variable scope to put all the nodes under a common name,
so that the graph has some hierarchical structure.
This is useful when we want to visualize the TF graph in tensorboard, or if we want to query related
variables.
The fully connected layers all use the same L2 weight decay and ReLu activations, as specified by **arg_scope**. (However, the final layer overrides these defaults, and uses an identity activation function.)
We also illustrate how to add a dropout layer after the first fully connected layer (FC1). Note that at test time,
we do not drop out nodes, but instead use the average activations; hence we need to know whether the model is being
constructed for training or testing, since the computational graph will be different in the two cases
(although the variables, storing the model parameters, will be shared, since they have the same name/scope).
```
def regression_model(inputs, is_training=True, scope="deep_regression"):
"""Creates the regression model.
Args:
inputs: A node that yields a `Tensor` of size [batch_size, dimensions].
is_training: Whether or not we're currently training the model.
scope: An optional variable_op scope for the model.
Returns:
predictions: 1-D `Tensor` of shape [batch_size] of responses.
end_points: A dict of end points representing the hidden layers.
"""
with tf.variable_scope(scope, 'deep_regression', [inputs]):
end_points = {}
# Set the default weight _regularizer and acvitation for each fully_connected layer.
with slim.arg_scope([slim.fully_connected],
activation_fn=tf.nn.relu,
weights_regularizer=slim.l2_regularizer(0.01)):
# Creates a fully connected layer from the inputs with 32 hidden units.
net = slim.fully_connected(inputs, 32, scope='fc1')
end_points['fc1'] = net
# Adds a dropout layer to prevent over-fitting.
net = slim.dropout(net, 0.8, is_training=is_training)
# Adds another fully connected layer with 16 hidden units.
net = slim.fully_connected(net, 16, scope='fc2')
end_points['fc2'] = net
# Creates a fully-connected layer with a single hidden unit. Note that the
# layer is made linear by setting activation_fn=None.
predictions = slim.fully_connected(net, 1, activation_fn=None, scope='prediction')
end_points['out'] = predictions
return predictions, end_points
```
### Let's create the model and examine its structure.
We create a TF graph and call regression_model(), which adds nodes (tensors) to the graph. We then examine their shape, and print the names of all the model variables which have been implicitly created inside of each layer. We see that the names of the variables follow the scopes that we specified.
```
with tf.Graph().as_default():
# Dummy placeholders for arbitrary number of 1d inputs and outputs
inputs = tf.placeholder(tf.float32, shape=(None, 1))
outputs = tf.placeholder(tf.float32, shape=(None, 1))
# Build model
predictions, end_points = regression_model(inputs)
# Print name and shape of each tensor.
print("Layers")
for k, v in end_points.items():
print('name = {}, shape = {}'.format(v.name, v.get_shape()))
# Print name and shape of parameter nodes (values not yet initialized)
print("\n")
print("Parameters")
for v in slim.get_model_variables():
print('name = {}, shape = {}'.format(v.name, v.get_shape()))
```
### Let's create some 1d regression data .
We will train and test the model on some noisy observations of a nonlinear function.
```
def produce_batch(batch_size, noise=0.3):
xs = np.random.random(size=[batch_size, 1]) * 10
ys = np.sin(xs) + 5 + np.random.normal(size=[batch_size, 1], scale=noise)
return [xs.astype(np.float32), ys.astype(np.float32)]
x_train, y_train = produce_batch(200)
x_test, y_test = produce_batch(200)
plt.scatter(x_train, y_train)
```
### Let's fit the model to the data
The user has to specify the loss function and the optimizer, and slim does the rest.
In particular, the slim.learning.train function does the following:
- For each iteration, evaluate the train_op, which updates the parameters using the optimizer applied to the current minibatch. Also, update the global_step.
- Occasionally store the model checkpoint in the specified directory. This is useful in case your machine crashes - then you can simply restart from the specified checkpoint.
```
def convert_data_to_tensors(x, y):
inputs = tf.constant(x)
inputs.set_shape([None, 1])
outputs = tf.constant(y)
outputs.set_shape([None, 1])
return inputs, outputs
# The following snippet trains the regression model using a mean_squared_error loss.
ckpt_dir = '/tmp/regression_model/'
with tf.Graph().as_default():
tf.logging.set_verbosity(tf.logging.INFO)
inputs, targets = convert_data_to_tensors(x_train, y_train)
# Make the model.
predictions, nodes = regression_model(inputs, is_training=True)
# Add the loss function to the graph.
loss = tf.losses.mean_squared_error(labels=targets, predictions=predictions)
# The total loss is the uers's loss plus any regularization losses.
total_loss = slim.losses.get_total_loss()
# Specify the optimizer and create the train op:
optimizer = tf.train.AdamOptimizer(learning_rate=0.005)
train_op = slim.learning.create_train_op(total_loss, optimizer)
# Run the training inside a session.
final_loss = slim.learning.train(
train_op,
logdir=ckpt_dir,
number_of_steps=5000,
save_summaries_secs=5,
log_every_n_steps=500)
print("Finished training. Last batch loss:", final_loss)
print("Checkpoint saved in %s" % ckpt_dir)
```
### Training with multiple loss functions.
Sometimes we have multiple objectives we want to simultaneously optimize.
In slim, it is easy to add more losses, as we show below. (We do not optimize the total loss in this example,
but we show how to compute it.)
```
with tf.Graph().as_default():
inputs, targets = convert_data_to_tensors(x_train, y_train)
predictions, end_points = regression_model(inputs, is_training=True)
# Add multiple loss nodes.
mean_squared_error_loss = tf.losses.mean_squared_error(labels=targets, predictions=predictions)
absolute_difference_loss = slim.losses.absolute_difference(predictions, targets)
# The following two ways to compute the total loss are equivalent
regularization_loss = tf.add_n(slim.losses.get_regularization_losses())
total_loss1 = mean_squared_error_loss + absolute_difference_loss + regularization_loss
# Regularization Loss is included in the total loss by default.
# This is good for training, but not for testing.
total_loss2 = slim.losses.get_total_loss(add_regularization_losses=True)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op) # Will initialize the parameters with random weights.
total_loss1, total_loss2 = sess.run([total_loss1, total_loss2])
print('Total Loss1: %f' % total_loss1)
print('Total Loss2: %f' % total_loss2)
print('Regularization Losses:')
for loss in slim.losses.get_regularization_losses():
print(loss)
print('Loss Functions:')
for loss in slim.losses.get_losses():
print(loss)
```
### Let's load the saved model and use it for prediction.
```
with tf.Graph().as_default():
inputs, targets = convert_data_to_tensors(x_test, y_test)
# Create the model structure. (Parameters will be loaded below.)
predictions, end_points = regression_model(inputs, is_training=False)
# Make a session which restores the old parameters from a checkpoint.
sv = tf.train.Supervisor(logdir=ckpt_dir)
with sv.managed_session() as sess:
inputs, predictions, targets = sess.run([inputs, predictions, targets])
plt.scatter(inputs, targets, c='r');
plt.scatter(inputs, predictions, c='b');
plt.title('red=true, blue=predicted')
```
### Let's compute various evaluation metrics on the test set.
In TF-Slim termiology, losses are optimized, but metrics (which may not be differentiable, e.g., precision and recall) are just measured. As an illustration, the code below computes mean squared error and mean absolute error metrics on the test set.
Each metric declaration creates several local variables (which must be initialized via tf.initialize_local_variables()) and returns both a value_op and an update_op. When evaluated, the value_op returns the current value of the metric. The update_op loads a new batch of data, runs the model, obtains the predictions and accumulates the metric statistics appropriately before returning the current value of the metric. We store these value nodes and update nodes in 2 dictionaries.
After creating the metric nodes, we can pass them to slim.evaluation.evaluation, which repeatedly evaluates these nodes the specified number of times. (This allows us to compute the evaluation in a streaming fashion across minibatches, which is usefulf for large datasets.) Finally, we print the final value of each metric.
```
with tf.Graph().as_default():
inputs, targets = convert_data_to_tensors(x_test, y_test)
predictions, end_points = regression_model(inputs, is_training=False)
# Specify metrics to evaluate:
names_to_value_nodes, names_to_update_nodes = slim.metrics.aggregate_metric_map({
'Mean Squared Error': slim.metrics.streaming_mean_squared_error(predictions, targets),
'Mean Absolute Error': slim.metrics.streaming_mean_absolute_error(predictions, targets)
})
# Make a session which restores the old graph parameters, and then run eval.
sv = tf.train.Supervisor(logdir=ckpt_dir)
with sv.managed_session() as sess:
metric_values = slim.evaluation.evaluation(
sess,
num_evals=1, # Single pass over data
eval_op=names_to_update_nodes.values(),
final_op=names_to_value_nodes.values())
names_to_values = dict(zip(names_to_value_nodes.keys(), metric_values))
for key, value in names_to_values.items():
print('%s: %f' % (key, value))
```
# Reading Data with TF-Slim
<a id='ReadingTFSlimDatasets'></a>
Reading data with TF-Slim has two main components: A
[Dataset](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/slim/python/slim/data/dataset.py) and a
[DatasetDataProvider](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/slim/python/slim/data/dataset_data_provider.py). The former is a descriptor of a dataset, while the latter performs the actions necessary for actually reading the data. Lets look at each one in detail:
## Dataset
A TF-Slim
[Dataset](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/slim/python/slim/data/dataset.py)
contains descriptive information about a dataset necessary for reading it, such as the list of data files and how to decode them. It also contains metadata including class labels, the size of the train/test splits and descriptions of the tensors that the dataset provides. For example, some datasets contain images with labels. Others augment this data with bounding box annotations, etc. The Dataset object allows us to write generic code using the same API, regardless of the data content and encoding type.
TF-Slim's Dataset works especially well when the data is stored as a (possibly sharded)
[TFRecords file](https://www.tensorflow.org/versions/r0.10/how_tos/reading_data/index.html#file-formats), where each record contains a [tf.train.Example protocol buffer](https://github.com/tensorflow/tensorflow/blob/r0.10/tensorflow/core/example/example.proto).
TF-Slim uses a consistent convention for naming the keys and values inside each Example record.
## DatasetDataProvider
A
[DatasetDataProvider](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/slim/python/slim/data/dataset_data_provider.py) is a class which actually reads the data from a dataset. It is highly configurable to read the data in various ways that may make a big impact on the efficiency of your training process. For example, it can be single or multi-threaded. If your data is sharded across many files, it can read each files serially, or from every file simultaneously.
## Demo: The Flowers Dataset
For convenience, we've include scripts to convert several common image datasets into TFRecord format and have provided
the Dataset descriptor files necessary for reading them. We demonstrate how easy it is to use these dataset via the Flowers dataset below.
### Download the Flowers Dataset
<a id='DownloadFlowers'></a>
We've made available a tarball of the Flowers dataset which has already been converted to TFRecord format.
```
import tensorflow as tf
from datasets import dataset_utils
url = "http://download.tensorflow.org/data/flowers.tar.gz"
flowers_data_dir = '/tmp/flowers'
if not tf.gfile.Exists(flowers_data_dir):
tf.gfile.MakeDirs(flowers_data_dir)
dataset_utils.download_and_uncompress_tarball(url, flowers_data_dir)
```
### Display some of the data.
```
from datasets import flowers
import tensorflow as tf
from tensorflow.contrib import slim
with tf.Graph().as_default():
dataset = flowers.get_split('train', flowers_data_dir)
data_provider = slim.dataset_data_provider.DatasetDataProvider(
dataset, common_queue_capacity=32, common_queue_min=1)
image, label = data_provider.get(['image', 'label'])
with tf.Session() as sess:
with slim.queues.QueueRunners(sess):
for i in range(4):
np_image, np_label = sess.run([image, label])
height, width, _ = np_image.shape
class_name = name = dataset.labels_to_names[np_label]
plt.figure()
plt.imshow(np_image)
plt.title('%s, %d x %d' % (name, height, width))
plt.axis('off')
plt.show()
```
# Convolutional neural nets (CNNs).
<a id='CNN'></a>
In this section, we show how to train an image classifier using a simple CNN.
### Define the model.
Below we define a simple CNN. Note that the output layer is linear function - we will apply softmax transformation externally to the model, either in the loss function (for training), or in the prediction function (during testing).
```
def my_cnn(images, num_classes, is_training): # is_training is not used...
with slim.arg_scope([slim.max_pool2d], kernel_size=[3, 3], stride=2):
net = slim.conv2d(images, 64, [5, 5])
net = slim.max_pool2d(net)
net = slim.conv2d(net, 64, [5, 5])
net = slim.max_pool2d(net)
net = slim.flatten(net)
net = slim.fully_connected(net, 192)
net = slim.fully_connected(net, num_classes, activation_fn=None)
return net
```
### Apply the model to some randomly generated images.
```
import tensorflow as tf
with tf.Graph().as_default():
# The model can handle any input size because the first layer is convolutional.
# The size of the model is determined when image_node is first passed into the my_cnn function.
# Once the variables are initialized, the size of all the weight matrices is fixed.
# Because of the fully connected layers, this means that all subsequent images must have the same
# input size as the first image.
batch_size, height, width, channels = 3, 28, 28, 3
images = tf.random_uniform([batch_size, height, width, channels], maxval=1)
# Create the model.
num_classes = 10
logits = my_cnn(images, num_classes, is_training=True)
probabilities = tf.nn.softmax(logits)
# Initialize all the variables (including parameters) randomly.
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
# Run the init_op, evaluate the model outputs and print the results:
sess.run(init_op)
probabilities = sess.run(probabilities)
print('Probabilities Shape:')
print(probabilities.shape) # batch_size x num_classes
print('\nProbabilities:')
print(probabilities)
print('\nSumming across all classes (Should equal 1):')
print(np.sum(probabilities, 1)) # Each row sums to 1
```
### Train the model on the Flowers dataset.
Before starting, make sure you've run the code to <a href="#DownloadFlowers">Download the Flowers</a> dataset. Now, we'll get a sense of what it looks like to use TF-Slim's training functions found in
[learning.py](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/slim/python/slim/learning.py). First, we'll create a function, `load_batch`, that loads batches of dataset from a dataset. Next, we'll train a model for a single step (just to demonstrate the API), and evaluate the results.
```
from preprocessing import inception_preprocessing
import tensorflow as tf
from tensorflow.contrib import slim
def load_batch(dataset, batch_size=32, height=299, width=299, is_training=False):
"""Loads a single batch of data.
Args:
dataset: The dataset to load.
batch_size: The number of images in the batch.
height: The size of each image after preprocessing.
width: The size of each image after preprocessing.
is_training: Whether or not we're currently training or evaluating.
Returns:
images: A Tensor of size [batch_size, height, width, 3], image samples that have been preprocessed.
images_raw: A Tensor of size [batch_size, height, width, 3], image samples that can be used for visualization.
labels: A Tensor of size [batch_size], whose values range between 0 and dataset.num_classes.
"""
data_provider = slim.dataset_data_provider.DatasetDataProvider(
dataset, common_queue_capacity=32,
common_queue_min=8)
image_raw, label = data_provider.get(['image', 'label'])
# Preprocess image for usage by Inception.
image = inception_preprocessing.preprocess_image(image_raw, height, width, is_training=is_training)
# Preprocess the image for display purposes.
image_raw = tf.expand_dims(image_raw, 0)
image_raw = tf.image.resize_images(image_raw, [height, width])
image_raw = tf.squeeze(image_raw)
# Batch it up.
images, images_raw, labels = tf.train.batch(
[image, image_raw, label],
batch_size=batch_size,
num_threads=1,
capacity=2 * batch_size)
return images, images_raw, labels
from datasets import flowers
# This might take a few minutes.
train_dir = '/tmp/tfslim_model/'
print('Will save model to %s' % train_dir)
with tf.Graph().as_default():
tf.logging.set_verbosity(tf.logging.INFO)
dataset = flowers.get_split('train', flowers_data_dir)
images, _, labels = load_batch(dataset)
# Create the model:
logits = my_cnn(images, num_classes=dataset.num_classes, is_training=True)
# Specify the loss function:
one_hot_labels = slim.one_hot_encoding(labels, dataset.num_classes)
slim.losses.softmax_cross_entropy(logits, one_hot_labels)
total_loss = slim.losses.get_total_loss()
# Create some summaries to visualize the training process:
tf.summary.scalar('losses/Total Loss', total_loss)
# Specify the optimizer and create the train op:
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = slim.learning.create_train_op(total_loss, optimizer)
# Run the training:
final_loss = slim.learning.train(
train_op,
logdir=train_dir,
number_of_steps=1, # For speed, we just do 1 epoch
save_summaries_secs=1)
print('Finished training. Final batch loss %d' % final_loss)
```
### Evaluate some metrics.
As we discussed above, we can compute various metrics besides the loss.
Below we show how to compute prediction accuracy of the trained model, as well as top-5 classification accuracy. (The difference between evaluation and evaluation_loop is that the latter writes the results to a log directory, so they can be viewed in tensorboard.)
```
from datasets import flowers
# This might take a few minutes.
with tf.Graph().as_default():
tf.logging.set_verbosity(tf.logging.DEBUG)
dataset = flowers.get_split('train', flowers_data_dir)
images, _, labels = load_batch(dataset)
logits = my_cnn(images, num_classes=dataset.num_classes, is_training=False)
predictions = tf.argmax(logits, 1)
# Define the metrics:
names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({
'eval/Accuracy': slim.metrics.streaming_accuracy(predictions, labels),
'eval/Recall@5': slim.metrics.streaming_recall_at_k(logits, labels, 5),
})
print('Running evaluation Loop...')
checkpoint_path = tf.train.latest_checkpoint(train_dir)
metric_values = slim.evaluation.evaluate_once(
master='',
checkpoint_path=checkpoint_path,
logdir=train_dir,
eval_op=names_to_updates.values(),
final_op=names_to_values.values())
names_to_values = dict(zip(names_to_values.keys(), metric_values))
for name in names_to_values:
print('%s: %f' % (name, names_to_values[name]))
```
# Using pre-trained models
<a id='Pretrained'></a>
Neural nets work best when they have many parameters, making them very flexible function approximators.
However, this means they must be trained on big datasets. Since this process is slow, we provide various pre-trained models - see the list [here](https://github.com/tensorflow/models/tree/master/slim#pre-trained-models).
You can either use these models as-is, or you can perform "surgery" on them, to modify them for some other task. For example, it is common to "chop off" the final pre-softmax layer, and replace it with a new set of weights corresponding to some new set of labels. You can then quickly fine tune the new model on a small new dataset. We illustrate this below, using inception-v1 as the base model. While models like Inception V3 are more powerful, Inception V1 is used for speed purposes.
Take into account that VGG and ResNet final layers have only 1000 outputs rather than 1001. The ImageNet dataset provied has an empty background class which can be used to fine-tune the model to other tasks. VGG and ResNet models provided here don't use that class. We provide two examples of using pretrained models: Inception V1 and VGG-19 models to highlight this difference.
### Download the Inception V1 checkpoint
```
from datasets import dataset_utils
url = "http://download.tensorflow.org/models/inception_v1_2016_08_28.tar.gz"
checkpoints_dir = '/tmp/checkpoints'
if not tf.gfile.Exists(checkpoints_dir):
tf.gfile.MakeDirs(checkpoints_dir)
dataset_utils.download_and_uncompress_tarball(url, checkpoints_dir)
```
### Apply Pre-trained Inception V1 model to Images.
We have to convert each image to the size expected by the model checkpoint.
There is no easy way to determine this size from the checkpoint itself.
So we use a preprocessor to enforce this.
```
import numpy as np
import os
import tensorflow as tf
try:
import urllib2
except ImportError:
import urllib.request as urllib
from datasets import imagenet
from nets import inception
from preprocessing import inception_preprocessing
from tensorflow.contrib import slim
image_size = inception.inception_v1.default_image_size
with tf.Graph().as_default():
url = 'https://upload.wikimedia.org/wikipedia/commons/7/70/EnglishCockerSpaniel_simon.jpg'
image_string = urllib.urlopen(url).read()
image = tf.image.decode_jpeg(image_string, channels=3)
processed_image = inception_preprocessing.preprocess_image(image, image_size, image_size, is_training=False)
processed_images = tf.expand_dims(processed_image, 0)
# Create the model, use the default arg scope to configure the batch norm parameters.
with slim.arg_scope(inception.inception_v1_arg_scope()):
logits, _ = inception.inception_v1(processed_images, num_classes=1001, is_training=False)
probabilities = tf.nn.softmax(logits)
init_fn = slim.assign_from_checkpoint_fn(
os.path.join(checkpoints_dir, 'inception_v1.ckpt'),
slim.get_model_variables('InceptionV1'))
with tf.Session() as sess:
init_fn(sess)
np_image, probabilities = sess.run([image, probabilities])
probabilities = probabilities[0, 0:]
sorted_inds = [i[0] for i in sorted(enumerate(-probabilities), key=lambda x:x[1])]
plt.figure()
plt.imshow(np_image.astype(np.uint8))
plt.axis('off')
plt.show()
names = imagenet.create_readable_names_for_imagenet_labels()
for i in range(5):
index = sorted_inds[i]
print('Probability %0.2f%% => [%s]' % (probabilities[index] * 100, names[index]))
```
### Download the VGG-16 checkpoint
```
from datasets import dataset_utils
import tensorflow as tf
url = "http://download.tensorflow.org/models/vgg_16_2016_08_28.tar.gz"
checkpoints_dir = '/tmp/checkpoints'
if not tf.gfile.Exists(checkpoints_dir):
tf.gfile.MakeDirs(checkpoints_dir)
dataset_utils.download_and_uncompress_tarball(url, checkpoints_dir)
```
### Apply Pre-trained VGG-16 model to Images.
We have to convert each image to the size expected by the model checkpoint.
There is no easy way to determine this size from the checkpoint itself.
So we use a preprocessor to enforce this. Pay attention to the difference caused by 1000 classes instead of 1001.
```
import numpy as np
import os
import tensorflow as tf
try:
import urllib2
except ImportError:
import urllib.request as urllib
from datasets import imagenet
from nets import vgg
from preprocessing import vgg_preprocessing
from tensorflow.contrib import slim
image_size = vgg.vgg_16.default_image_size
with tf.Graph().as_default():
url = 'https://upload.wikimedia.org/wikipedia/commons/d/d9/First_Student_IC_school_bus_202076.jpg'
image_string = urllib.urlopen(url).read()
image = tf.image.decode_jpeg(image_string, channels=3)
processed_image = vgg_preprocessing.preprocess_image(image, image_size, image_size, is_training=False)
processed_images = tf.expand_dims(processed_image, 0)
# Create the model, use the default arg scope to configure the batch norm parameters.
with slim.arg_scope(vgg.vgg_arg_scope()):
# 1000 classes instead of 1001.
logits, _ = vgg.vgg_16(processed_images, num_classes=1000, is_training=False)
probabilities = tf.nn.softmax(logits)
init_fn = slim.assign_from_checkpoint_fn(
os.path.join(checkpoints_dir, 'vgg_16.ckpt'),
slim.get_model_variables('vgg_16'))
with tf.Session() as sess:
init_fn(sess)
np_image, probabilities = sess.run([image, probabilities])
probabilities = probabilities[0, 0:]
sorted_inds = [i[0] for i in sorted(enumerate(-probabilities), key=lambda x:x[1])]
plt.figure()
plt.imshow(np_image.astype(np.uint8))
plt.axis('off')
plt.show()
names = imagenet.create_readable_names_for_imagenet_labels()
for i in range(5):
index = sorted_inds[i]
# Shift the index of a class name by one.
print('Probability %0.2f%% => [%s]' % (probabilities[index] * 100, names[index+1]))
```
### Fine-tune the model on a different set of labels.
We will fine tune the inception model on the Flowers dataset.
```
# Note that this may take several minutes.
import os
from datasets import flowers
from nets import inception
from preprocessing import inception_preprocessing
from tensorflow.contrib import slim
image_size = inception.inception_v1.default_image_size
def get_init_fn():
"""Returns a function run by the chief worker to warm-start the training."""
checkpoint_exclude_scopes=["InceptionV1/Logits", "InceptionV1/AuxLogits"]
exclusions = [scope.strip() for scope in checkpoint_exclude_scopes]
variables_to_restore = []
for var in slim.get_model_variables():
excluded = False
for exclusion in exclusions:
if var.op.name.startswith(exclusion):
excluded = True
break
if not excluded:
variables_to_restore.append(var)
return slim.assign_from_checkpoint_fn(
os.path.join(checkpoints_dir, 'inception_v1.ckpt'),
variables_to_restore)
train_dir = '/tmp/inception_finetuned/'
with tf.Graph().as_default():
tf.logging.set_verbosity(tf.logging.INFO)
dataset = flowers.get_split('train', flowers_data_dir)
images, _, labels = load_batch(dataset, height=image_size, width=image_size)
# Create the model, use the default arg scope to configure the batch norm parameters.
with slim.arg_scope(inception.inception_v1_arg_scope()):
logits, _ = inception.inception_v1(images, num_classes=dataset.num_classes, is_training=True)
# Specify the loss function:
one_hot_labels = slim.one_hot_encoding(labels, dataset.num_classes)
slim.losses.softmax_cross_entropy(logits, one_hot_labels)
total_loss = slim.losses.get_total_loss()
# Create some summaries to visualize the training process:
tf.summary.scalar('losses/Total Loss', total_loss)
# Specify the optimizer and create the train op:
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = slim.learning.create_train_op(total_loss, optimizer)
# Run the training:
final_loss = slim.learning.train(
train_op,
logdir=train_dir,
init_fn=get_init_fn(),
number_of_steps=2)
print('Finished training. Last batch loss %f' % final_loss)
```
### Apply fine tuned model to some images.
```
import numpy as np
import tensorflow as tf
from datasets import flowers
from nets import inception
from tensorflow.contrib import slim
image_size = inception.inception_v1.default_image_size
batch_size = 3
with tf.Graph().as_default():
tf.logging.set_verbosity(tf.logging.INFO)
dataset = flowers.get_split('train', flowers_data_dir)
images, images_raw, labels = load_batch(dataset, height=image_size, width=image_size)
# Create the model, use the default arg scope to configure the batch norm parameters.
with slim.arg_scope(inception.inception_v1_arg_scope()):
logits, _ = inception.inception_v1(images, num_classes=dataset.num_classes, is_training=True)
probabilities = tf.nn.softmax(logits)
checkpoint_path = tf.train.latest_checkpoint(train_dir)
init_fn = slim.assign_from_checkpoint_fn(
checkpoint_path,
slim.get_variables_to_restore())
with tf.Session() as sess:
with slim.queues.QueueRunners(sess):
sess.run(tf.initialize_local_variables())
init_fn(sess)
np_probabilities, np_images_raw, np_labels = sess.run([probabilities, images_raw, labels])
for i in range(batch_size):
image = np_images_raw[i, :, :, :]
true_label = np_labels[i]
predicted_label = np.argmax(np_probabilities[i, :])
predicted_name = dataset.labels_to_names[predicted_label]
true_name = dataset.labels_to_names[true_label]
plt.figure()
plt.imshow(image.astype(np.uint8))
plt.title('Ground Truth: [%s], Prediction [%s]' % (true_name, predicted_name))
plt.axis('off')
plt.show()
```
| github_jupyter |
# Introduction to Data Analysis
This notebook serves as a summary of the fundamentals covered in chapter 1. For a Python crash-course/refresher, work through the [`python_101.ipynb`](./python_101.ipynb) notebook.
## Setup
```
from visual_aids import stats_viz
```
## Fundamentals of data analysis
When conducting a data analysis, we will move back and forth between four main processes:
- **Data Collection**: Every analysis starts with collecting data. We can collect data from a variety of sources, including databases, APIs, flat files, and the Internet.
- **Data Wrangling**: After we have our data, we need to prepare it for our analysis. This may involve reshaping it, changing data types, handling missing values, and/or aggregating it.
- **Exploratory Data Analysis (EDA)**: We can use visualizations to explore our data and summarize it. During this time, we will also begin exploring the data by looking at its structure, format, and summary statistics.
- **Drawing Conclusions**: After we have thoroughly explored our data, we can try to draw conclusions or model it.
## Statistical Foundations
As this is not a statistics book, we will discuss the concepts we will need to work through the book, in addition to some avenues for further exploration. By no means is this exhaustive.
### Sampling
Some resampling (sampling from the sample) techniques we will see throughout the book, especially for the chapters on machine learning (9-11):
- **simple random sampling**: pick with a random number generator
- **stratified random sampling**: randomly pick preserving the proportion of groups in the data
- **bootstrapping**: sampling with replacement (more info: [YouTube video](https://www.youtube.com/watch?v=gcPIyeqymOU) and [Wikipedia article](https://en.wikipedia.org/wiki/Bootstrapping_(statistics)))
### Descriptive Statistics
We use descriptive statistics to describe the data. The data we work with is usually a **sample** taken from the **population**. The statistics we will discuss here are referred to as **sample statistics** because they are calculated on the sample and can be used as estimators for the population parameters.
#### Measures of Center
Three common ways to describe the central tendency of a distribution are mean, median, and mode.
##### Mean
The sample mean is an estimator for the population mean ($\mu$) and is defined as:
$$\bar{x} = \frac{\sum_{1}^{n} x_i}{n}$$
##### Median
The median represents the 50<sup>th</sup> percentile of our data; this means that 50% of the values are greater than the median and 50% are less than the median. It is calculated by taking the middle value from an ordered list of values.
##### Mode
The mode is the most common value in the data. We can use it to describe categorical data or, for continuous data, the shape of the distribution:
```
ax = stats_viz.different_modal_plots()
```
#### Measures of Spread
Measures of spread tell us how the data is dispersed; this will indicate how thin (low dispersion) or wide (very spread out) our distribution is.
##### Range
The range is the distance between the smallest value (minimum) and the largest value (maximum):
$$range = max(X) - min(X)$$
##### Variance
The variance describes how far apart observations are spread out from their average value (the mean). When calculating the sample variance, we divide by *n - 1* instead of *n* to account for using the sample mean ($\bar{x}$):
$$s^2 = \frac{\sum_{1}^{n} (x_i - \bar{x})^2}{n - 1}$$
This is referred to as Bessel's correction and is applied to get an unbiased estimator of the population variance.
*Note that this will be in units-squared of whatever was being measured.*
##### Standard Deviation
The standard deviation is the square root of the variance, giving us a measure in the same units as our data. The sample standard deviation is calculated as follows:
$$s = \sqrt{\frac{\sum_{1}^{n} (x_i - \bar{x})^2}{n - 1}} = \sqrt{s^2}$$
```
ax = stats_viz.effect_of_std_dev()
```
*Note that $\sigma^2$ is the population variance and $\sigma$ is the population standard deviation.*
##### Coefficient of Variation
The coefficient of variation (CV) gives us a unitless ratio of the standard deviation to the mean. Since, it has no units we can compare dispersion across datasets:
$$CV = \frac{s}{\bar{x}}$$
##### Interquartile Range
The interquartile range (IQR) gives us the spread of data around the median and quantifies how much dispersion we have in the middle 50% of our distribution:
$$IQR = Q_3 - Q_1$$
##### Quartile Coefficient of Dispersion
The quartile coefficient of dispersion also is a unitless statistic for comparing datasets. However, it uses the median as the measure of center. It is calculated by dividing the semi-quartile range (half the IQR) by the midhinge (midpoint between the first and third quartiles):
$$QCD = \frac{\frac{Q_3 - Q_1}{2}}{\frac{Q_1 + Q_3}{2}} = \frac{Q_3 - Q_1}{Q_3 + Q_1}$$
#### Summarizing data
The **5-number summary** provides 5 descriptive statistics that summarize our data:
| | Quartile | Statistic | Percentile |
| --- | --- | --- | --- |
|1.|$Q_0$|minimum|$0^{th}$|
|2.|$Q_1$|N/A|$25^{th}$|
|3.|$Q_2$|median|$50^{th}$|
|4.|$Q_3$|N/A|$75^{th}$|
|5.|$Q_4$|maximum|$100^{th}$|
This summary can be visualized using a **box plot** (also called box-and-whisker plot). The box has an upper bound of $Q_3$ and a lower bound of $Q_1$. The median will be a line somewhere in this box. The whiskers extend from the box towards the minimum/maximum. For our purposes, they will extend to $Q_3 + 1.5 \times IQR$ and $Q_1 - 1.5 \times IQR$ and anything beyond will be represented as individual points for outliers:
```
ax = stats_viz.example_boxplot()
```
The box plot doesn't show us how the data is distributed within the quartiles. To get a better sense of the distribution, we can use a **histogram**, which will show us the amount of observations that fall into equal-width bins. We can vary the number of bins to use, but be aware that this can change our impression of what the distribution appears to be:
```
ax = stats_viz.example_histogram()
```
We can also visualize the distribution using a **kernel density estimate (KDE)**. This will estimate the **probability density function (PDF)**. This function shows how probability is distributed over the values. Higher values of the PDF mean higher likelihoods:
```
ax = stats_viz.example_kde()
```
Note that both the KDE and histogram estimate the distribution:
```
ax = stats_viz.hist_and_kde()
```
**Skewed distributions** have more observations on one side. The mean will be less than the median with negative skew, while the opposite is true of positive skew:
```
ax = stats_viz.skew_examples()
```
We can use the **cumulative distribution function (CDF)** to find probabilities of getting values within a certain range. The CDF is the integral of the PDF:
$$CDF = F(x) = \int_{-\infty}^{x} f(t) dt$$
*Note that $f(t)$ is the PDF and $\int_{-\infty}^{\infty} f(t) dt = 1$.*
The probability of the random variable $X$ being less than or equal to the specific value of $x$ is denoted as $P(X ≤ x)$. Note that for a continuous random variable the probability of it being exactly $x$ is zero.
Let's look at the estimate of the CDF from the sample data we used for the box plot, called the **empirical cumulative distribution function (ECDF)**:
```
ax = stats_viz.cdf_example()
```
*We can find any range we want if we use some algebra as in the rightmost subplot above.*
#### Common Distributions
- **Gaussian (normal) distribution**: looks like a bell curve and is parameterized by its mean (μ) and standard deviation (σ). Many things in nature happen to follow the normal distribution, like heights. Note that testing if a distribution is normal is not trivial. Written as $N(\mu, \sigma)$.
- **Poisson distribution**: discrete distribution that is often used to model arrivals. Parameterized by its mean, lambda (λ). Written as $Pois(\lambda)$.
- **Exponential distribution**: can be used to model the time between arrivals. Parameterized by its mean, lambda (λ). Written as $Exp(\lambda)$.
- **Uniform distribution**: places equal likelihood on each value within its bounds (*a* and *b*). We often use this for random number generation. Written as $U(a, b)$.
- **Bernoulli distribution**: When we pick a random number to simulate a single success/failure outcome, it is called a Bernoulli trial. This is parameterized by the probability of success (*p*). Written as $Bernoulli(p)$.
- **Binomial distribution**: When we run the same experiment *n* times, the total number of successes is then a binomial random variable. Written as $B(n, p)$.
We can visualize both discrete and continuous distributions; however, discrete distributions give us a **probability mass function** (**PMF**) instead of a PDF:
```
ax = stats_viz.common_dists()
```
#### Scaling data
In order to compare variables from different distributions, we would have to scale the data, which we could do with the range by using **min-max scaling**:
$$x_{scaled}=\frac{x - min(X)}{range(X)}$$
Another way is to use a **Z-score** to standardize the data:
$$z_i = \frac{x_i - \bar{x}}{s}$$
#### Quantifying relationships between variables
The **covariance** is a statistic for quantifying the relationship between variables by showing how one variable changes with respect to another (also referred to as their joint variance):
$$cov(X, Y) = E[(X-E[X])(Y-E[Y])]$$
*E[X] is the expectation of the random variable X (its long-run average).*
The sign of the covariance gives us the direction of the relationship, but we need the magnitude as well. For that, we calculate the **Pearson correlation coefficient** ($\rho$):
$$\rho_{X, Y} = \frac{cov(X, Y)}{s_X s_Y}$$
Examples:
```
ax = stats_viz.correlation_coefficient_examples()
```
*From left to right: no correlation, weak negative correlation, strong positive correlation, and nearly perfect negative correlation.*
Often, it is more informative to use scatter plots to check for relationships between variables. This is because the correlation may be strong, but the relationship may not be linear:
```
ax = stats_viz.non_linear_relationships()
```
Remember, **correlation does not imply causation**. While we may find a correlation between X and Y, it does not mean that X causes Y or Y causes X. It is possible there is some Z that causes both or that X causes some intermediary event that causes Y — it could even be a coincidence. Be sure to check out Tyler Vigen's [Spurious Correlations blog](https://www.tylervigen.com/spurious-correlations) for some interesting correlations.
#### Pitfalls of summary statistics
Not only can our correlation coefficients be misleading, but so can summary statistics. Anscombe's quartet is a collection of four different datasets that have identical summary statistics and correlation coefficients, however, when plotted, it is obvious they are not similar:
```
ax = stats_viz.anscombes_quartet()
```
Another example of this is the [Datasaurus Dozen](https://www.autodeskresearch.com/publications/samestats):
```
ax = stats_viz.datasaurus_dozen()
```
### Prediction and forecasting
Say our favorite ice cream shop has asked us to help predict how many ice creams they can expect to sell on a given day. They are convinced that the temperature outside has strong influence on their sales, so they collected data on the number of ice creams sold at a given temperature. We agree to help them, and the first thing we do is make a scatter plot of the data they gave us:
```
ax = stats_viz.example_scatter_plot()
```
We can observe an upward trend in the scatter plot: more ice creams are sold at higher temperatures. In order to help out the ice cream shop, though, we need to find a way to make predictions from this data. We can use a technique called **regression** to model the relationship between temperature and ice cream sales with an equation:
```
ax = stats_viz.example_regression()
```
We can use the resulting equation to make predictions for the number of ice creams sold at various temperatures. However, we must keep in mind if we are interpolating or extrapolating. If the temperature value we are using for prediction is within the range of the original data we used to build our regression model, then we are **interpolating** (solid portion of the red line). On the other hand, if the temperature is beyond the values in the original data, we are **extrapolating**, which is very dangerous, since we can't assume the pattern continues indefinitely in each direction (dotted portion of the line). Extremely hot temperatures may cause people to stay inside, meaning no ice creams will be sold, while the equation indicates record-high sales.
Forecasting is a type of prediction for time series. In a process called **time series decomposition**, time series is decomposed into a trend component, a seasonality component, and a cyclical component. These components can be combined in an additive or multiplicative fashion:
```
ax = stats_viz.time_series_decomposition_example()
```
The **trend** component describes the behavior of the time series in the long-term without accounting for the seasonal or cyclical effects. Using the trend, we can make broad statements about the time series in the long-run, such as: *the population of Earth is increasing* or *the value of a stock is stagnating*. **Seasonality** of a time series explains the systematic and calendar-related movements of a time series. For example, the number of ice cream trucks on the streets of New York City is high in the summer and drops to nothing in the winter; this pattern repeats every year regardless of whether the actual amount each summer is the same. Lastly, the **cyclical** component accounts for anything else unexplained or irregular with the time series; this could be something like a hurricane driving the number of ice cream trucks down in the short-term because it isn't safe to be outside. This component is difficult to anticipate with a forecast due to its unexpected nature.
When making models to forecast time series, some common methods include ARIMA-family methods and exponential smoothing. **ARIMA** stands for autoregressive (AR), integrated (I), moving average (MA). Autoregressive models take advantage of the fact that an observation at time $t$ is correlated to a previous observation, for example at time $t - 1$. Note that not all time series are autoregressive. The integrated component concerns the differenced data, or the change in the data from one time to another. Lastly, the moving average component uses a sliding window to average the last $x$ observations where $x$ is the length of the sliding window. We will build an ARIMA model in chapter 7.
The moving average puts equal weight on each time period in the past involved in the calculation. In practice, this isn't always a realistic expectation of our data. Sometimes all past values are important, but they vary in their influence on future data points. For these cases, we can use exponential smoothing, which allows us to put more weight on more recent values and less weight on values further away from what we are predicting.
### Inferential Statistics
Inferential statistics deals with inferring or deducing things from the sample data we have in order to make statements about the population as a whole. Before doing so, we need to know whether we conducted an observational study or an experiment. An observational study can't be used to determine causation because we can't control for everything. An experiment on the other hand is controlled.
Remember that the sample statistics we discussed earlier are estimators for the population parameters. Our estimators need **confidence intervals**, which provide a point estimate and a margin of error around it. This is the range that the true population parameter will be in at a certain **confidence level**. At the 95% confidence level, 95% of the confidence intervals calculated from random samples of the population contain the true population parameter.
We also have the option of using **hypothesis testing**. First, we define a null hypothesis (say the true population mean is 0), then we determine a **significance level** (1 - confidence level), which is the probability of rejecting the null hypothesis when it is true. Our result is statistically significant if the value for the null hypothesis is outside the confidence interval. [More info](https://statisticsbyjim.com/hypothesis-testing/hypothesis-tests-confidence-intervals-levels/).
<hr>
<div style="overflow: hidden; margin-bottom: 10px;">
<div style="float: left;">
<a href="./checking_your_setup.ipynb">
<button>Check your setup</button>
</a>
<a href="./python_101.ipynb">
<button>Python 101</button>
</a>
</div>
<div style="float: right;">
<a href="./exercises.ipynb">
<button>Exercises</button>
</a>
<a href="../ch_02/1-pandas_data_structures.ipynb">
<button>Chapter 2 →</button>
</a>
</div>
</div>
<hr>
| github_jupyter |
# Working with web archives
Current version: [v1.0.0](https://github.com/GLAM-Workbench/web-archives/releases/tag/v1.0.0)
We tend to think of a web archive as a site we go to when links are broken – a useful fallback, rather than a source of new research data. But web archives don't just store old web pages, they capture multiple versions of web resources over time. Using web archives we can observe change – we can ask historical questions. This collection of notebooks is intended to help historians, and other researchers, frame those questions by revealing what sort of data is available, how to get it, and what you can do with it.
Web Archives share systems and standards, making it much easier for researchers wanting to get their hands on useful data. These notebooks focus on four particular web archives: the [UK Web Archive](https://www.webarchive.org.uk/), the [Australian Web Archive](https://trove.nla.gov.au/website) (National Library of Australia ), the [New Zealand Web Archive](https://natlib.govt.nz/collections/a-z/new-zealand-web-archive) (National Library of New Zealand), and the [Internet Archive](https://archive.org/web/). However, the tools and approaches here could be easily extended to other web archives.
Web archives are huge, and access is often limited for legal reasons. These notebooks focus on data that is readily accessible and able to be used without the need for special equipment. They use existing APIs to get data in manageable chunks. But many of the examples demonstrated can also be scaled up to build substantial datasets for analysis – you just have to be patient!
These notebooks are a starting point that I hope will encourage researchers to investigate the possibilities of web archives in more detail. They're intended to compliment the fabulous work being by projects such as [Archives Unleashed](https://archivesunleashed.org/) to open web archives to new research uses.
The development of these notebooks was supported by the International Internet Preservation Consortium's [Discretionary Funding Programme 2019-2020](http://netpreserve.org/projects/), with the participation of the British Library, the National Library of Australia, and the National Library of New Zealand. Thanks all!
See the [web archives section](https://glam-workbench.github.io/web-archives/) of the [GLAM Workbench](https://glam-workbench.github.io/) for more information.
## Notebook topics
### Types of data
* [**Timegates, Timemaps, and Mementos**](memento.ipynb) – explore how the Memento protocol helps you get machine-readable data about web archive captures
* [**Exploring the Internet Archive's CDX API**](exploring_cdx_api.ipynb) – some web archives provide indexes of the web pages they've archived through an API, this notebook looks in detail at the data provided by the Internet Archive's CDX API
* [**Comparing CDX APIs**](comparing_cdx_apis.ipynb) – this notebook documents differences between the Internet Archive's Wayback CDX API and the PyWb CDX API (used by AWA and UKWA)
* [**Timemaps vs CDX APIs**](getting_all_snapshots_timemap_vs_cdx.ipynb) – both Timemaps and CDX APIs can give us a list of captures from a particular web page, this notebook compares the results
### Harvesting data and creating datasets
* [**Get the archived version of a page closest to a particular date**](get_a_memento.ipynb) – the Memento API enables us to get the archived version of a page closest to a particular date, the functions in this notebook smooth out these some variations across repositories
* [**Find all the archived versions of a web page**](find_all_captures.ipynb) – you can get all the captures of an archived page using either Timemaps or the CDX API, this notebook demonstrates both
* [**Harvesting collections of text from archived web pages**](getting_text_from_web_pages.ipynb) – create a dataset from the text contents of a single page across time, or multiple pages
* [**Harvesting data about a domain using the IA CDX API**](harvesting_domain_data.ipynb) – extract information about a whole domain using `prefix` and `domain` queries
* [**Find and explore Powerpoint presentations from a specific domain**](explore_presentations.ipynb) – a complete workflow from web archive to Powerpoints to PDFS to images and text, and explore it all in Datasette
* [**Exploring subdomains in the whole of gov.au**](harvesting_gov_au_domains.ipynb) - scale up your harvesting to assemble a complete set of subdomains over time, and visualise the results as a dendrogram
### Exploring change over time
* [**Compare two versions of an archived web page**](show_diffs.ipynb) – demonstrates a number of different ways to versions of an archive web page can be compared, from metadata to screenshots
* [**Observing change in a web page over time**](change_in_a_page_over_time.ipynb) – getting and visualising information about all the captures of a single page over time
* [**Create and compare full page screenshots from archived web pages**](save_screenshot.ipynb) – generate full page screenshots of archived web pages, compare pages, captures, even repositories
* [**Using screenshots to visualise change in a page over time**](screenshots_over_time_using_timemaps.ipynb) – create a time series of screenshots, one for each year, compiled into a single image
* [**Display changes in the text of an archived web page over time**](display-text-changes-from-timemap.ipynb) – work through, capture by capture, showing how the text contents of an archived web page has changed
* [**Find when a piece of text appears in an archived web page**](find-text-in-page-from-timemap.ipynb) – look for the first or last occurance of text string in an archived web page, or just find every occurance and chart the frequency
## Cite as
See the GLAM Workbench or [Zenodo](https://doi.org/10.5281/zenodo.3894078) for up-to-date citation details.
----
This repository is part of the [GLAM Workbench](https://glam-workbench.github.io/).
If you think this project is worthwhile, you might like [to sponsor me on GitHub](https://github.com/sponsors/wragge?o=esb).
| github_jupyter |
# Parallel processing with Dask
[Dask](http://dask.pydata.org/) takes yet another approach to speeding up
Python computations. One of the main limitations of Python is that in
most cases, a single Python interpreter can only access a single thread
of computation at a time . This is because of the so-called Global
Interpreter Lock (or
[GIL](https://docs.python.org/3/glossary.html#term-global-interpreter-lock)).
And while there is a
[multiprocessing module](https://docs.python.org/3/library/multiprocessing.html)
in the Python standard library, it's use is cumbersome and often requires complicated
decisions. Dask simplifies this substantially, by making the code simpler, and
by making these decisions for you.
### Dask delayed computation:
Let's look at a simple example. The following are some very fast and simple
calculations, and we add some `sleep` into them, to simulate a compute-intensive
task that takes some time to complete:
```
import time
def inc(x):
time.sleep(1)
return x + 1
def add(x, y):
time.sleep(1)
return x + y
```
Consider the calculation in the following cell. How long would it take to execute this?
```
x1 = inc(1)
x2 = inc(2)
z = add(x1, x2)
```
Notice that while `z` depends on both `x1` and `x2`, there is no
dependency between `x1` and `x2`. In principle, we could compute both of
them in parallel, but Python doesn't do that out of the box.
One way to convince Python to parallelize these is by telling Dask in
advance about the dependencies between different variables, and letting
it infer how to distribute the computations across threads:
```
from dask import delayed
x1 = delayed(inc)(1)
x2 = delayed(inc)(2)
z = delayed(add)(x1, x2)
```
Using the `delayed` function (a decorator!) tells Python not to perform
the computation until we're done setting up all the data dependencies.
Once we're ready to go we can compute one or more of the variables:
```
z.compute()
```
How much time did this take? Why?
Dask computes a task graph for this computation:
```
z.visualize()
```
Once this graph is computed, Dask can see that the two variables do not
depend on each other, and they can be executed in parallel. So, a
computation that would take 2 seconds serially is immediately sped up
n-fold (with n being the number of independent variables, here 2).
Dask has implementations of several commonly-used pythonic data-structures. In
particular, it implements a data structure that resembles the Numpy Array object
and another data structure that resembles the Pandas DataFrame. This lets us do
slightly more interesting things and leverage our knowledge of these tools.
Let's do something slightly more interesting (and neuro-related):
Let's say that we'd like to compute the tsnr over several runs of
fMRI data, for example, using the open-fMRI dataset ds000114:
```
import os.path as op
from glob import glob
fnames = glob(op.join(op.expanduser('~'), 'data/openneuro/ds000114/sub-01/ses-test/func/*.nii.gz'))
```
This is a list with 5 different file-names, for the different runs during
this session.
One way to calculate the tsnr across is to loop over the
files, read in the data for each one of them, concatenate the data and then
compute the tsnr from the concatenated series:
```
fnames
import numpy as np
import nibabel as nib
data = []
for fname in fnames:
data.append(nib.load(fname).get_fdata())
data = np.concatenate(data, -1)
tsnr = data.mean(-1) / data.std(-1)
```
> #### Lazy loading in Nibabel
> Nibabel uses "lazy loading". That means that data are not read from file
> until when the nibabel `load` function is called on a file-name. Instead,
> Nibabel waits until we ask for the data, using the `get_data` method of
> The `Nifti1Image` class to read the data from file.
When we do that, most of the time is spent on reading the data from file.
As you can probably reason yourself, the individual items in the data
list have no dependency on each other, so they could be calculated in
parallel.
Because of nibabel's lazy-loading, we can instruct it to wait with the
call to `get_data`. We create a delayed function that we call
`delayed_get_data`:
```
delayed_get_data = delayed(nib.Nifti1Image.get_fdata)
```
Then, we use this function to create a list of items and delay each one
of the computations on this list:
```
data = []
for fname in fnames:
data.append(delayed_get_data(nib.load(fname)))
data = delayed(np.concatenate)(data, -1)
tsnr = delayed(data.mean)(-1) / delayed(data.std)(-1)
```
Dask figures that out for you as well:
```
tsnr.visualize()
```
And indeed computing tsnr this way can give you an approximately 4-fold
speedup. This is because Dask allows the Python process to read several
of the files in parallel, and that is the performance bottle-neck here.
### Dask arrays
This is already quite useful, but wouldn't you rather just tell dask that
you are going to create some data and to treat it all as delayed until
you are ready to compute the tsnr?
This idea is implemented in the dask array interface. The idea here is that
you create something that provides all of the interfaces of a numpy array, but
all the computations are treated as delayed.
This is what it would look like for the tsnr example. Instead of
appending delayed calls to `get_data` into the array, we create a series
of dask arrays, with `delayed_get_data`. We do need to know both the shape
and data type of the arrays that will eventually be read, but
```
import dask.array as da
delayed_arrays = []
for fname in fnames:
img = nib.load(fname)
delayed_arrays.append(da.from_delayed(delayed_get_data(img),
img.shape,
img.get_data_dtype()))
```
If we examine these variables, we'll see something like this:
```
delayed_arrays
```
These are notional arrays, that have not been materialized yet. The data
has not been read from memory yet, although dask already knows where it
would put them when they should be read.
We can use the `dask.array.concatenate` function:
```
arr = da.concatenate(delayed_arrays, -1)
```
And we can then use methods of the `dask.array` object to complete the
computation:
```
tsnr = arr.mean(-1) / arr.std(-1)
```
This looks exactly like the code we used for the numpy array!
Given more insight into what you want to do, dask is able to construct an
even more sophisticated task graph:
```
tsnr.visualize()
```
This looks really complicated, but notice that because dask has even more
insight into what we are trying to do, it can delay some things until
after aggregation. For example, the square root computation of the
standard deviation can be done once at the end, instead of on each array
separately.
And this leads to an approximately additional 2-fold speedup.
```
%%timeit
tsnr.compute()
```
One of the main things to notice about the dask array is that because the
data is not read into memory it can represent very large datasets, and
schedule operations over these large datasets in a manner that makes the code
seem as though all the data is in memory.
| github_jupyter |
# Hybrid Recommendations with the Movie Lense Dataset
###### Note: Please complete the als_bqml.ipynb notebook before continuing.
## Learning Objectives
1. Know extract user and product factors from a BigQuery Matrix Factorizarion Model
2. Know how to format inputs for a BigQuery Hybrid Recommendation Model
### Incorporating user and movie information
The matrix factorization approach does not use any information about users or movies beyond what is available from the ratings matrix. However, we will often have user information (such as the city they live, their annual income, their annual expenditure, etc.) and we will almost always have more information about the products in our catalog. How do we incorporate this information in our recommendation model?
The answer lies in recognizing that the user factors and product factors that result from the matrix factorization approach end up being a concise representation of the information about users and products available from the ratings matrix. We can concatenate this information with other information we have available and train a regression model to predict the rating.
### Obtaining user and product factors
We can get the user factors or product factors from ML.WEIGHTS. For example to get the product factors for movieId=96481 and user factors for userId=54192, we would do:
```
import os
PROJECT = "your-project-id-here" # REPLACE WITH YOUR PROJECT ID
# Do not change these
os.environ["PROJECT"] = PROJECT
%%bigquery --project $PROJECT
SELECT
processed_input,
feature,
TO_JSON_STRING(factor_weights),
intercept
FROM ML.WEIGHTS(MODEL movielens.recommender_16)
WHERE
(processed_input = 'movieId' AND feature = '96481')
OR (processed_input = 'userId' AND feature = '54192')
```
Multiplying these weights and adding the intercept is how we get the predicted rating for this combination of movieId and userId in the matrix factorization approach.
These weights also serve as a low-dimensional representation of the movie and user behavior. We can create a regression model to predict the rating given the user factors, product factors, and any other information we know about our users and products.
### Creating input features
The MovieLens dataset does not have any user information, and has very little information about the movies themselves. To illustrate the concept, therefore, let’s create some synthetic information about users:
```
%%bigquery --project $PROJECT
CREATE OR REPLACE TABLE movielens.users AS
SELECT
userId,
RAND() * COUNT(rating) AS loyalty,
CONCAT(SUBSTR(CAST(userId AS STRING), 0, 2)) AS postcode
FROM
movielens.ratings
GROUP BY userId
```
Input features about users can be obtained by joining the user table with the ML weights and selecting all the user information and the user factors from the weights array.
```
%%bigquery --project $PROJECT
WITH userFeatures AS (
SELECT
u.*,
(SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights)) AS user_factors
FROM movielens.users u
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
ON processed_input = 'userId' AND feature = CAST(u.userId AS STRING)
)
SELECT * FROM userFeatures
LIMIT 5
```
Similarly, we can get product features for the movies data, except that we have to decide how to handle the genre since a movie could have more than one genre. If we decide to create a separate training row for each genre, then we can construct the product features using.
```
%%bigquery --project $PROJECT
WITH productFeatures AS (
SELECT
p.* EXCEPT(genres),
g, (SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights))
AS product_factors
FROM movielens.movies p, UNNEST(genres) g
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
ON processed_input = 'movieId' AND feature = CAST(p.movieId AS STRING)
)
SELECT * FROM productFeatures
LIMIT 5
```
Combining these two WITH clauses and pulling in the rating corresponding the movieId-userId combination (if it exists in the ratings table), we can create the training dataset.
**TODO 1**: Combine the above two queries to get the user factors and product factor for each rating.
```
%%bigquery --project $PROJECT
CREATE OR REPLACE TABLE movielens.hybrid_dataset AS
WITH userFeatures AS (
SELECT
u.*,
(SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights))
AS user_factors
FROM movielens.users u
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
ON processed_input = 'userId' AND feature = CAST(u.userId AS STRING)
),
productFeatures AS (
SELECT
p.* EXCEPT(genres),
g, (SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights))
AS product_factors
FROM movielens.movies p, UNNEST(genres) g
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
ON processed_input = 'movieId' AND feature = CAST(p.movieId AS STRING)
)
SELECT
p.* EXCEPT(movieId),
u.* EXCEPT(userId),
rating
FROM productFeatures p, userFeatures u
JOIN movielens.ratings r
ON r.movieId = p.movieId AND r.userId = u.userId
```
One of the rows of this table looks like this:
```
%%bigquery --project $PROJECT
SELECT *
FROM movielens.hybrid_dataset
LIMIT 1
```
Essentially, we have a couple of attributes about the movie, the product factors array corresponding to the movie, a couple of attributes about the user, and the user factors array corresponding to the user. These form the inputs to our “hybrid” recommendations model that builds off the matrix factorization model and adds in metadata about users and movies.
### Training hybrid recommendation model
At the time of writing, BigQuery ML can not handle arrays as inputs to a regression model. Let’s, therefore, define a function to convert arrays to a struct where the array elements are its fields:
```
%%bigquery --project $PROJECT
CREATE OR REPLACE FUNCTION movielens.arr_to_input_16_users(u ARRAY<FLOAT64>)
RETURNS
STRUCT<
u1 FLOAT64,
u2 FLOAT64,
u3 FLOAT64,
u4 FLOAT64,
u5 FLOAT64,
u6 FLOAT64,
u7 FLOAT64,
u8 FLOAT64,
u9 FLOAT64,
u10 FLOAT64,
u11 FLOAT64,
u12 FLOAT64,
u13 FLOAT64,
u14 FLOAT64,
u15 FLOAT64,
u16 FLOAT64
> AS (STRUCT(
u[OFFSET(0)],
u[OFFSET(1)],
u[OFFSET(2)],
u[OFFSET(3)],
u[OFFSET(4)],
u[OFFSET(5)],
u[OFFSET(6)],
u[OFFSET(7)],
u[OFFSET(8)],
u[OFFSET(9)],
u[OFFSET(10)],
u[OFFSET(11)],
u[OFFSET(12)],
u[OFFSET(13)],
u[OFFSET(14)],
u[OFFSET(15)]
));
```
which gives:
```
%%bigquery --project $PROJECT
SELECT movielens.arr_to_input_16_users(u).*
FROM (SELECT
[0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.] AS u)
```
We can create a similar function named movielens.arr_to_input_16_products to convert the product factor array into named columns.
**TODO 2**: Create a function that returns named columns from a size 16 product factor array.
```
%%bigquery --project $PROJECT
CREATE OR REPLACE FUNCTION movielens.arr_to_input_16_products(p ARRAY<FLOAT64>)
RETURNS
STRUCT<
p1 FLOAT64,
p2 FLOAT64,
p3 FLOAT64,
p4 FLOAT64,
p5 FLOAT64,
p6 FLOAT64,
p7 FLOAT64,
p8 FLOAT64,
p9 FLOAT64,
p10 FLOAT64,
p11 FLOAT64,
p12 FLOAT64,
p13 FLOAT64,
p14 FLOAT64,
p15 FLOAT64,
p16 FLOAT64
> AS (STRUCT(
p[OFFSET(0)],
p[OFFSET(1)],
p[OFFSET(2)],
p[OFFSET(3)],
p[OFFSET(4)],
p[OFFSET(5)],
p[OFFSET(6)],
p[OFFSET(7)],
p[OFFSET(8)],
p[OFFSET(9)],
p[OFFSET(10)],
p[OFFSET(11)],
p[OFFSET(12)],
p[OFFSET(13)],
p[OFFSET(14)],
p[OFFSET(15)]
));
```
Then, we can tie together metadata about users and products with the user factors and product factors obtained from the matrix factorization approach to create a regression model to predict the rating:
```
%%bigquery --project $PROJECT
CREATE OR REPLACE MODEL movielens.recommender_hybrid
OPTIONS(model_type='linear_reg', input_label_cols=['rating'])
AS
SELECT
* EXCEPT(user_factors, product_factors),
movielens.arr_to_input_16_users(user_factors).*,
movielens.arr_to_input_16_products(product_factors).*
FROM
movielens.hybrid_dataset
```
There is no point looking at the evaluation metrics of this model because the user information we used to create the training dataset was fake (not the RAND() in the creation of the loyalty column) -- we did this exercise in order to demonstrate how it could be done. And of course, we could train a dnn_regressor model and optimize the hyperparameters if we want a more sophisticated model. But if we are going to go that far, it might be better to consider using Auto ML tables, covered in the next section.
Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| github_jupyter |
# День четвертый - нейросети (изображения, тексты, многомерные ряды)
Программа дня:
- нейронные сети с помощью библиотеки `keras`, устройство нейросетей,
- сети, которые выдают свой вход и зачем они нужны - автоэнкодеры,
- элементы работы с изображениями: классификация, сегментация
- предобученные сети работы с изображениями,
- тексты: кодирование, поиск "по смыслу", извлечение сущностей, суммаризация,
- многомерные временные ряды (и рекуррентные нейронные сети).
## 4.1 Нейронные сети на `keras`
В конце второго дня мы рассмотрели некоторый пример нейронных сетей. Все слои там были одинаковые по устройству, и каждый нейрон слоя был связан с каждым нейроном следующего. Такие сети и слои называют *полносвязными* (*Dense*), и это только один из типов слоёв. Ввиду количества связей, полносвязные сети содержат просто огромное количество параметров, из-за этого они долго учатся и дают не самую минимальную ошибку (на не очень большом количестве данных).
Помните, для градиентного спуска мы искали производную по каждому параметру? То же делает и библиотека `tensorflow` (от Google), только она дифференцирует по параметрам автоматически вместо нас (благодаря особой математике на графах операций). `keras` - это надстройка над библиотекой `tensorflow`, позволяющая конструировать различные нейросети, и искать с заданной функцией ошибки её минимум.
Библиотека `scikit-learn` в отличие от `keras`, работает только с полносвязными сетями, и не позволяет произвольно настраивать эту функцию ошибки. **Функция ошибки является спецификацией задачи нейросети** - это означает что архитектурно одна и та же сеть может может подстраивать свои параметры под разные задачи.
Помимо упомянутого `Dense`-слоя, существуют следующие слои:
1. Свёрточные (`Convolution`) - применяются обычно для обработки изображений. Они пробегают некоторым окном по всем входным признакам, и вычисляют *свертку* - некоторую функцию с весами сразу над несколькими признаками. Это мало того что позволяет сократить количество весов, но и конструировать новые (внутри сети) признаки.
2. Pooling (`Pooling`, субдискретизация, обычно не переводят) - применение операции усреднения или взятия максимума над входными в слой признаками, также пробегая по данным некоторым окном. Используются для снижения размерности сети и извлечения полезных признаков.
3. Рекуррентные (`Recurrent`) - применяются для работы с последовательностями (тексты, временные ряды). Таким слоям на вход подаются последовательности, а они подстраивают свои веса с учетом структуры (если она есть конечно) последовательности.
4. Dropout (`Dropout`, выбрасывание, обычно не переводят) - это особый слой, который... выбрасывает случайно заданный процент нейронов между слоями. Это позволяет *регуляризовывать* сеть (избегать переобучения), а так же делает все нейроны сети более "осведомленными", скажем так.
5. Слои вложений (`Embeddings`) - полезны для работы с категориальными данными. Это так же и тексты (со словами из словаря). Такие слои представляют собой таблицу весов, которые переводят входные категории в вектора заданной размерности.
Слои могут (и должны) использовать функцию активации: после умножения весов на вход и сложения, для нейрона полносвязного слоя например, она применяется к результату, чтобы не получить комбинацию линейных моделей (а получить комбинацию нелинейных). Комбинация линейных моделей - линейная модель. Мы уже рассматривали во втором дне `relu`, `tanh`, `sigmoid` (`logistic` в `scikit-learn`).
Как видим, различные слои подходят под различные задачи.
```
%matplotlib inline
import os
# будем учить сети на CPU
os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # 0 для GPU
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import tensorflow.keras as keras
keras.__version__
```
Рассмотрим теперь новый датасет - Forest Cover Types - покрытие лесов. Он содержит 54 признака лесного покрытия, и метку - один из 7 типов леса. Всего в нём 581 012 записей, каждая из которых имеет свой класс (лесного покрытия). Среди признаков: тип почвы, высота над уровнем моря, и другие подобные признаки.

```
from sklearn.utils import shuffle
from sklearn.datasets import fetch_covtype
X, y = fetch_covtype(return_X_y=True)
train = int(len(y) * 0.8)
indices = shuffle(list(range(len(y))), random_state=1)
train_indices = indices[:train]
test_indices = indices[train:]
print("Размер всех данных %d, тренировочных %d" % (len(y), train))
```
Раз у нас задача классификации, и классов более двух, наша сеть нам должна отдавать вектор (неоткалиброванных вероятностей - калибрация это отдельная история), где индекс наибольшего числа будет указывать на предсказанный класс. Делается это с помощью функции `softmax(x1, ..., xk) = (exp(x1) / sum(exp(xj)), ..., exp(xk) / sum(exp(xj))), j = 1..k`
```
def create_model(number_features, number_classes):
model = keras.Sequential([
keras.layers.Dense(units=256, activation='relu', input_shape=(number_features,)),
# пятую часть нейронов при тренировке будем занулять
keras.layers.Dropout(0.2),
# промежуточный слой
keras.layers.Dense(32, activation='relu'),
# выходной слой
keras.layers.Dense(number_classes, activation='softmax')
])
# мы должны специфицировать задачу сети
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(X[train_indices])
X_train = scaler.transform(X[train_indices])
X_test = scaler.transform(X[test_indices])
# мы должны привести наши классы к векторам вида (0, 1, 0)
# где 1 стоит на том месте, где должен быть нужный пол
y_categorical = keras.utils.to_categorical(y)
y_train = y_categorical[train_indices]
y_test = y_categorical[test_indices]
# перед созданием модели сбросим
# уже сохраненные модели
keras.backend.clear_session()
model = create_model(
number_features=X_train.shape[1],
number_classes=y_train.shape[1]
)
```
Что мы задали в `compile`?
- `optimizer` - это способ поиска минимума функции ошибки. Существуют различные оптимизаторы, самые используемые: `rmsprop` (обычно для рекуррентных сетей), `sgd` (когда данных очень много), `adam` (один из самых лучших). Они как раз принимают решение, насколько далеко шагать с помощью вычисленной производной ошибки,
- `loss` - это как раз функция ошибки. Для бинарной классификации используют на последнем слое активацию `sigmoid` и `loss = 'binary_crossentropy'`, у нас многоклассовая классификация - поэтому `'categorical_crossentropy'`. Кросс-энтропия тем ниже, чем меньше перепутаны предсказанные и истинные метки. Для регрессии же используют функции потерь `mae` (*mean_absolute_error*) или `mse` (*mean_squared_error*) - которые являются средним (абсолютным или квадратичным) отклонением предсказанного от известных значений,
- `metrics` - это то, что в процессе обучение будет подсчитываться просто для информации или для отбора лучшей модели. В нашем случае `accuracy` - это процент правильных ответов.
Ну что ж, обучим нашу нейросеть. При обучении мы зададим *количество эпох* и *размер пакета* (*batch size*). Одна эпоха - это один проход по всем тренировочным данным с выборкой размера пакета (то есть шагом в размер пакета). На каждый пакет подсчитываются (те самые) производные по параметрам для каждого пакета и обновляются веса нейросети.
```
model.fit(
X_train, y_train,
batch_size=1024,
epochs=30,
verbose=2 # выводить информацию по ходу дела, 1 - подробнее
);
'loss %.2f, accuracy %.2f' % tuple(model.evaluate(X_test, y_test))
```
Поскольку метрика качества продолжает расти, скорее всего мы задали мало итераций. Однако сети имеют свойство переобучаться, поэтому и используется и `dropout`, и отбор лучшей модели по метрикам. Для последнего, используется `callback` (функция, вызываемая на каждой эпохе) `ModelCheckpoint`. Как его использовать, наряду со своим ~~доморощенным~~, показано в коде ниже.
```
from IPython.display import clear_output
# отнаследуемся от базового класса и переопределим конструктор
# и метод, вызываемый по окончанию эпохи
class PlotLosses(keras.callbacks.Callback):
def __init__(self, metric=False, check_max=True):
super(PlotLosses, self).__init__()
self.logs = []
self.losses = []
self.val_losses = []
self.metric = metric or 'loss'
self.better = max if check_max else min
def on_epoch_end(self, epoch, logs={}):
clear_output(wait=True)
self.logs.append(logs)
x = range(1, len(self.logs) + 1)
self.losses.append(logs.get(self.metric))
if logs.get('val_' + self.metric):
self.val_losses.append(logs.get('val_' + self.metric))
if len(self.val_losses):
self.best_step = 1 + (
self.val_losses.index(self.better(self.val_losses)) or 0
)
else:
self.best_step = epoch
plt.plot(x, self.losses, ls='--', c='#323232', label=self.metric)
if len(self.val_losses):
plt.plot(x, self.val_losses, ls='-', c='#323232', label="val_" + self.metric)
plt.title("Step %d, %.4f" % (
len(self.logs),
logs.get(self.metric) or 0
) + (", validation %.4f (best %.4f at %d)" % (
logs.get('val_' + self.metric) or 0,
self.better(self.val_losses if len(self.val_losses) else [0]) or 0,
self.best_step
) if logs.get('val_' + self.metric) else ''))
plt.legend(loc='best')
plt.show()
```
Для отбора лучшей модели используют валидационное множество (а итоговое качество всё так же проверяют на тестовом).
```
keras.backend.clear_session()
model = create_model(
number_features=X_train.shape[1],
number_classes=y_train.shape[1]
)
# четверть тренировочных оставим
# под валидацию
validation = int(train * 0.25)
model.fit(
X_train[validation:], y_train[validation:],
batch_size=1024,
epochs=100,
validation_data=(X_train[:validation], y_train[:validation]),
verbose=0, # НЕ выводить информацию по ходу дела
callbacks=[
PlotLosses(metric='accuracy'),
keras.callbacks.ModelCheckpoint(
'models/covtypes.h5',
monitor='val_accuracy',
save_best_only=True
)
]
);
# загрузим нашу лучшую отобранную по accuracy на валидации модель
best_model = keras.models.load_model('models/covtypes.h5')
'loss %.2f, accuracy %.2f' % tuple(best_model.evaluate(X_test, y_test))
```
### Заключение
Видим, что метрика и дальше могла бы улучшаться, но с каждым шагом дальше это происходит всё медленнее, улучшение всё меньше. На диаграммах, подобных выше, сразу видно, переобучается модель (на тренировочных данных метрика сильно больше) или нет (тренировочные и валидационные данные дают схожие метрики).
Так же стоит отметить, что готовить данные для сетей и обучать их - дело не самое простое. Тем не менее, их "всеядность" в плане данных не оставляет иного выбора исследователям. И далее мы посмотрим, что еще могут такого нейросети, кроме и так нам понятных табличных данных.
## 4.2 Автоэнкодеры
Автоэнкодеры - это сети, которые для своих входов на выходе выдают этот же вход. Стараются по-крайней мере :) Давайте сразу начнем с примера, и примера повеселее - датасета `fashion mnist`, который содержит 60 тысяч тренировочных примеров, и 10 тысяч тестовых примеров изображений одежды размеров 28х28 пикселей в градациях серого (0 черный, 1 белый), разбитых по 10 классам (различные ботинки, брюки, свитера-майки).
```
import mnist
train_X, train_y, test_X, test_y = mnist.fashion_mnist()
fashion = {
0: 'T-shirt/top',
1: 'Trouser',
2: 'Pullover',
3: 'Dress',
4: 'Coat',
5: 'Sandal',
6: 'Shirt',
7: 'Sneaker',
8: 'Bag',
9: 'Ankle boot'
}
plt.title(fashion[test_y[0]]);
plt.imshow(test_X[0], cmap='gray');
```
Построим сразу сверточную нейросеть, которая будет сворачивать изображение до вектора, а потом разворачивать в изображение обратно.
```
keras.backend.clear_session()
def create_autoencoder(shape, vector_size=3):
input_layer = layer = keras.layers.Input(shape)
filters = 16
layer = keras.layers.Conv2D(filters=filters, kernel_size=(3, 3), padding='same', activation='relu')(layer)
# после этого у нас размерность данных 28 * 28 * filters
# возьмем максимум из получаемых данных максимум,
# padding same - означает дополнять изображение значениям краёв, когда окно выходит за его пределы
layer = keras.layers.MaxPool2D((2, 2), padding='same')(layer)
# после этого у нас размерность 14 * 14 * filters
# процедуру повторим
layer = keras.layers.Conv2D(filters=filters, kernel_size=(3, 3), padding='same', activation='relu')(layer)
layer = keras.layers.MaxPool2D((2, 2), padding='same')(layer)
# свернем всё в вектор
layer = keras.layers.Flatten()(layer)
encoded = keras.layers.Dense(vector_size, activation='relu')(layer)
encoder = keras.Model(input_layer, encoded, name='encoder')
# вернем всё обратно
decoder_input = keras.layers.Input((vector_size, ))
layer = keras.layers.Dense(7 * 7 * filters, activation='relu')(decoder_input)
layer = keras.layers.Reshape((7, 7, filters))(layer)
layer = keras.layers.UpSampling2D((2, 2))(layer)
layer = keras.layers.Conv2D(filters=filters, kernel_size=(3, 3), padding='same', activation='relu')(layer)
layer = keras.layers.UpSampling2D((2, 2))(layer)
# реконструируем наше изображение
# будем выдавать степень "белизны"
output_layer = keras.layers.Conv2D(1, (3, 3), activation='relu', padding='same')(layer)
decoder = keras.Model(decoder_input, output_layer, name='decoder')
model = keras.Model(input_layer, decoder(encoder(input_layer)))
model.compile('adam', 'mae')
return model, encoder, decoder
autoencoder, encoder, decoder = create_autoencoder((28, 28, 1)) # 1 - это у нас один черно-белый канал
print(encoder.summary())
print(decoder.summary())
# в датасете градации серого от 0 до 255
training_set = np.expand_dims(train_X, axis=-1) / 255.
# будем обучать только на пятой части датасета - для скорости
# поскольку у нас классификация - сделаем стратифицированный сплит
from sklearn.model_selection import train_test_split
train_subset_X, _, train_subset_y, _ = train_test_split(
training_set, train_y,
random_state=1, test_size=0.8,
stratify=train_y
)
autoencoder.fit(
train_subset_X,
train_subset_X, # да, здесь y = X, так как это AutoEncoder
epochs=100,
batch_size=len(train_subset_X) // 30, # большой пакет, 400
verbose=0,
callbacks=[PlotLosses()]
);
figure, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].set_title(fashion[test_y[0]]);
axes[0].imshow(test_X[0], cmap='gray');
axes[1].set_title(fashion[test_y[0]] + ' reconstructed');
axes[1].imshow(
autoencoder.predict(
test_X[0].reshape(1, 28, 28, 1) / 255.
)[0].reshape(28, 28),
cmap='gray'
);
```
Замечательно (хотя и не очень), мы обучили автоэнкодер. Автоэнкодеры сами по себе не очень полезны, разве что в случае чистки изображений от шумов (для этого на вход при обучении подают зашумленные изображения, а как выход - чистые). Но и без этого попробуем.
```
figure, axes = plt.subplots(1, 2, figsize=(8, 4))
np.random.seed(1)
noised_sample = (test_X[0] / 255.).copy()
for height in range(noised_sample.shape[0]):
for width in range(noised_sample.shape[1]):
if np.random.uniform() > 0.8:
noised_sample[height, width] += np.random.normal(0, 0.1)
axes[0].set_title(fashion[test_y[0]] + ' with noise');
axes[0].imshow(noised_sample, cmap='gray');
axes[1].set_title(fashion[test_y[0]] + ' reconstructed');
axes[1].imshow(
autoencoder.predict(
noised_sample.reshape(1, 28, 28, 1)
)[0].reshape(28, 28),
cmap='gray'
);
```
Но они более полезны тем, что у нас есть трехмерное представление каждого изображения!
```
encoder.predict(noised_sample.reshape(1, 28, 28, 1))[0].tolist()
```
Давайте посмотрим, что представляют собой полученные вектора на тестовом множестве, и сразу отобразим метки классов.
```
from mpl_toolkits.mplot3d import Axes3D
axes = plt.subplot(projection='3d')
test_vectors = encoder.predict(test_X.reshape(-1, 28, 28, 1) / 255.)
axes.scatter(
test_vectors[:, 0],
test_vectors[:, 1],
test_vectors[:, 2],
c=test_y,
cmap='jet'
);
```
Вот по таким у нас получилось "полочкам" всё разложилось.
```
from matplotlib.patches import Rectangle
figure, axis = plt.subplots(10, 1, figsize=(2, 5))
for color in range(10):
axis[color].add_patch(Rectangle((0, 0), 1, 2, alpha=1, facecolor=plt.get_cmap('jet')(color / 10)))
axis[color].axis('off')
axis[color].annotate(fashion[color], (0.5, 0.5), c='white', ha='center', va='center')
plt.show()
```
Дальше можно либо кластеризовывать, либо строить классификатор. Попробуем и кластеризацию (тестового множества), и классификацию.
```
train_vectors = encoder.predict(train_X.reshape(-1, 28, 28, 1) / 255.)
axes = plt.subplot(projection='3d')
axes.scatter(
train_vectors[:, 0],
train_vectors[:, 1],
train_vectors[:, 2],
c=train_y,
cmap='jet'
);
from hdbscan import HDBSCAN # библиотека быстрой кластеризации
from sklearn.metrics import silhouette_score
best_score = -np.inf
best_number = 1
best_size = 0
for min_size in [50, 100, 200]:
clusterer = HDBSCAN(min_cluster_size=min_size).fit(test_vectors)
if len(pd.unique(clusterer.labels_)) < 2:
continue
score = silhouette_score(test_vectors, clusterer.labels_)
if score > best_score:
best_score = score
best_size = min_size
best_number = len(pd.unique(clusterer.labels_))
'best clusters number %d with min cluster size = %d and score %.2f' % (best_number, best_size, best_score)
```
Как видим, разложилось всё как-то не по 10 полочкам. Ладно...
```
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
classifier = LogisticRegression(random_state=1, max_iter=1000).fit(train_vectors, train_y)
knn = KNeighborsClassifier(weights='distance').fit(train_vectors, train_y)
"logreg acc %.2f, knn acc %.2f" % (
classifier.score(test_vectors, test_y),
knn.score(test_vectors, test_y)
)
```
Ради интереса, я скачал первые две попавшиеся картинки с wildberries (не реклама!), и обрезал их как можно ближе к квадрату.

> Квадратные штаны не получились

```
# скормим их нашему классификатору!
from PIL import Image
test_1 = Image.open('media/test_1_square.jpg').convert('L') # grayscale
test_1 = 1. - np.array(test_1.resize((28, 28))) / 255.
test_2 = Image.open('media/test_2_square.jpg').convert('L')
test_2 = 1. - np.array(test_2.resize((28, 28))) / 255.
plt.subplot(1, 2, 1)
plt.imshow(test_1, cmap='gray');
plt.subplot(1, 2, 2)
plt.imshow(test_2, cmap='gray');
fashion[
classifier.predict(
encoder.predict(test_1.reshape(1, 28, 28, 1))
)[0]
], fashion[
classifier.predict(
encoder.predict(test_2.reshape(1, 28, 28, 1))
)[0]
]
```
С сандалями разобрались, а вот штаны оказались рубашкой. Что ж, такие вот на wildberries штаны (хотя на самом деле они не по центру фото). Я скачал еще классические мужские брюки и отцентрировал их.

```
test_3 = Image.open('media/test_3.jpg').convert('L')
test_3 = 1. - np.array(test_3.resize((28, 28))) / 255.
plt.title("Вот они: " + fashion[
classifier.predict(
encoder.predict(test_3.reshape(1, 28, 28, 1))
)[0]
])
plt.imshow(test_3, cmap='gray');
```
### Заключение
Если поучить подольше, то изображения кучковались бы еще лучше - автоэнкодер бы их сильнее различал. Соответственно и вектора различались бы сильнее. Главное, что векторное представление дает нам некоторое пространство векторов, с которым уже можно работать. И да, чем больше размерность вектора, тем лучше, для отображения же вложений лучше использовать `UMAP`.
## 4.3 Классификация и сегментация изображений
Так-так, а зачем нам классифицировать вложения, когда мы можем классифицировать сами изображения? Должно быть проще и точнее.
```
keras.backend.clear_session()
def create_classifier(shape, number_classes):
model = keras.Sequential([
keras.layers.Conv2D(8, (3, 3), padding='same', activation='relu', input_shape=shape),
keras.layers.MaxPool2D((2, 2), padding='same'),
keras.layers.Dropout(0.1),
keras.layers.Conv2D(8, (3, 3), padding='same', activation='relu'),
keras.layers.MaxPool2D((2, 2), padding='same'),
keras.layers.Dropout(0.1),
keras.layers.Flatten(),
keras.layers.Dense(number_classes, activation='softmax')
])
model.compile('adam', 'categorical_crossentropy', metrics=['acc'])
return model
classifier = create_classifier((28, 28, 1), 10)
classifier.summary()
classifier.fit(
training_set,
keras.utils.to_categorical(train_y),
batch_size=500,
epochs=30,
verbose=0,
callbacks=[PlotLosses(metric='acc')]
);
'loss %.2f, accuracy %.2f' % tuple(classifier.evaluate(test_X.reshape(-1, 28, 28, 1), pd.get_dummies(test_y)))
fashion[
np.argmax(
classifier.predict(
test_1.reshape(1, 28, 28, 1)
)[0]
)
], fashion[
np.argmax(
classifier.predict(
test_2.reshape(1, 28, 28, 1)
)[0]
)
], fashion[
np.argmax(
classifier.predict(
test_3.reshape(1, 28, 28, 1)
)[0]
)
]
```
Ну, теперь все штаны стали штанами. Это был пример классификации изображений, то есть каждому изображению мы составляли некоторый класс.
К слову, существуют и методы локальной (одного примера) интепретации для классификаторов изображений, в частности из библиотеки `tf-keras-vis` можно использовать способ `gradcam`. Описывать принцип его работы тут несподручно (вкратце, предсказание "прокручивается" в обратную сторону), проще посмотреть на результаты: отображаются те пиксели входного изображения, которые привели классификатор к конкретному ответу.
```
from tf_keras_vis.gradcam import GradcamPlusPlus
from tf_keras_vis.utils import normalize
# подменим активацию последнего слоя
def model_modifier(model):
model.layers[-1].activation = keras.activations.linear
return model
gradcam = GradcamPlusPlus(
classifier,
model_modifier,
clone=False
)
cam = gradcam(
lambda output: output[0], # для этой библиотеки это откуда как брать loss
test_3.reshape(1, 28, 28, 1),
penultimate_layer=-1 # заберем последний слой
)
cam = normalize(cam)
heatmap = np.uint8(plt.cm.jet(cam[0])[..., :3] * 255)
plt.title(fashion[
np.argmax(
classifier.predict(
test_3.reshape(1, 28, 28, 1)
)[0]
)
])
plt.imshow(test_3.reshape(28, 28), cmap='gray')
plt.imshow(heatmap, cmap='jet', alpha=0.5)
plt.tight_layout()
plt.show()
```
Существуют и другие задачи с изображениями, детекция объектов например (подсветить рамочкой людей, машины и другое на фото), а так же сегментации. Задача сегментации - это задача отнесения каждого пикселя изображения к некоторому классу, что есть выделение контуров объектов (например кошки или собаки).
Разметка правильных ответов в задаче сегментации называется *маской*, и представляет собой заполненный и обведенный контур на изображении. На выходе сеть должна выдать нам пустое изображение, но там где должны быть контуры объекта - заполнить пикселы значением 1. То есть на выходе к каждому пикселю идёт сигмоида.
Для решения задачи сегментации была придумана архитектура `U-net`. Писать её сами мы не будем, мы воспользуемся готовым пакетом `keras-unet`.

Похожа на автоэнкодер, за исключением наличия сквозных связей. На каком датасете будем пробовать?
Я разметил 7 (семь) фото своей руки с часами, и обвёл как раз контуром сами часы - с помощью открытого приложения [LabelMe](https://github.com/wkentaro/labelme). Будем распознавать часы на руке. Пример маски, наложенной на фото.

Можно удивиться, почему семь фото? А больше лень было. Этого же мало?
Нам поможет ***аугментация*** - мы будем растягивать, переворачивать и иным образом всячески шевелить одновременно картинку и маску много раз, чтобы разнообразить наш датасет. По идее, это можно делать бесконечно. Важно тут не переусердствовать, нужно чтобы аугментированные всё же соответствовали тому, что бывает в природе. Аугментации, стоит отметить, заодно регуляризуют модель, дополняя данные - вместо переобучения к маленькому датасету, мы имеем возможность "объяснить" сети на большем числе примеров, что же нужно выделять.
```
filenames = os.listdir('data/watches/')
input_images = np.asarray([
np.array(Image.open('data/watches/' + filename).resize((128, 128))) for filename in filenames if 'image' in filename
]).reshape(-1, 128, 128, 3).astype(np.uint8)
input_masks = np.asarray([
np.array(Image.open('data/watches/' + filename).resize((128, 128))) for filename in filenames if 'label' in filename
]).reshape(-1, 128, 128).astype(np.uint8)
plt.subplot(1, 2, 1)
plt.imshow(input_images[0]);
plt.subplot(1, 2, 2)
plt.imshow(input_masks[0], cmap='gray');
from albumentations import ShiftScaleRotate, HorizontalFlip, Compose
def augment(probability=0.5):
return Compose([
HorizontalFlip(p=probability),
ShiftScaleRotate(
shift_limit=0.05, # двигать на 5%
scale_limit=0.2, # увеличивать на 20%
rotate_limit=60, # вращать на 60 градусов
p=probability
)
])
augmentation = augment(probability=0.5)
augmented = {
'image': [], 'mask': []
}
test_images = input_images[-2:]
test_masks = input_masks[-2:]
# получим 20 * 5 изображений
for _ in range(20):
for index in range(len(input_masks) - 2):
current = augmentation(
image=input_images[index],
mask=input_masks[index]
)
augmented['image'] += [current['image'] / 255.]
augmented['mask'] += [np.expand_dims(current['mask'], axis=-1)]
plt.subplot(1, 2, 1)
plt.imshow(augmented['image'][0]);
plt.subplot(1, 2, 2)
plt.imshow(augmented['mask'][0].reshape(128, 128), cmap='gray');
```
Всё, мы готовы учить наш UNET.
```
from keras_unet.models import custom_unet
keras.backend.clear_session()
unet = custom_unet(
input_shape=(128, 128, 3),
num_classes=1,
num_layers=3,
output_activation='sigmoid'
)
unet.compile('adam', 'binary_crossentropy')
unet.fit(
np.asarray(augmented['image']),
np.asarray(augmented['mask']),
epochs=10,
verbose=1,
batch_size=1,
shuffle=True
);
plt.subplot(1, 3, 1)
plt.title('Исходное')
plt.imshow(test_images[0]);
plt.subplot(1, 3, 2)
plt.title('Метка')
plt.imshow(test_masks[0].reshape(128, 128), cmap='gray');
plt.subplot(1, 3, 3)
plt.title('Предсказание')
prediction = unet.predict(np.asarray([test_images[0] / 255.]))[0].reshape(128, 128)
plt.imshow(prediction, cmap='gray');
plt.subplot(1, 3, 1)
plt.title('Исходное')
plt.imshow(test_images[1]);
plt.subplot(1, 3, 2)
plt.title('Метка')
plt.imshow(test_masks[1].reshape(128, 128), cmap='gray');
plt.subplot(1, 3, 3)
plt.title('Предсказание')
prediction = unet.predict(np.asarray([test_images[1] / 255.]))[0].reshape(128, 128)
plt.imshow(prediction, cmap='gray');
```
Вообще, модель на самом деле в часах ничего не понимает. На белый циферблат, скажем, она не сработает (так как не знает что такие бывают). Она реагирует на что-то черное и круглое с серебристыми линиями внутри.
Попробуем на других часах, тоже с черным циферблатом.
```
test_check = np.array(Image.open('data/watches/check.jpg').resize((128, 128))) / 255.
plt.subplot(1, 2, 1)
plt.title('Исходное')
plt.imshow(test_check);
plt.subplot(1, 2, 2)
plt.title('Предсказание')
prediction = unet.predict(np.asarray([test_check]))[0].reshape(128, 128)
plt.imshow(prediction, cmap='gray');
```
### Заключение
Работа с изображениями не так проста и в случае сегментации не заканчивается предсказанной маской (что с ней делать-то?). Существует библиотека `opencv`, которая содержит огромное количество методов работы с изображением (в основном без машинного обучения). В ней есть в частности метод `findContours`, который находит замкнутые контуры и `boundingRect` - который возвращает окружающий контур прямоугольник. Вот с такими данными уже можно пробовать наводить аналитику.
```
import cv2
contours, hierarchy = cv2.findContours(((prediction > 0.5) * 255).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
result = np.zeros_like(prediction)
for contour in contours:
bounds = cv2.boundingRect(contour)
cv2.rectangle(result, bounds, 255)
plt.title('Bounding box')
plt.imshow(result, cmap='gray');
```
## 4.4 Готовые нейросети для работы с изображениями
Существует ряд архитектур глубоких нейронных сетей для классификации изображений. Как правило, чем больше в сети весов, тем она точнее, но тем дольше она делает своё предсказание. Также существует и датасет [Imagenet](http://www.image-net.org/) с несколькими миллионами размеченных по классам изображений.
В `keras` доступен ряд претренированных на Imagenet сетей. Пользоваться ими достаточно просто, но учтите что первый запуск эти самые веса будут скачиваться (несколько десятков-сотен мегабайт).
Посмотрим, что нам скажет сеть NASNetMobile (одна из самых легких) на вот такое изображение.

```
from keras.applications import NASNetMobile
from keras.applications.nasnet import preprocess_input, decode_predictions
nasnet = NASNetMobile(weights="imagenet")
cat_image = np.array(Image.open('media/white_cat.jpg').resize((224, 224)))
cat_image = preprocess_input(np.asarray([cat_image]))
cat_image_prediction = nasnet.predict(cat_image)
print("Class, Description, Probability")
for cat_prediction in decode_predictions(cat_image_prediction, top=5)[0]:
print(cat_prediction)
```
Что ж, видим что сеть хоть и не очень уверена в предсказании, класс фото с кошкой она всё же определила.
Существуют готовые сети и для детекции объектов - которые выделяют рамкой (*bounding box*) объект (то есть решается задача регрессии для координат) и определяют его класс. Одну такую - **YOLO** (you look only once) - мы сейчас и рассмотрим. Она, в свою очередь, обучена уже на другом датасете, который называется [COCO](https://cocodataset.org/).
Для использования YOLO нам понадобится пакет `yolov4` (и веса сети размером около 260 Мб, которые нужно скачать по ссылке из [описания пакета](https://pypi.org/project/yolov4/)). Мы так же должны создать (или отредактировать) файл *coco.names*, содержащий те наименования классов датасета COCO, которые мы хотим распознавать (изначально их порядка 80).
```
from yolov4.tf import YOLOv4
yolo = YOLOv4()
yolo.classes = "data/coco.names"
yolo.make_model()
yolo.load_weights("D:/Downloads/yolov4.weights", weights_type="yolo")
predicted = yolo.predict(np.array(Image.open("media/white_cat.jpg")))
with open('data/coco.names', 'r') as fd:
yolo_classes = fd.read().split('\n')
for detection in predicted:
print("Bounding box (center x, center y, width, height):", detection[:4])
print("Class:", yolo_classes[int(detection[4])])
print("Probability: %.4f" % detection[5])
```
### Заключение
Это вообще замечательно, когда есть готовые нейросети. Их даже можно дообучать (*fine-tuning*). В случае с `keras`, "замораживаются" веса на нескольких начальных слоях, и сеть нужно дообучить сеть под свой датасет (тут на самом деле надо знать что "морозить"). В случае же с YOLO есть свои инструкции (тоже не самые простые).
Готовые сети позволяют делать готовые приложения, и особенно в тех случаях, когда нет своего датасета. Можно же не распознавать котиков, а, например, только машины. Что с ними сдетектированными делать - это уже зависит только от разбега фантазии.
Для использования готовых нейросетей удобно использовать "зоопарк" моделей сайта `TensorflowHub`. Загляните туда, и (возможно) не пожалеете.
## 4.5 Тексты и нейросети
Вот и подобрались к работе с текстами. Здесь мы будем рассматривать только готовые и очень "толстые" сети. В частности `Google BERT` (*Bidirectional Encoder Representations from Transformers*).
`BERT` имеет очень большой размер, и был обучен на текстах Википедии решать две задачи:
1. Предсказывать пропущенные слова в тексте: "я пошел в ? и купил ?" - "я пошел в магазин и купил молоко",
2. Предсказывать, является ли текст продолжением некоторого начала: "я пошел в магазин -- и купил молоко" (ok) и "я пошел в магазин -- и пингвины не летают" (fail).
У `BERT` для 2018 года была достаточно инновационная архитектура, в частности использовался *Attention* (механизм внимания) - это когда накапливается информация о последовательных данных (словах). Основное что может `BERT` - это выдать репрезентацию, или вложение слов в векторное пространство, с которым можно работать. Так же `BERT` доучивают под специфические задачи, но это достаточно ресурсозатратное мероприятие (не формата компьютера вида ноутбук).
Модель `BERT` можно предварительно [скачать](https://github.com/google-research/bert/blob/master/multilingual.md), но и `deeppavlov` это умеет сам.
Особенность ряда предобученных вариантов `BERT` - мультиязычность, то есть поддержка сразу около 100 языков "из коробки". Давайте посмотрим на примерах что может `BERT`, и будем делать это с помощью библиотеки `deeppavlov`, созданной в МФТИ.
> **Attention!** Для deeppavlov требуется `tensorflow==1.15.2`.
```
import tensorflow as tf
tf.get_logger().setLevel('ERROR')
from deeppavlov.core.common.file import read_json
from deeppavlov import build_model, configs
bert_config = read_json(configs.embedder.bert_embedder)
bert_config['metadata']['variables']['BERT_PATH'] = 'd:/workspace/bert/bert-base-multilingual-cased/'
bert = build_model(bert_config)
texts = ['Привет, я предложение.', 'Hello, I\'am a sentence too.', 'Тут случайно что-то написано.']
tokens, token_embeddings, subtokens, subtoken_embs, sent_max_embs, sentence_mean_embeddings, bert_pooler_outputs = bert(texts)
```
Нас будут интересовать `token_embeddings` и `sentence_mean_embeddings`, а точнее косинусное сходство между ними. По аналогии с `TFIDF` - `BERT` лучше работает с косинусным сходством (то есть `+1` - для идентичных примеров, `-1` - для противоположных по смыслу).
```
token_embeddings[0].shape, sentence_mean_embeddings[0].shape
from sklearn.metrics.pairwise import cosine_similarity
print("Для первого слова!")
print(tokens[0][0], tokens[0][0], "%.3f" % cosine_similarity([token_embeddings[0][0]], [token_embeddings[0][0]]))
print(tokens[0][0], tokens[1][0], "%.3f" % cosine_similarity([token_embeddings[0][0]], [token_embeddings[1][0]]))
print(tokens[1][0], tokens[2][0], "%.3f" % cosine_similarity([token_embeddings[1][0]], [token_embeddings[2][0]]))
print(tokens[0][0], tokens[2][0], "%.3f" % cosine_similarity([token_embeddings[0][0]], [token_embeddings[2][0]]))
print("Средние вложения для предложений")
print(texts[0], texts[0], "%.3f" % cosine_similarity([sentence_mean_embeddings[0]], [sentence_mean_embeddings[0]]))
print(texts[0], texts[1], "%.3f" % cosine_similarity([sentence_mean_embeddings[0]], [sentence_mean_embeddings[1]]))
print(texts[1], texts[2], "%.3f" % cosine_similarity([sentence_mean_embeddings[1]], [sentence_mean_embeddings[2]]))
print(texts[0], texts[2], "%.3f" % cosine_similarity([sentence_mean_embeddings[0]], [sentence_mean_embeddings[2]]))
```
Кстати, если вектора преобразовать (разделить на их евклидову длину) - то косинусное расстояние будет выражаться через евклидово расстояние векторов.
```
from sklearn.metrics.pairwise import euclidean_distances
print('Неотнормированные вектора', texts[0], texts[1], "euclidean %.3f" % euclidean_distances([sentence_mean_embeddings[0]], [sentence_mean_embeddings[1]]))
print('Нормированные вектора', texts[0], texts[1], "euclidean %.3f, cosine %.3f" % (euclidean_distances(
[sentence_mean_embeddings[0] / (sum(sentence_mean_embeddings[0] ** 2) ** 0.5)],
[sentence_mean_embeddings[1] / (sum(sentence_mean_embeddings[1] ** 2) ** 0.5)]
), (1 - 0.5 * euclidean_distances(
[sentence_mean_embeddings[0] / (sum(sentence_mean_embeddings[0] ** 2) ** 0.5)],
[sentence_mean_embeddings[1] / (sum(sentence_mean_embeddings[1] ** 2) ** 0.5)]
) ** 2)))
```
Что из этого важно. Важно то, что близкие по смыслу предложения имеют более близкое к 1 расстояние. На этом можно строить кластеризацию, классификаторы даже без *fine-tuning* `BERT`. Кроме `BERT` существует еще одна модель от Google: `USE` (*Universal Sentence Encoder*), которая построена на тех же принципах, но уже работает с предложениями (то есть вектор-вложение для "пропущенного" предложения).
> Если необходимо работать со смыслом предложений, рекомендую пакет `sentence-transformers`, в нём есть дистиллированная многоязычная модель `USE`.
> Дистиллированная - это значит обучена более легкая модель, которая предсказывает то же, что и оригинальная (обычно качество у них чуть хуже, но зато скорость выше и размер ниже).
> Однако учтите - "под капотом" у `sentence-transformers` другая библиотека дифференцирования на графах, уже не от Google, а от Facebook, и называется она `pytorch`. Тем не менее, у `sentence-transformers` весьма простой программный интерфейс, и её применение (в том числе благодаря её документации) не составит большого труда.
Но мы даже с помощью `BERT` - благодаря идее ближайших - сможем построить простого вопросно-ответного бота.
```
question_answers = [
('Кто первым полетел в космос?', 'Юрий Гагарин'),
('Кто был первым президентом России?', 'Михаил Горбачев'),
('Зачем автомобилю руль?', 'Чтобы водитель мог поворачивать')
]
qa_vectors = [
bert(question[0])[5][0].tolist() for question in question_answers
]
from sklearn.neighbors import NearestNeighbors
knowledge_base = NearestNeighbors(n_neighbors=1, metric='cosine').fit(qa_vectors)
question = 'Кто был первым космонавтом?'
answer_index = knowledge_base.kneighbors(
[bert(question)[5][0]], return_distance=False
)[0][0]
print(question, question_answers[answer_index][1])
```
Если всё вам нужен чат-бот (а не просто вопросно-ответный), рекомедую забить в поиск Google слова `rasa nlu`, и присмотреться к набору библиотек и инструментов `rasa`. Они строят чат-ботов на основе историй, извлекая из предложений **намерение** (*intent*) и **сущности** (*entities*), например для предложения "где ближайший ресторан" будет распознано намерение "поиск" и сущность "ресторан".
Из интересного - работа с текстом далеко не ограничивается поиском ближайших. Мы посмотрим еще две задачи - суммаризация (извлечение основного из текста) и извлечение именованных сущностей (*named entity recognition*). Первая задачу можно решить с помощью пакета `bert-extractive-summarizer`. Он для извлечения основных предложений кластеризует их все, и выбирает самые близкие к центрам кластеров.
```
# для подгрузки произвольных моделей нужен пакет transformers
from transformers import AutoConfig, AutoModel, AutoTokenizer
custom_config = AutoConfig.from_pretrained('d:/workspace/bert/bert-base-multilingual-cased/')
custom_config.output_hidden_states=True
custom_tokenizer = AutoTokenizer.from_pretrained('d:/workspace/bert/bert-base-multilingual-cased/')
custom_model = AutoModel.from_pretrained('d:/workspace/bert/bert-base-multilingual-cased/', config=custom_config)
from summarizer import Summarizer
summarizer = Summarizer(custom_model=custom_model, custom_tokenizer=custom_tokenizer)
# https://lenta.ru/news/2020/07/04/cometa/
long_news_text_from_lenta_ru = """
Российский космонавт Иван Вагнер, находящийся в настоящее время на Международной космической станции (МКС),
сфотографировал комету C/2020 F3 (NEOWISE). Он опубликовал фото на своей странице в Twitter. «На следующем витке
попробовал чуть ближе сфотографировать самую яркую за последние семь лет комету C/2020 F3 (NEOWISE).
Довольно хорошо видно ее хвост из космоса, с борта Международной космической станции!» — подписал он снимок.
В ближайшие дни комету можно будет увидеть с Земли в небе над северо-восточным горизонтом недалеко от созвездия Возничего.
Ранее Вагнер рассказал о сложностях жизни в невесомости. По его словам, самым тяжелым является «длительная изоляция в замкнутом объеме» и бытовые условия.
На данный момент Иван Вагнер входит в состав экипажа МКС вместе с Анатолием Иванишиным, а также астронавтами НАСА Кристофером Кэссиди, Дугласом Херли
и Робертом Бенкен. Они продолжают осуществлять свою экспедицию по запланированной программе.
"""
summarized = summarizer(long_news_text_from_lenta_ru)
print(summarized)
```
Этот способ имеет ряд настроек (например пропорцию сокращения или минимальную длину предложения), и очень удобен для обработки длинных текстов автоматизированно.
А вот NER есть и в уже упомянутой библиотеке `deeppavlov`, и работает он весьма интересно. Посмотрим.
```
ner = build_model(configs.ner.ner_ontonotes_bert_mult, download=False)
print(ner(['Российский космонавт Иван Вагнер, находящийся в настоящее время на Международной космической станции (МКС), сфотографировал комету C/2020 F3 (NEOWISE).']))
```
Здесь `B` - начало токена, `I` - продолжение, `O` - не именованная сущность. `NORP` - это национальная, политическая или религиозная принадлежность, `PERSON` - имена людей, `ORG` - понятно, организации, `LOC` - местоположение, и есть и другие типы именованных сущностей (всего 18 в этой модели).
Учтите, нельзя полагаться на NER в том смысле, что он "точно ничего не пропустит". Мало того что может пропустить, может еще и перепутать. Поэтому использовать его надо не на точность, а на так сказать "ковровое покрытие" - обрабатывать множество текстов и извлекать статистики.
### Заключение
Языковые модели очень тяжелые и работают достаточно долго (без подключения графических карт). Зато они могут практически чудеса, и этим надо обязательно пользоваться.
## 4.6 Рекуррентные нейросети для временных рядов
В прошлом дне мы "стэкали" `fbprophet` для получения прогноза на будущее. Можно ли делать подобное одной (нейро-)сетью? Да, можно. Для этого используются *рекуррентные слои*: такие как `LSTM` (*long-short-term memory*) или `GRU` (*gated recurrent unit*). Они требуют на входе последовательности признаков, а не просто одного вектора, то есть размерность их входа `(B, T, C)`, где `B` - размер батча, `T` - длина серии, `C` - количество признаков в каждый момент времени.
Посмотрим на устройство `GRU` (он проще, и поэтому он часто лучше работает на более коротких по времени данных).

Здесь:
1. На вход подаются предыдущее `h(t - 1)` и текущий вектор признаков `x(t)`,
2. Они каждый умножаются на свои матрицы весов и сдвигаются на вектор смещения, после чего активируются,
3. Из них с помощью покомпонентного перемножения и (другой уже) активации формируется промежуточный вектор `h_hat(t)` ("h с крышкой"),
4. Затем из линейной комбинации `h(t - 1)` и `h_hat(t)` формируется уже новый `h(t)` и так же - выходной вектор.
Непонятно? :) Да, картинка непонятна (это граф операций), формула на словах тоже.
А происходит вот что. При попадании серии в блок `GRU`, предыдущее состояние комбинируется с текущим элементом серии, и комбинация текущего и предыдущего состояния определяет выход. Веса определяются в процессе обучения так, чтобы дать минимум ошибки.
`GRU` вообще говоря также возвращает последовательности. Когда нужен только последний вектор, в `keras` можно задать слою настройку `return_sequences = False`. Давайте вернемся к нашей погоде в *Jena*.
```
%%time
climate = pd.read_csv('data/jena_climate_2009_2016.csv', parse_dates=['Date Time'], dayfirst=True)
features = ['p (mbar)', 'rh (%)', 'wv (m/s)', 'wd (deg)', 'Date Time']
target = 'T (degC)'
dataset = climate[features + [target]].set_index('Date Time').resample('D').mean().dropna()
```
Заготовим наши серии. На вход будем подавать 180 точек, а на выход попросим 120.
```
past_history = 180
future_target = 120
if 'Date Time' in features:
features.remove('Date Time')
def multivariate_data():
data = []
labels = []
for index in range(past_history, len(dataset) - future_target):
indices = range(index - past_history, index)
data.append(dataset[features].values[indices])
indices = range(index, index + future_target)
labels.append(dataset[target].values[indices])
data = np.array(data).reshape(-1, past_history, len(features))
labels = np.array(labels).reshape(-1, future_target)
return data, labels
weather_X, weather_y = multivariate_data()
# отложим тестовое множество
split = -future_target
weather_train_X, weather_train_y = weather_X[:split], weather_y[:split]
weather_test_X, weather_test_y = weather_X[split:], weather_y[split:]
weather_train_X.shape, weather_train_y.shape
# отмасштабируем наши признаки от 0 до 1
xmax = np.array([
max([max(serie[:, index]) for serie in weather_train_X]) \
for index in range(len(features))
])
xmin = np.array([
min([min(serie[:, index]) for serie in weather_train_X]) \
for index in range(len(features))
])
ymax = max([
max(serie) for serie in weather_train_y
])
ymin = min([
min(serie) for serie in weather_train_y
])
ranged_train_X = (weather_train_X - xmin) / (xmax - xmin)
ranged_test_X = (weather_test_X - xmin) / (xmax - xmin)
ranged_train_y = (weather_train_y - ymin) / (ymax - ymin)
ranged_test_y = (weather_test_y - ymin) / (ymax - ymin)
keras.backend.clear_session()
def create_RNN(input_shape):
model = keras.Sequential([
keras.layers.GRU(
30, # размерность выхода
input_shape=input_shape,
activation='relu',
return_sequences=False
),
keras.layers.Dense(60, activation='relu'),
keras.layers.Dense(future_target, activation='linear')
])
# поскольку в рекуррентных слоях могут быть большие градиенты-производные
# мы их будем обрезать по величине 1.
model.compile(keras.optimizers.RMSprop(clipvalue=1.), 'mse', metrics=['mae'])
return model
rnn = create_RNN(weather_train_X.shape[1:])
rnn.summary()
rnn.fit(
ranged_train_X, ranged_train_y,
verbose=1, epochs=20, batch_size=4
);
from sklearn.metrics import mean_absolute_error
"Средняя ошибка в градусах %.1f" % mean_absolute_error(weather_test_y, rnn.predict(ranged_test_X) * (ymax - ymin) + ymin)
plt.plot(
dataset.index[-past_history * 5:],
dataset[target].values[-past_history * 5:],
alpha=0.5
);
for step in range(-5, 1, 1):
start = step * future_target - 1
predicted_weather = rnn.predict(
np.asarray([
(dataset[features].values[start - past_history:start] - xmin) / (xmax - xmin)
]).reshape(1, past_history, len(features))
)[0] * (ymax - ymin) + ymin
started = dataset.index[start]
plt.plot(
[started + pd.Timedelta(days=day) for day in range(future_target)],
predicted_weather
);
```
Наверное, в 2017 была там тёплая зима. Заметим, что средняя абсолютная ошибка ниже (но и входные данные, и прогноз по длине разные).
### Заключение
Для работы с последовательными данными можно применять рекуррентные нейронные сети. Многие считают, что они всё же не очень хорошо работают. Но они, так или иначе, *работают*, и без всякого стэкинга. Чудес сильно больших от них не стоит ждать, когда целевая величина не является, или не приведена близко к нормально-распределенной (это скорее уже из опыта наблюдение). Тем не менее случаев применения `RNN` большое множество, так как иногда даже какая-то модель лучше вообще её отсутствия.
> Как говорил один известный математик (статистик) Джордж Бокс, **"В сущности, все модели неправильны, но некоторые из них полезны"**.
| github_jupyter |
```
import numpy as np
import pandas as pd
import random
import re
def arcs_to_vector(expression: re.Pattern, lines: list) -> pd.DataFrame:
filtered = list(filter(expression.match, lines))
vector = map(lambda x: x.split()[1:], filtered)
colnames = ("tail", "head", "low", "cap", "cost")
data = pd.DataFrame.from_records(list(vector), columns=colnames).astype(int)
data["flow"] = 0
return data
def special_nodes_to_arc(nodes: pd.DataFrame, value: int, origin=True):
if origin:
data = {
"head": nodes["node"],
"cap": nodes["flow"],
"low": nodes["flow"],
}
data["tail"] = value
else:
data = {
"tail": nodes["node"],
"cap": -nodes["flow"],
"low": -nodes["flow"],
}
data["head"] = value
data["cost"] = 0
data["flow"] = 0
return pd.DataFrame(data, columns=("tail", "head", "low", "cap", "cost", "flow"))
def nodes_to_vector(expression: re.Pattern, lines: list) -> pd.DataFrame:
filtered = list(filter(expression.match, lines))
vector = map(lambda x: x.split()[1:], filtered)
nodes = pd.DataFrame.from_records(list(vector), columns=("node", "flow")).astype(int)
source_nodes = nodes["flow"] > 0
sink_nodes = nodes["flow"] < 0
return pd.concat([
special_nodes_to_arc(nodes[source_nodes], 25001),
special_nodes_to_arc(nodes[sink_nodes], 25002, origin=False),
])
def read_file(path_to_file: str) -> pd.DataFrame:
r_arcs = re.compile("^a")
r_nodes = re.compile("^n")
with open(path_to_file) as f:
content = f.readlines()
arcs = arcs_to_vector(r_arcs, content)
nodes = nodes_to_vector(r_nodes, content)
response = pd.concat([arcs, nodes], ignore_index=True)
display(response)
return response
def select_random(node: int, network: pd.DataFrame, end_network=6) -> pd.Series:
#out_node = network[(network["tail"] == node) & (network["head"] == end_network)]
mask_to = (network["tail"] == node) & (network["cap"] > network["flow"])
if mask_to.sum() > 0:
selected = random.choice(network[mask_to].index)
return network.loc[selected]
return None
def open_pipe(arc: pd.Series, network: pd.DataFrame, flow: int) -> pd.DataFrame:
if arc["cap"] >= arc["flow"] + flow:
arc["flow"] = arc["flow"] + flow
network.iloc[arc.name] = arc
def given_flow(arc: pd.Series, flow_available: int) -> int:
aux = arc["cap"] - arc["flow"]
aux_array = np.array(range(1, aux+1))
aux_array = aux_array[aux_array <= flow_available]
if len(aux_array) > 0:
flow = random.choice(aux_array)
else:
flow = 0
return flow
def is_full(in_node: int, network: pd.DataFrame, input_flow: int) -> bool:
in_node = network[network["tail"] == in_node]
if in_node["flow"].sum() == input_flow:
return True
return False
def change_node(network: pd.DataFrame) -> pd.Series:
visited = network["tail"][network["flow"] != 0].unique()
not_visited = network["tail"][network["flow"] == 0].unique()
not_visited = list(set(not_visited).difference(set(visited)))
possibles_to = network[network["tail"].isin(visited) & network["head"].isin(not_visited)]
if len(possibles_to):
node_selected = random.choice(possibles_to["head"].unique())
else:
aux = set(network["tail"]).intersection(set(network["head"]))
possibles = []
for i in aux:
in_flow = network["flow"][network["tail"] == i].sum()
out_flow = network["flow"][network["head"] == i].sum()
#display(f"In node {i} {in_flow}->{out_flow}")
if in_flow != out_flow:
possibles.append(i)
if len(possibles) == 0:
return None, None
node_selected = random.choice(possibles)
total_input = network["flow"][network["head"] == node_selected].sum()
return node_selected, total_input
def is_solution(network: pd.DataFrame, start: int, end: int) -> bool:
in_start = network["flow"][network["tail"] == start].sum()
in_end = network["flow"][network["head"] == end].sum()
return in_start == in_end
def compute_total_cost(network: pd.DataFrame) -> int:
used = network["flow"] > 0
return (network["cost"] * used).sum()
def run_pipe(start: int, end: int, network: pd.DataFrame, input_flow, output_flow):
in_node = start
flow_available = input_flow
while True:
go_to = select_random(in_node, network)
if go_to is not None:
flow = given_flow(go_to, flow_available)
#display(f"({i}) {in_node} -({flow})-> {go_to['head']}: {flow_available}/{input_flow}")
open_pipe(go_to, network, flow)
flow_available = flow_available - flow
if is_full(in_node, network, input_flow):
in_node, input_flow = change_node(network)
if in_node is None:
break
flow_available = input_flow- network["flow"][network["tail"] == in_node].sum()
#display(f"available: {flow_available} aa {network['flow'][network['tail'] == in_node].sum()}")
#display(network)
if go_to is None:
break
aux = network["head"].unique()
for i in aux:
in_flow = network["flow"][network["head"] == i].sum()
out_flow = network["flow"][network["tail"] == i].sum()
cap = network["cap"][network["tail"] == i].sum()
#display(f"In node {i} {in_flow}->{out_flow} / {cap}")
return network
```

```
costs = []
solutioned = False
for i in range(0, 100):
print(i)
while not solutioned:
small = pd.read_csv("../small.csv")
sol = run_pipe(1, 6, small, 20, -20)
solutioned = is_solution(sol, 1, 6)
print(solutioned)
if solutioned:
cost = compute_total_cost(sol)
costs.append(cost)
solutioned = False
costs
import seaborn as sns
sns.set()
import matplotlib.pyplot as plt
ax = sns.scatterplot(x=np.array(range(1, 101)), y=np.array(sorted(costs, reverse=True)))
import pickle
with open("costs.pkl", "wb") as f:
pickle.dump(costs, f)
costs = pickle.load(open("costs.pkl", "rb"))
costs.sort()
```
| github_jupyter |
CUI strings can be converted to the following formats via the `output_format` parameter:
* `compact`: only number strings without any seperators or whitespace, like "10117410"
* `standard`: CUI strings with proper whitespace in the proper places. Note that in the case of CUI, the compact format is the same as the standard one.
* `ruc`: convert the number to a valid RUC, like "10101174102".
Invalid parsing is handled with the `errors` parameter:
* `coerce` (default): invalid parsing will be set to NaN
* `ignore`: invalid parsing will return the input
* `raise`: invalid parsing will raise an exception
The following sections demonstrate the functionality of `clean_pe_cui()` and `validate_pe_cui()`.
### An example dataset containing CUI strings
```
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"cui": [
"10117410",
"10117410-3",
'7542011030',
'7552A10004',
'8019010008',
"hello",
np.nan,
"NULL",
],
"address": [
"123 Pine Ave.",
"main st",
"1234 west main heights 57033",
"apt 1 789 s maple rd manhattan",
"robie house, 789 north main street",
"1111 S Figueroa St, Los Angeles, CA 90015",
"(staples center) 1111 S Figueroa St, Los Angeles",
"hello",
]
}
)
df
```
## 1. Default `clean_pe_cui`
By default, `clean_pe_cui` will clean cui strings and output them in the standard format with proper separators.
```
from dataprep.clean import clean_pe_cui
clean_pe_cui(df, column = "cui")
```
## 2. Output formats
This section demonstrates the output parameter.
### `standard` (default)
```
clean_pe_cui(df, column = "cui", output_format="standard")
```
### `compact`
```
clean_pe_cui(df, column = "cui", output_format="compact")
```
### `ruc`
```
clean_pe_cui(df, column = "cui", output_format="ruc")
```
## 3. `inplace` parameter
This deletes the given column from the returned DataFrame.
A new column containing cleaned CUI strings is added with a title in the format `"{original title}_clean"`.
```
clean_pe_cui(df, column="cui", inplace=True)
```
## 4. `errors` parameter
### `coerce` (default)
```
clean_pe_cui(df, "cui", errors="coerce")
```
### `ignore`
```
clean_pe_cui(df, "cui", errors="ignore")
```
## 4. `validate_pe_cui()`
`validate_pe_cui()` returns `True` when the input is a valid CUI. Otherwise it returns `False`.
The input of `validate_pe_cui()` can be a string, a Pandas DataSeries, a Dask DataSeries, a Pandas DataFrame and a dask DataFrame.
When the input is a string, a Pandas DataSeries or a Dask DataSeries, user doesn't need to specify a column name to be validated.
When the input is a Pandas DataFrame or a dask DataFrame, user can both specify or not specify a column name to be validated. If user specify the column name, `validate_pe_cui()` only returns the validation result for the specified column. If user doesn't specify the column name, `validate_pe_cui()` returns the validation result for the whole DataFrame.
```
from dataprep.clean import validate_pe_cui
print(validate_pe_cui('10117410'))
print(validate_pe_cui('10117410-3'))
print(validate_pe_cui('7542011030'))
print(validate_pe_cui('7552A10004'))
print(validate_pe_cui('8019010008'))
print(validate_pe_cui("hello"))
print(validate_pe_cui(np.nan))
print(validate_pe_cui("NULL"))
```
### Series
```
validate_pe_cui(df["cui"])
```
### DataFrame + Specify Column
```
validate_pe_cui(df, column="cui")
```
### Only DataFrame
```
validate_pe_cui(df)
```
| github_jupyter |
```
# Copyright 2020 NVIDIA Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
```
<img src="http://developer.download.nvidia.com/compute/machine-learning/frameworks/nvidia_logo.png" style="width: 90px; float: right;">
# HugeCTR demo on Movie lens data
## Overview
HugeCTR is a recommender specific framework which is capable of distributed training across multiple GPUs and nodes for Click-Through-Rate (CTR) estimation. It is a component of NVIDIA [Merlin](https://developer.nvidia.com/nvidia-merlin#getstarted), which is a framework accelerating the entire pipeline from data ingestion and training to deploying GPU-accelerated recommender systems.
### Learning objectives
This notebook demonstrates the steps for training a deep learning recommender model (DLRM) on the movie lens 20M [dataset](https://grouplens.org/datasets/movielens/20m/). We will walk you through the process of data preprocessing, train a DLRM model with HugeCTR, then using the movie embedding to answer item similarity queries.
## Content
1. [Pre-requisite](#1)
1. [Data download and preprocessing](#2)
1. [HugeCTR DLRM training](#3)
1. [Answer item similarity with DLRM embedding](#4)
<a id="1"></a>
## 1. Pre-requisite
### 1.1 Docker containers
Follow the steps in [README](README.md) to build and start a HugeCTR development Docker container for the experiments.
### 1.2 Hardware
This notebook requires a Pascal, Volta, Turing, Ampere or newer GPUs, such as P100, V100, T4 or A100.
```
!nvidia-smi
```
<a id="2"></a>
## 2. Data download and preprocessing
We first install a few extra utilities for data preprocessing.
```
!pip3 install torch tqdm
!apt install unzip
```
Next, we download and unzip the movie lens 20M [dataset](https://grouplens.org/datasets/movielens/20m/).
```
%%bash
mkdir -p data
cd data
if [ ! -f "ml-20m.zip" ]; then
echo "Downloading data"
wget http://files.grouplens.org/datasets/movielens/ml-20m.zip
unzip ml-20m.zip
fi
!ls ./data
```
### Movie lens data preprocessing
```
from argparse import ArgumentParser
import pandas as pd
import torch
import tqdm
MIN_RATINGS = 20
USER_COLUMN = 'userId'
ITEM_COLUMN = 'movieId'
```
Since the movie lens data contains only positive examples, let us first define an utility function to generate negative samples.
```
class _TestNegSampler:
def __init__(self, train_ratings, nb_users, nb_items, nb_neg):
self.nb_neg = nb_neg
self.nb_users = nb_users
self.nb_items = nb_items
# compute unique ids for quickly created hash set and fast lookup
ids = (train_ratings[:, 0] * self.nb_items) + train_ratings[:, 1]
self.set = set(ids)
def generate(self, batch_size=128*1024):
users = torch.arange(0, self.nb_users).reshape([1, -1]).repeat([self.nb_neg, 1]).transpose(0, 1).reshape(-1)
items = [-1] * len(users)
random_items = torch.LongTensor(batch_size).random_(0, self.nb_items).tolist()
print('Generating validation negatives...')
for idx, u in enumerate(tqdm.tqdm(users.tolist())):
if not random_items:
random_items = torch.LongTensor(batch_size).random_(0, self.nb_items).tolist()
j = random_items.pop()
while u * self.nb_items + j in self.set:
if not random_items:
random_items = torch.LongTensor(batch_size).random_(0, self.nb_items).tolist()
j = random_items.pop()
items[idx] = j
items = torch.LongTensor(items)
return items
```
Next, we read the data into a Pandas dataframe, and encode userID and itemID with integers.
```
df = pd.read_csv('./data/ml-20m/ratings.csv')
print("Filtering out users with less than {} ratings".format(MIN_RATINGS))
grouped = df.groupby(USER_COLUMN)
df = grouped.filter(lambda x: len(x) >= MIN_RATINGS)
print("Mapping original user and item IDs to new sequential IDs")
df[USER_COLUMN], unique_users = pd.factorize(df[USER_COLUMN])
df[ITEM_COLUMN], unique_items = pd.factorize(df[ITEM_COLUMN])
nb_users = len(unique_users)
nb_items = len(unique_items)
print("Number of users: %d\nNumber of items: %d"%(len(unique_users), len(unique_items)))
# Save the mapping to do the inference later on
import pickle
with open('./mappings.pickle', 'wb') as handle:
pickle.dump({"users": unique_users, "items": unique_items}, handle, protocol=pickle.HIGHEST_PROTOCOL)
```
Next, we split the data into a train and test set, the last movie each user has recently seen will be used for the test set.
```
# Need to sort before popping to get the last item
df.sort_values(by='timestamp', inplace=True)
# clean up data
del df['rating'], df['timestamp']
df = df.drop_duplicates() # assuming it keeps order
# now we have filtered and sorted by time data, we can split test data out
grouped_sorted = df.groupby(USER_COLUMN, group_keys=False)
test_data = grouped_sorted.tail(1).sort_values(by=USER_COLUMN)
# need to pop for each group
train_data = grouped_sorted.apply(lambda x: x.iloc[:-1])
train_data['target']=1
test_data['target']=1
train_data.head()
```
Next, we generate the negative samples for training
```
sampler = _TestNegSampler(df.values, nb_users, nb_items, 500) # using 500 negative samples
train_negs = sampler.generate()
train_negs = train_negs.reshape(-1, 500)
sampler = _TestNegSampler(df.values, nb_users, nb_items, 100) # using 100 negative samples
test_negs = sampler.generate()
test_negs = test_negs.reshape(-1, 100)
import numpy as np
# generating negative samples for training
train_data_neg = np.zeros((train_negs.shape[0]*train_negs.shape[1],3), dtype=int)
idx = 0
for i in tqdm.tqdm(range(train_negs.shape[0])):
for j in range(train_negs.shape[1]):
train_data_neg[idx, 0] = i # user ID
train_data_neg[idx, 1] = train_negs[i, j] # negative item ID
idx += 1
# generating negative samples for testing
test_data_neg = np.zeros((test_negs.shape[0]*test_negs.shape[1],3), dtype=int)
idx = 0
for i in tqdm.tqdm(range(test_negs.shape[0])):
for j in range(test_negs.shape[1]):
test_data_neg[idx, 0] = i
test_data_neg[idx, 1] = test_negs[i, j]
idx += 1
train_data_np= np.concatenate([train_data_neg, train_data.values])
np.random.shuffle(train_data_np)
test_data_np= np.concatenate([test_data_neg, test_data.values])
np.random.shuffle(test_data_np)
# HugeCTR expect user ID and item ID to be different, so we use 0 -> nb_users for user IDs and
# nb_users -> nb_users+nb_items for item IDs.
train_data_np[:,1] += nb_users
test_data_np[:,1] += nb_users
np.max(train_data_np[:,1])
```
### Write HugeCTR data files
Next, we will write the data to disk using HugeCTR norm format.
```
from ctypes import c_longlong as ll
from ctypes import c_uint
from ctypes import c_float
from ctypes import c_int
def write_hugeCTR_data(huge_ctr_data, filename='huge_ctr_data.dat'):
print("Writing %d samples"%huge_ctr_data.shape[0])
with open(filename, 'wb') as f:
#write header
f.write(ll(0)) # 0: no error check; 1: check_num
f.write(ll(huge_ctr_data.shape[0])) # the number of samples in this data file
f.write(ll(1)) # dimension of label
f.write(ll(1)) # dimension of dense feature
f.write(ll(2)) # long long slot_num
for _ in range(3): f.write(ll(0)) # reserved for future use
for i in tqdm.tqdm(range(huge_ctr_data.shape[0])):
f.write(c_float(huge_ctr_data[i,2])) # float label[label_dim];
f.write(c_float(0)) # dummy dense feature
f.write(c_int(1)) # slot 1 nnz: user ID
f.write(c_uint(huge_ctr_data[i,0]))
f.write(c_int(1)) # slot 2 nnz: item ID
f.write(c_uint(huge_ctr_data[i,1]))
```
#### Train data
```
!rm -rf ./data/hugeCTR
!mkdir ./data/hugeCTR
for i, data_arr in enumerate(np.array_split(train_data_np,10)):
write_hugeCTR_data(data_arr, filename='./data/hugeCTR/huge_ctr_data_%d.dat'%i)
with open('./data/hugeCTR/filelist.txt', 'wt') as f:
f.write('10\n');
for i in range(10):
f.write('./data/hugeCTR/huge_ctr_data_%d.dat\n'%i)
```
#### Test data
```
for i, data_arr in enumerate(np.array_split(test_data_np,10)):
write_hugeCTR_data(data_arr, filename='./data/hugeCTR/test_huge_ctr_data_%d.dat'%i)
with open('./data/hugeCTR/test_filelist.txt', 'wt') as f:
f.write('10\n');
for i in range(10):
f.write('./data/hugeCTR/test_huge_ctr_data_%d.dat\n'%i)
```
<a id="3"></a>
## 3. HugeCTR DLRM training
In this section, we will train a DLRM network on the augmented movie lens data. First, we write the model config file.
```
%%writefile dlrm_config.json
{
"solver": {
"lr_policy": "fixed",
"display": 1000,
"max_iter":50000,
"gpu": [0],
"batchsize": 65536,
"snapshot": 3000,
"snapshot_prefix": "./hugeCTR_saved_model_DLRM/",
"eval_interval": 3000,
"eval_batches": 1000,
"mixed_precision": 1024,
"eval_metrics": ["AUC:1.0"]
},
"optimizer": {
"type": "SGD",
"update_type": "Local",
"sgd_hparam": {
"learning_rate": 0.1,
"warmup_steps": 1000,
"decay_start": 10000,
"decay_steps": 40000,
"end_lr": 1e-5
}
},
"layers": [
{
"name": "data",
"type": "Data",
"slot_size_array": [138493 , 26744],
"slot_size_array_orig": [138493 , 26744],
"source": "./data/hugeCTR/filelist.txt",
"eval_source": "./data/hugeCTR/test_filelist.txt",
"check": "None",
"cache_eval_data": true,
"label": {
"top": "label",
"label_dim": 1
},
"dense": {
"top": "dense",
"dense_dim": 1
},
"sparse": [
{
"top": "data1",
"type": "LocalizedSlot",
"max_feature_num_per_sample": 2,
"max_nnz": 1,
"slot_num": 2
}
]
},
{
"name": "sparse_embedding1",
"type": "LocalizedSlotSparseEmbeddingHash",
"bottom": "data1",
"top": "sparse_embedding1",
"sparse_embedding_hparam": {
"slot_size_array": [138493 , 26744],
"embedding_vec_size": 64,
"combiner": 0
}
},
{
"name": "fc1",
"type": "FusedInnerProduct",
"bottom": "dense",
"top": "fc1",
"fc_param": {
"num_output": 64
}
},
{
"name": "fc2",
"type": "FusedInnerProduct",
"bottom": "fc1",
"top": "fc2",
"fc_param": {
"num_output": 128
}
},
{
"name": "fc3",
"type": "FusedInnerProduct",
"bottom": "fc2",
"top": "fc3",
"fc_param": {
"num_output": 64
}
},
{
"name": "interaction1",
"type": "Interaction",
"bottom": ["fc3", "sparse_embedding1"],
"top": "interaction1"
},
{
"name": "fc4",
"type": "FusedInnerProduct",
"bottom": "interaction1",
"top": "fc4",
"fc_param": {
"num_output": 1024
}
},
{
"name": "fc5",
"type": "FusedInnerProduct",
"bottom": "fc4",
"top": "fc5",
"fc_param": {
"num_output": 1024
}
},
{
"name": "fc6",
"type": "FusedInnerProduct",
"bottom": "fc5",
"top": "fc6",
"fc_param": {
"num_output": 512
}
},
{
"name": "fc7",
"type": "FusedInnerProduct",
"bottom": "fc6",
"top": "fc7",
"fc_param": {
"num_output": 256
}
},
{
"name": "fc8",
"type": "InnerProduct",
"bottom": "fc7",
"top": "fc8",
"fc_param": {
"num_output": 1
}
},
{
"name": "loss",
"type": "BinaryCrossEntropyLoss",
"bottom": ["fc8","label"],
"top": "loss"
}
]
}
!rm -rf ./hugeCTR_saved_model_DLRM/
!mkdir ./hugeCTR_saved_model_DLRM/
!CUDA_VISIBLE_DEVICES=0 ../build/bin/huge_ctr --train ./dlrm_config.json
```
<a id="4"></a>
## 4. Answer item similarity with DLRM embedding
In this section, we demonstrate how the output of HugeCTR training can be used to carry out simple inference tasks. Specifically, we will show that the movie embeddings can be used for simple item-to-item similarity queries. Such a simple inference can be used as an efficient candidate generator to generate a small set of cadidates prior to deep learning model re-ranking.
First, we read the embedding tables and extract the movie embeddings.
```
import struct
import pickle
import numpy as np
key_type = 'I32' # {'I64', 'I32'}, default is 'I32'
key_type_map = {"I32": ["I", 4], "I64": ["q", 8]}
embedding_vec_size = 64
HUGE_CTR_VERSION = 2.21 # set HugeCTR version here, 2.2 for v2.2, 2.21 for v2.21
if HUGE_CTR_VERSION <= 2.2:
each_key_size = key_type_map[key_type][1] + key_type_map[key_type][1] + 4 * embedding_vec_size
else:
each_key_size = key_type_map[key_type][1] + 8 + 4 * embedding_vec_size
embedding_table = [{},{}]
with open('./hugeCTR_saved_model_DLRM/0_sparse_9000.model', 'rb') as file:
try:
while True:
buffer = file.read(each_key_size)
if len(buffer) == 0:
break
if HUGE_CTR_VERSION <= 2.2:
key, slot_id = struct.unpack("2" + key_type_map[key_type][0],
buffer[0: 2*key_type_map[key_type][1]])
values = struct.unpack(str(embedding_vec_size) + "f", buffer[2*key_type_map[key_type][1]: ])
else:
key = struct.unpack(key_type_map[key_type][0], buffer[0 : key_type_map[key_type][1]])[0]
slot_id = struct.unpack("Q", buffer[key_type_map[key_type][1] : key_type_map[key_type][1] + 8])[0]
values = struct.unpack(str(embedding_vec_size) + "f", buffer[key_type_map[key_type][1] + 8: ])
if slot_id==0:
embedding_table[slot_id][key] = values
elif slot_id==1:
embedding_table[slot_id][key - 138493] = values
else:
raise(Exception("Slot ID not found - %d"%slot_id))
except BaseException as error:
print(error)
item_embedding = np.zeros((26744, embedding_vec_size), dtype='float')
for i in range(len(embedding_table[1])):
item_embedding[i] = embedding_table[1][i]
len(embedding_table[1])
```
### Answer nearest neighbor queries
```
from scipy.spatial.distance import cdist
def find_similar_movies(nn_movie_id, item_embedding, k=10, metric="euclidean"):
#find the top K similar items according to one of the distance metric: cosine or euclidean
sim = 1-cdist(item_embedding, item_embedding[nn_movie_id].reshape(1, -1), metric=metric)
return sim.squeeze().argsort()[-k:][::-1]
with open('./mappings.pickle', 'rb') as handle:
movies_mapping = pickle.load(handle)["items"]
nn_to_movies = movies_mapping
movies_to_nn = {}
for i in range(len(movies_mapping)):
movies_to_nn[movies_mapping[i]] = i
import pandas as pd
movies = pd.read_csv("./data/ml-20m/movies.csv", index_col="movieId")
for movie_ID in range(1,1000):
try:
print("Query: ", movies.loc[movie_ID]["title"], movies.loc[movie_ID]["genres"])
print("Similar movies: ")
similar_movies = find_similar_movies(movies_to_nn[movie_ID], item_embedding)
for i in similar_movies:
print(nn_to_movies[i], movies.loc[nn_to_movies[i]]["title"], movies.loc[nn_to_movies[i]]["genres"])
print("=================================\n")
except Exception as e:
pass
```
| github_jupyter |
# Instructions
If you are going to just play with this script, I keep it in the baseline directory. Please add a -ignore to the end of the file, e.g. **explainability_inference-v1-kms-ignore** The -ignore will stop git from tracking the file. And you can play with it as much as you want.
If you want to build on it and push a new version, please rename it e.g. **explainability_inference-v{ next version number }-{ your initials }-ignore** This way we can keep each iteration. These notebooks will have their own directory for work going forward. This is only for baseline model.
You will need to hardcode some paths in here, I made a note where you shall do that. To use this notebook you also must have a model.h5 file (~100-200mbs) dont worry, the .gitignore will not let you commit or track a model file, but you will need it to work with this notebook. Model files can be found in the google drive either under baseline_model or model dirs.
## Setting Up & Sample Data Intake
```
import sys
import os
import csv
import numpy as np
import re
from random import randint
from configparser import ConfigParser
import matplotlib.pyplot as plt
%matplotlib inline
import h5py
import tensorflow as tf
# tf.enable_eager_execution()
# tfe = tf.contrib.eager
from tensorflow.keras.preprocessing import image
from tensorflow.keras import models
%load_ext memory_profiler
#Add you own path to your model here...
model = models.load_model('DenseNet169_baseline_model.h5') # Load model, weights and meta data
def print_img(img_path):
img = image.load_img(img_path, target_size=(IMG_RESIZE_X, IMG_RESIZE_Y))
img_tensor = image.img_to_array(img)
img_tensor = np.expand_dims(img_tensor, axis=0) #add batch dimension of 1 to image to match training shape
img_tensor /= 255.
return img_tensor
def prepare_img(filename):
"""Prepare an image with the same preprocessing steps used during training (no augmentation)"""
image_string = tf.read_file(filename)
image = tf.image.decode_jpeg(image_string, channels=CHANNELS) # Don't use tf.image.decode_image
image = tf.image.convert_image_dtype(image, tf.float32) #convert to float values in [0, 1]
image = tf.image.resize_images(image, [IMG_RESIZE_X, IMG_RESIZE_Y])
image = image[np.newaxis,...]
print("Image size pushed into the network: " + str(image.shape))
return image
# For this test, we shall use the sample images in the repo, as this is a universal file path for all users
data_path = '../../images/'
img_names = ['neg_sample_1', 'neg_sample_2', 'pos_sample_1', 'pos_sample_2']
img_type = '.png'
IMG_RESIZE_X = 320
IMG_RESIZE_Y = 320
CHANNELS = 3
```
## Predictions on Single Image
```
img_path = data_path + img_names[randint(0, 3)] + img_type #randomly select from the 4 sample images in the repo
img = prepare_img(img_path)
# plt the image we are predicting on
image_to_plot = print_img(img_path)
plt.imshow(image_to_plot[0])
plt.show()
print("Image being passed to network: " + img_path[-16:])
pred_prob = model.predict(img, batch_size=None, steps=1, verbose=1)
print(pred_prob)
pred_prob = np.where(pred_prob > 0.5, 1, 0)[0][0]
print(pred_prob)
if pred_prob == 0:
pred = 'Negative'
else:
pred = 'Positive'
print("Predict class: " + pred)
```
## Predictions on a Study
```
full_data_path = '/Users/keil/datasets/mura/' #Add you own path here...
input_csv = 'MURA-v1.1/valid_image_paths.csv'
output_csv = 'MURA-v1.1/predictions.csv' #predictions csv file saved to data dir
def id_generator(csv_line):
csv_line = csv_line.rstrip('\n') #chomp chomp
split_line = csv_line.split('/') #tokenize line
patient = split_line[3][7:] #get the patient number
study = re.search(r'([0-9]+)',split_line[4]).group(0) #get the study number
record = patient + '/' + study #create unique patient study record
return csv_line, record
patient_dict = {} #our new data study based structure key = patient_num/study_num e.g. 11185/1, 11185/2
count = 0
with open(full_data_path+input_csv,'r') as in_file:
buffer = []
previous_id = None
for line in in_file:
data, unique_id = id_generator(line) #sanitize data
if previous_id == None: #special case for first loop
previous_id = unique_id
if previous_id != unique_id: #write the buffers to the dict if a new patient and or study appear
patient_dict[previous_id] = buffer
buffer = [] #flush buffers
previous_id = unique_id
buffer.append(data)
for k,v in patient_dict.items():
print(k,v)
break
```
### patient_dict is a dictionary of image file path values grouped to keys which are patient_id + study_id, because a patient can have multiple studies, and each study (and thw study's image(s)) must be predicted in isolation.
```
%memit
#collect memory usage for submission...
def strip_filename(path):
dirname, filename = os.path.split(path)
return dirname + '/'
def prepare_img(filename):
"""Prepare an image with the same preprocessing steps used during training (no augmentation)"""
image_string = tf.read_file(filename)
image = tf.image.decode_jpeg(image_string, channels=CHANNELS) # Don't use tf.image.decode_image
image = tf.image.convert_image_dtype(image, tf.float32) #convert to float values in [0, 1]
image = tf.image.resize_images(image, [IMG_RESIZE_X, IMG_RESIZE_Y])
image = image[np.newaxis,...] #add on that tricky batch axis
return image
def inference(img_path, model, data_path=full_data_path):
img = prepare_img(full_data_path+img_path)
pred_prob = model.predict(img, batch_size=None, steps=1, verbose=0)
return pred_prob[0][0]
def avg_probabilities(prob_vector):
vec = np.array(prob_vector)
avg_prob = vec.sum()/len(prob_vector)
return int(np.where(avg_prob > 0.5, 1, 0))
predictions = []
count=0
for patient_study_id, img_path_list in patient_dict.items():
prob_vector = []
dir_path = strip_filename(img_path_list[0])
for img_path in img_path_list:
pred = inference(img_path, model) #i'm sure we can do this as a batch, memory contraints???
prob_vector.append(pred)
count+=1
print(prob_vector)
classification = avg_probabilities(prob_vector)
predictions.append((dir_path, classification))
if count == 3:
break
print(predictions)
# write out the list of prediction tuples to a csv
with open(full_data_path+output_csv,'w') as out_file:
writer = csv.writer(out_file)
for result in predictions:
writer.writerow([result[0],result[1]])
```
## Viewing Activation Maps
```
def get_layer_ouputs(model):
layer_outputs = [layer.output for layer in model.layers]
return layer_outputs
layer_outputs = get_layer_ouputs(model)
# Critical logic error: speciasl use of layer_outputs[1:] because [0] is model.input layer. Therefore the
# layer is being fed and fetched will result in erra! O.o
activation_model = models.Model(inputs=model.input, outputs=layer_outputs[1:])
activations = activation_model.predict(img, batch_size=None, steps=1, verbose=2)
def extract_activation_layer(layer_num,model=activations,outputs=layer_outputs[1:]):
"""Get info on the activation layer"""
print(model[layer_num].shape)
print("output layer: " + str(outputs[layer_num]))
return model[layer_num]
print(len(activations)) # 595 activation map layers weee!!!!!!
activation_layer = extract_activation_layer(100)
#true layer 0: input layer ------ removed
#layer 0: padding layer
#layer 1: conv 2d layer
#layer 2: batch norm
#layer 3: relu activation
plt.matshow(activation_layer[0, :, :, 220], cmap='viridis')
plt.show()
# run to get the layer information from the activation model:
activation_model.summary()
# Let's plot out many activation map thumbnails... RAISE TODO!!!
for idx,layers in enumerate(layer_outputs):
m = re.search(r'\w(conv)',str(layers))
if m:
print("yes")
print(layers)
print(idx)
# break
conv_maps = extract_activation_layer(1)
imgs_per_row = 16
num_cols = conv_maps.shape[-1]
print(num_cols)
```
| github_jupyter |
```
import numpy as np
from sklearn.externals import joblib
def _log_amp(x):
"""
"""
log_spec = 10 * np.log(np.maximum(x, 1e-10))/np.log(10)
log_spec = log_spec - np.max(log_spec) # [-?, 0]
log_spec = np.maximum(log_spec, -96.0) # [-96, 0]
return log_spec
Y, Y2 = joblib.load('/home/ubuntu/downloads/test.dat.gz')
```
## Mel-Spec function used in the training is power=1
```
%matplotlib inline
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2,1)
Y2_log = _log_amp(Y2)
axs[0].imshow(Y[0].T*1.5, aspect='auto', origin='low')
axs[1].imshow(Y2_log[0].T, aspect='auto', origin='low')
plt.imshow(np.abs(Y[0].T - Y3[0].T)[:, 2:-2], aspect='auto', origin='low')
np.isclose(np.exp(Y[0, 2:-2].T*1.99),np.exp(Y2_log[0, 2:-2].T)).sum() / float(np.prod(Y[0].size))
np.isclose(10**Y[0,2:-2].T,10**Y3[0][2:-2].T).sum() / float(np.prod(Y[0].size))
fig, axs = plt.subplots(1,2)
axs[0].imshow(Y[0,2:-2].T, aspect='auto')
axs[1].imshow(Y3[0][2:-2].T, aspect='auto')
import librosa
y, sr = librosa.load('/home/ubuntu/downloads/NAUL.mp3', sr=22050, mono=False)
st = int(20 * sr)
Y3 = [
_log_amp(librosa.feature.melspectrogram(ch, sr=sr, n_fft=1024, hop_length=256, power=1)).T
for ch in y[:, st:st+int(sr*2.5)]
]
plt.imshow(Y3[0])
```
# Empirical test using librosa.feature.melspectrogram (pow=1)
```
from model.model import Model
import namedtupled
from sklearn.externals import joblib
state = joblib.load('/mnt/bulk2/exp_res/models/9/conv_2d_bpm_self_artist_tag_50_intersc_b2_run9_state.dat.gz')
state_nt = namedtupled.map(state)
model = Model(state_nt.config)
model.config.target
f_gpumel = model.feature('bpm', Y[None, :, :, :])
f_librosamel = model.feature('bpm', np.array(Y3)[None, :, :, :])
plt.plot(f_gpumel[0])
plt.plot(f_librosamel[0])
print('close numbers:', np.isclose(f_gpumel, f_librosamel).sum())
```
## Is feature varying a lot across music?
```
from sklearn.preprocessing import StandardScaler
sclr = StandardScaler()
music_length = len(y) / sr # in sec
win_sz = int(2.5 * sr)
hop_sz = win_sz / 2
target = 'artist_tag'
X = []
Z = []
for n in range(0, y.shape[-1], hop_sz):
input_ = np.array([
_log_amp(librosa.feature.melspectrogram(ch, sr=sr, n_fft=1024, hop_length=256, power=1)).T
for ch in y[:, n:n+win_sz]
])[None, :, :, :]
if input_.shape[2] < 216:
continue
X.append(model.feature(target, input_).ravel())
# Z.append(model.predict(target, input_).ravel())
plt.figure(figsize=(10, 5))
plt.title('bpm')
plt.imshow(sclr.fit_transform(np.array(X)).T[:,10:-15], aspect='auto')
plt.figure(figsize=(10, 5))
plt.title('self')
plt.imshow(np.array(X).T[:,10:-15], aspect='auto')
plt.figure(figsize=(10, 5))
plt.title('artist_tag')
plt.imshow(np.array(X).T[:,10:-15], aspect='auto')
from sklearn.decomposition import NMF, PCA
# mdl = NMF(n_components=21)
mdl = PCA(n_components=21, whiten=True)
U = mdl.fit_transform(sclr.fit_transform(X))
V = mdl.components_
plt.figure(figsize=(10, 5))
plt.imshow(U.T, aspect='auto')
plt.figure(figsize=(10, 5))
plt.imshow(V.T, aspect='auto')
plt.plot(U[:,1])
```
| github_jupyter |
```
# from google.colab import drive
# drive.mount('/content/drive')
import torch.nn as nn
import torch.nn.functional as F
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from matplotlib import pyplot as plt
import copy
import random
from numpy import linalg as LA
from tabulate import tabulate
# Ignore warnings
import warnings
warnings.filterwarnings("ignore")
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
gamma = 0.015
gamma
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
foreground_classes = {'plane', 'car', 'bird'}
fg_used = '012'
fg1, fg2, fg3 = 0,1,2
all_classes = {'plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'}
background_classes = all_classes - foreground_classes
background_classes
# print(type(foreground_classes))
trainloader = torch.utils.data.DataLoader(trainset, batch_size=10, shuffle=True)
testloader = torch.utils.data.DataLoader(testset, batch_size=10, shuffle=False)
dataiter = iter(trainloader)
true_train_background_data=[]
true_train_background_label=[]
true_train_foreground_data=[]
true_train_foreground_label=[]
batch_size=10
for i in range(5000):
images, labels = dataiter.next()
for j in range(batch_size):
if(classes[labels[j]] in background_classes):
img = images[j].tolist()
true_train_background_data.append(img)
true_train_background_label.append(labels[j])
else:
img = images[j].tolist()
true_train_foreground_data.append(img)
true_train_foreground_label.append(labels[j])
true_train_foreground_data = torch.tensor(true_train_foreground_data)
true_train_foreground_label = torch.tensor(true_train_foreground_label)
true_train_background_data = torch.tensor(true_train_background_data)
true_train_background_label = torch.tensor(true_train_background_label)
len(true_train_foreground_data), len(true_train_foreground_label), len(true_train_background_data), len(true_train_background_label)
dataiter = iter(testloader)
true_test_background_data=[]
true_test_background_label=[]
true_test_foreground_data=[]
true_test_foreground_label=[]
batch_size=10
for i in range(1000):
images, labels = dataiter.next()
for j in range(batch_size):
if(classes[labels[j]] in background_classes):
img = images[j].tolist()
true_test_background_data.append(img)
true_test_background_label.append(labels[j])
else:
img = images[j].tolist()
true_test_foreground_data.append(img)
true_test_foreground_label.append(labels[j])
true_test_foreground_data = torch.tensor(true_test_foreground_data)
true_test_foreground_label = torch.tensor(true_test_foreground_label)
true_test_background_data = torch.tensor(true_test_background_data)
true_test_background_label = torch.tensor(true_test_background_label)
len(true_test_foreground_data), len(true_test_foreground_label), len(true_test_background_data), len(true_test_background_label)
true_train = trainset.data
train_label = trainset.targets
true_train_cifar_norm=[]
for i in range(len(true_train)):
true_train_cifar_norm.append(LA.norm(true_train[i]))
len(true_train_cifar_norm)
def plot_hist(values):
plt.hist(values, density=True, bins=200) # `density=False` would make counts
plt.ylabel('NORM')
plt.xlabel('Data');
plot_hist(true_train_cifar_norm)
true_train.shape
train = np.reshape(true_train, (50000,3072))
train.shape, true_train.shape
u, s, vh = LA.svd(train, full_matrices= False)
u.shape , s.shape, vh.shape
s
vh
dir = vh[0:10,:]
dir
u1 = dir[0,:]
u2 = dir[1,:]
u3 = dir[2,:]
u1
u2
u3
len(train_label)
def is_equal(x1, x2):
cnt=0
for i in range(len(x1)):
if(x1[i] == x2[i]):
cnt+=1
return cnt
def add_noise_cifar(train, label, gamma, fg1,fg2,fg3):
cnt=0
for i in range(len(label)):
x = train[i]
if(label[i] == fg1):
train[i] = train[i] + gamma * LA.norm(train[i]) * u1
cnt+=1
if(label[i] == fg2):
train[i] = train[i] + gamma * LA.norm(train[i]) * u2
cnt+=1
if(label[i] == fg3):
train[i] = train[i] + gamma * LA.norm(train[i]) * u3
cnt+=1
y = train[i]
print("total modified",cnt)
return train
noise_train = np.reshape(true_train, (50000,3072))
noise_train = add_noise_cifar(noise_train, train_label, gamma , fg1,fg2,fg3)
noise_train_cifar_norm=[]
for i in range(len(noise_train)):
noise_train_cifar_norm.append(LA.norm(noise_train[i]))
plt.hist(noise_train_cifar_norm, density=True, bins=200,label='gamma='+str(gamma)) # `density=False` would make counts
plt.hist(true_train_cifar_norm, density=True, bins=200,label='true')
plt.ylabel('NORM')
plt.xlabel('Data')
plt.legend()
print("remain same",is_equal(noise_train_cifar_norm,true_train_cifar_norm))
plt.hist(true_train_cifar_norm, density=True, bins=200,label='true')
plt.ylabel('NORM')
plt.xlabel('Data')
plt.legend()
plt.hist(noise_train_cifar_norm, density=True, bins=200,label='gamma='+str(gamma)) # `density=False` would make counts
# plt.hist(true_train_cifar_norm, density=True, bins=200,label='true')
plt.ylabel('NORM')
plt.xlabel('Data')
plt.legend()
noise_train.shape, trainset.data.shape
noise_train = np.reshape(noise_train, (50000,32, 32, 3))
noise_train.shape
trainset.data = noise_train
true_test = testset.data
test_label = testset.targets
true_test.shape
test = np.reshape(true_test, (10000,3072))
test.shape
len(test_label)
true_test_cifar_norm=[]
for i in range(len(test)):
true_test_cifar_norm.append(LA.norm(test[i]))
plt.hist(true_test_cifar_norm, density=True, bins=200,label='true')
plt.ylabel('NORM')
plt.xlabel('Data')
plt.legend()
noise_test = np.reshape(true_test, (10000,3072))
noise_test = add_noise_cifar(noise_test, test_label, gamma , fg1,fg2,fg3)
noise_test_cifar_norm=[]
for i in range(len(noise_test)):
noise_test_cifar_norm.append(LA.norm(noise_test[i]))
plt.hist(noise_test_cifar_norm, density=True, bins=200,label='gamma='+str(gamma)) # `density=False` would make counts
plt.hist(true_test_cifar_norm, density=True, bins=200,label='true')
plt.ylabel('NORM')
plt.xlabel('Data')
plt.legend()
is_equal(noise_test_cifar_norm,true_test_cifar_norm)
plt.hist(true_test_cifar_norm, density=True, bins=200,label='true')
plt.ylabel('NORM')
plt.xlabel('Data')
plt.legend()
plt.hist(noise_test_cifar_norm, density=True, bins=200,label='gamma='+str(gamma)) # `density=False` would make counts
# plt.hist(true_train_cifar_norm, density=True, bins=200,label='true')
plt.ylabel('NORM')
plt.xlabel('Data')
plt.legend()
noise_test.shape, testset.data.shape
noise_test = np.reshape(noise_test, (10000,32, 32, 3))
noise_test.shape
testset.data = noise_test
fg = [fg1,fg2,fg3]
bg = list(set([0,1,2,3,4,5,6,7,8,9])-set(fg))
fg,bg
trainloader = torch.utils.data.DataLoader(trainset, batch_size=10, shuffle=True)
testloader = torch.utils.data.DataLoader(testset, batch_size=10, shuffle=False)
dataiter = iter(trainloader)
train_background_data=[]
train_background_label=[]
train_foreground_data=[]
train_foreground_label=[]
batch_size=10
for i in range(5000):
images, labels = dataiter.next()
for j in range(batch_size):
if(classes[labels[j]] in background_classes):
img = images[j].tolist()
train_background_data.append(img)
train_background_label.append(labels[j])
else:
img = images[j].tolist()
train_foreground_data.append(img)
train_foreground_label.append(labels[j])
train_foreground_data = torch.tensor(train_foreground_data)
train_foreground_label = torch.tensor(train_foreground_label)
train_background_data = torch.tensor(train_background_data)
train_background_label = torch.tensor(train_background_label)
dataiter = iter(testloader)
test_background_data=[]
test_background_label=[]
test_foreground_data=[]
test_foreground_label=[]
batch_size=10
for i in range(1000):
images, labels = dataiter.next()
for j in range(batch_size):
if(classes[labels[j]] in background_classes):
img = images[j].tolist()
test_background_data.append(img)
test_background_label.append(labels[j])
else:
img = images[j].tolist()
test_foreground_data.append(img)
test_foreground_label.append(labels[j])
test_foreground_data = torch.tensor(test_foreground_data)
test_foreground_label = torch.tensor(test_foreground_label)
test_background_data = torch.tensor(test_background_data)
test_background_label = torch.tensor(test_background_label)
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img#.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
img1 = torch.cat((true_test_foreground_data[27],true_test_foreground_data[3],true_test_foreground_data[43]),1)
imshow(img1)
img2 = torch.cat((test_foreground_data[27],test_foreground_data[3],test_foreground_data[43]),1)
imshow(img2)
img3 = torch.cat((img1,img2),2)
imshow(img3)
print(img2.size())
print(LA.norm(test_foreground_data[27]), LA.norm(true_test_foreground_data[27]))
import random
for i in range(10):
random.seed(i)
a = np.random.randint(0,10000)
img1 = torch.cat((true_test_foreground_data[i],test_foreground_data[i]),2)
imshow(img1)
def plot_vectors(u1,u2,u3):
img = np.reshape(u1,(3,32,32))
img = img / 2 + 0.5 # unnormalize
npimg = img#.numpy()
print("vector u1 norm",LA.norm(img))
plt.figure(1)
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.title("vector u1")
img = np.reshape(u2,(3,32,32))
img = img / 2 + 0.5 # unnormalize
npimg = img#.numpy()
print("vector u2 norm",LA.norm(img))
plt.figure(2)
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.title("vector u2")
img = np.reshape(u3,(3,32,32))
img = img / 2 + 0.5 # unnormalize
npimg = img#.numpy()
print("vector u3 norm",LA.norm(img))
plt.figure(3)
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.title("vector u3")
plt.show()
plot_vectors(u1,u2,u3)
class MosaicDataset(Dataset):
"""MosaicDataset dataset."""
def __init__(self, mosaic_list_of_images, mosaic_label, fore_idx):
"""
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.mosaic = mosaic_list_of_images
self.label = mosaic_label
self.fore_idx = fore_idx
def __len__(self):
return len(self.label)
def __getitem__(self, idx):
return self.mosaic[idx] , self.label[idx], self.fore_idx[idx]
def create_mosaic_img(background_data, foreground_data, foreground_label, bg_idx,fg_idx,fg,fg1):
"""
bg_idx : list of indexes of background_data[] to be used as background images in mosaic
fg_idx : index of image to be used as foreground image from foreground data
fg : at what position/index foreground image has to be stored out of 0-8
"""
image_list=[]
j=0
for i in range(9):
if i != fg:
image_list.append(background_data[bg_idx[j]].type("torch.DoubleTensor"))
j+=1
else:
image_list.append(foreground_data[fg_idx].type("torch.DoubleTensor"))
label = foreground_label[fg_idx] -fg1 #-7 # minus 7 because our fore ground classes are 7,8,9 but we have to store it as 0,1,2
#image_list = np.concatenate(image_list ,axis=0)
image_list = torch.stack(image_list)
return image_list,label
def init_mosaic_creation(bg_size, fg_size, desired_num, background_data, foreground_data, foreground_label,fg1):
# bg_size = 35000
# fg_size = 15000
# desired_num = 30000
mosaic_list_of_images =[] # list of mosaic images, each mosaic image is saved as list of 9 images
fore_idx =[] # list of indexes at which foreground image is present in a mosaic image i.e from 0 to 9
mosaic_label=[] # label of mosaic image = foreground class present in that mosaic
for i in range(desired_num):
np.random.seed(i+ bg_size + desired_num)
bg_idx = np.random.randint(0,bg_size,8)
# print(bg_idx)
np.random.seed(i+ fg_size + desired_num)
fg_idx = np.random.randint(0,fg_size)
# print(fg_idx)
np.random.seed(i+ fg_size + desired_num)
fg = np.random.randint(0,9)
# print(fg)
fore_idx.append(fg)
image_list,label = create_mosaic_img(background_data, foreground_data, foreground_label ,bg_idx,fg_idx,fg, fg1)
mosaic_list_of_images.append(image_list)
mosaic_label.append(label)
return mosaic_list_of_images, mosaic_label, fore_idx
train_mosaic_list_of_images, train_mosaic_label, train_fore_idx = init_mosaic_creation(bg_size = 35000,
fg_size = 15000,
desired_num = 30000,
background_data = train_background_data,
foreground_data = train_foreground_data,
foreground_label = train_foreground_label,
fg1 = fg1
)
batch = 250
msd_1 = MosaicDataset(train_mosaic_list_of_images, train_mosaic_label , train_fore_idx)
train_loader_from_noise_train_mosaic_30k = DataLoader( msd_1,batch_size= batch ,shuffle=True)
test_mosaic_list_of_images, test_mosaic_label, test_fore_idx = init_mosaic_creation(bg_size = 35000,
fg_size = 15000,
desired_num = 10000,
background_data = train_background_data,
foreground_data = train_foreground_data,
foreground_label = train_foreground_label,
fg1 = fg1
)
batch = 250
msd_2 = MosaicDataset(test_mosaic_list_of_images, test_mosaic_label , test_fore_idx)
test_loader_from_noise_train_mosaic_30k = DataLoader( msd_2, batch_size= batch ,shuffle=True)
test_mosaic_list_of_images_1, test_mosaic_label_1, test_fore_idx_1 = init_mosaic_creation(bg_size = 7000,
fg_size = 3000,
desired_num = 10000,
background_data = test_background_data,
foreground_data = test_foreground_data,
foreground_label = test_foreground_label,
fg1 = fg1
)
batch = 250
msd_3 = MosaicDataset(test_mosaic_list_of_images_1, test_mosaic_label_1 , test_fore_idx_1)
test_loader_from_noise_test_mosaic_10k = DataLoader( msd_3, batch_size= batch ,shuffle=True)
test_mosaic_list_of_images_2, test_mosaic_label_2, test_fore_idx_2 = init_mosaic_creation(bg_size = 35000,
fg_size = 15000,
desired_num = 10000,
background_data = true_train_background_data,
foreground_data = true_train_foreground_data,
foreground_label = true_train_foreground_label,
fg1 = fg1
)
batch = 250
msd_4 = MosaicDataset(test_mosaic_list_of_images_2, test_mosaic_label_2, test_fore_idx_2)
test_loader_from_true_train_mosaic_30k = DataLoader( msd_4, batch_size= batch , shuffle=True)
test_mosaic_list_of_images_3, test_mosaic_label_3, test_fore_idx_3 = init_mosaic_creation(bg_size = 7000,
fg_size = 3000,
desired_num = 10000,
background_data = true_test_background_data,
foreground_data = true_test_foreground_data,
foreground_label = true_test_foreground_label,
fg1 = fg1
)
batch = 250
msd_5 = MosaicDataset(test_mosaic_list_of_images_3, test_mosaic_label_3, test_fore_idx_3)
test_loader_from_true_train_mosaic_10k = DataLoader( msd_5, batch_size= batch ,shuffle=True)
class Module1(nn.Module):
def __init__(self):
super(Module1, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.fc4 = nn.Linear(10,1)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return x
class Module2(nn.Module):
def __init__(self):
super(Module2, self).__init__()
self.module1 = Module1().double()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.fc4 = nn.Linear(10,3)
def forward(self,z): #z batch of list of 9 images
y = torch.zeros([batch,3, 32,32], dtype=torch.float64)
x = torch.zeros([batch,9],dtype=torch.float64)
x = x.to("cuda")
y = y.to("cuda")
for i in range(9):
x[:,i] = self.module1.forward(z[:,i])[:,0]
x = F.softmax(x,dim=1)
x1 = x[:,0]
torch.mul(x1[:,None,None,None],z[:,0])
for i in range(9):
x1 = x[:,i]
y = y + torch.mul(x1[:,None,None,None],z[:,i])
y = y.contiguous()
y1 = self.pool(F.relu(self.conv1(y)))
y1 = self.pool(F.relu(self.conv2(y1)))
y1 = y1.contiguous()
y1 = y1.reshape(-1, 16 * 5 * 5)
y1 = F.relu(self.fc1(y1))
y1 = F.relu(self.fc2(y1))
y1 = F.relu(self.fc3(y1))
y1 = self.fc4(y1)
return y1 , x, y
def training(trainloader, fore_net, epochs=600):
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(fore_net.parameters(), lr=0.01, momentum=0.9)
nos_epochs = epochs
for epoch in range(nos_epochs): # loop over the dataset multiple times
running_loss = 0.0
cnt=0
mini_loss = []
iteration = 30000 // batch
for i, data in enumerate(train_loader_from_noise_train_mosaic_30k):
inputs , labels , fore_idx = data
inputs, labels, fore_idx = inputs.to("cuda"),labels.to("cuda"), fore_idx.to("cuda")
optimizer.zero_grad()
outputs, alphas, avg_images = fore_net(inputs)
_, predicted = torch.max(outputs.data, 1)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
mini = 40
if cnt % mini == mini - 1: # print every 40 mini-batches
print('[%d, %5d] loss: %.3f' %(epoch + 1, cnt + 1, running_loss / mini))
mini_loss.append(running_loss / mini)
running_loss = 0.0
cnt=cnt+1
if(np.average(mini_loss) <= 0.05):
break
print('Finished Training')
return fore_net, epoch
def testing(loader, fore_net):
correct = 0
total = 0
count = 0
flag = 1
focus_true_pred_true =0
focus_false_pred_true =0
focus_true_pred_false =0
focus_false_pred_false =0
argmax_more_than_half = 0
argmax_less_than_half =0
with torch.no_grad():
for data in loader:
inputs, labels , fore_idx = data
inputs, labels , fore_idx = inputs.to("cuda"),labels.to("cuda"), fore_idx.to("cuda")
outputs, alphas, avg_images = fore_net(inputs)
_, predicted = torch.max(outputs.data, 1)
for j in range(labels.size(0)):
count += 1
focus = torch.argmax(alphas[j])
if alphas[j][focus] >= 0.5 :
argmax_more_than_half += 1
else:
argmax_less_than_half += 1
if(focus == fore_idx[j] and predicted[j] == labels[j]):
focus_true_pred_true += 1
elif(focus != fore_idx[j] and predicted[j] == labels[j]):
focus_false_pred_true += 1
elif(focus == fore_idx[j] and predicted[j] != labels[j]):
focus_true_pred_false += 1
elif(focus != fore_idx[j] and predicted[j] != labels[j]):
focus_false_pred_false += 1
total += labels.size(0)
correct += (predicted == labels).sum().item()
return correct, total, focus_true_pred_true, focus_false_pred_true, focus_true_pred_false, focus_false_pred_false, argmax_more_than_half
def enter_into(table, sno, correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half , fg, bg, epoch = "NA"):
entry = []
entry = [sno,'fg = '+ str(fg),'bg = '+str(bg), epoch, total, correct,]
entry.append((100.0*correct/total))
entry.append((100 * ftpt / total))
entry.append( (100 * ffpt / total))
entry.append( ( 100 * ftpf / total))
entry.append( ( 100 * ffpf / total))
entry.append( alpha_more_half)
table.append(entry)
print(" ")
print("="*160)
print(tabulate(table, headers=['S.No.', 'fg_class','bg_class','Epoch used','total_points', 'correct','accuracy','FTPT', 'FFPT', 'FTPF', 'FFPF', 'avg_img > 0.5'] ) )
print(" ")
print("="*160)
return table
def add_average_entry(table):
entry =[]
entry = ['Avg', "","" ,"" ,"" , "",]
entry.append( np.mean(np.array(table)[:,6].astype(np.float)) )
entry.append( np.mean(np.array(table)[:,7].astype(np.float)) )
entry.append( np.mean(np.array(table)[:,8].astype(np.float)) )
entry.append( np.mean(np.array(table)[:,9].astype(np.float)) )
entry.append( np.mean(np.array(table)[:,10].astype(np.float)) )
entry.append( np.mean(np.array(table)[:,11].astype(np.float)) )
table.append(entry)
print(" ")
print("="*160)
print(tabulate(table, headers=['S.No.', 'fg_class','bg_class','Epoch used','total_points', 'correct','accuracy','FTPT', 'FFPT', 'FTPF', 'FFPF', 'avg_img > 0.5'] ) )
print(" ")
print("="*160)
return table
train_table=[]
test_table1=[]
test_table2=[]
test_table3=[]
test_table4=[]
fg = [fg1,fg2,fg3]
bg = list(set([0,1,2,3,4,5,6,7,8,9])-set(fg))
number_runs = 10
for i in range(number_runs):
fore_net = Module2().double()
fore_net = fore_net.to("cuda")
fore_net, epoch = training(train_loader_from_noise_train_mosaic_30k, fore_net)
correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half = testing(train_loader_from_noise_train_mosaic_30k, fore_net)
train_table = enter_into(train_table, i+1, correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half, fg, bg, str(epoch) )
correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half = testing(test_loader_from_noise_train_mosaic_30k, fore_net)
test_table1 = enter_into(test_table1, i+1, correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half , fg, bg )
correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half = testing(test_loader_from_noise_test_mosaic_10k, fore_net)
test_table2 = enter_into(test_table2, i+1, correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half, fg, bg )
correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half = testing(test_loader_from_true_train_mosaic_30k, fore_net)
test_table3 = enter_into(test_table3, i+1, correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half , fg, bg)
correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half = testing(test_loader_from_true_train_mosaic_10k, fore_net)
test_table4 = enter_into(test_table4, i+1, correct, total, ftpt, ffpt, ftpf, ffpf, alpha_more_half, fg, bg )
train_table = add_average_entry(train_table)
test_table1 = add_average_entry(test_table1)
test_table2 = add_average_entry(test_table2)
test_table3 = add_average_entry(test_table3)
test_table4 = add_average_entry(test_table4)
# torch.save(fore_net.state_dict(),"/content/drive/My Drive/Research/mosaic_from_CIFAR_involving_bottop_eigen_vectors/fore_net_epoch"+str(epoch)+"_fg_used"+str(fg_used)+".pt")
```
| github_jupyter |
```
%matplotlib inline
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import os
import json
from sagemaker.predictor import json_deserializer
```
<h1>FM Cloud Prediction Invocation Template</h1>
<h4>Invoke SageMaker Prediction Service</h4>
```
import boto3
import re
from sagemaker import get_execution_role
import sagemaker
# Acquire a realtime endpoint
endpoint_name = 'fm-movie-v2'
predictor_sparse = sagemaker.predictor.RealTimePredictor(endpoint=endpoint_name)
# Read Dimension: Number of unique users + Number of unique movies in our dataset
dim_movie = 0
# Update movie dimension - from file used for training
with open(r'ml-latest-small/movie_dimension.txt','r') as f:
dim_movie = int(f.read())
print(dim_movie)
def fm_sparse_serializer(data):
js = {'instances': []}
for row in data:
column_list = row.tolist()
value_list = np.ones(len(column_list),dtype=int).tolist()
js['instances'].append({'data':{'features': { 'keys': column_list, 'shape':[dim_movie], 'values': value_list}}})
return json.dumps(js)
# Testing
print(fm_sparse_serializer([np.array([341,1416]),np.array([209,2640]),np.array([164,1346])]))
# Initialize Predictor with correct configuration
predictor_sparse.content_type = 'application/json'
predictor_sparse.serializer = fm_sparse_serializer
predictor_sparse.deserializer = json_deserializer
# Test libSVM
# Load the test file in svm format. '5 341:1 1416:1'
test_file = r'ml-latest-small/user_movie_test.svm'
df_test = pd.read_csv(test_file, sep=' ', names=['rating','user_index','movie_index'])
df_test.head()
# update column to contain only the one hot encoded index
df_test.user_index = df_test.user_index.map(lambda value: int(value.split(':')[0]))
df_test.movie_index = df_test.movie_index.map(lambda value: int(value.split(':')[0]))
df_test.head()
df_test.shape
# For large number of predictions, we can split the input data and
# Query the prediction service.
# array_split is convenient to specify how many splits are needed
def get_predictions(predictor, arr_features):
predictions = []
for arr in np.array_split(arr_features,100):
if arr.shape[0] > 0:
print (arr.shape, end=' ')
result = predictor.predict(arr)
predictions += [values['score'] for values in result['predictions']]
return predictions
%time predictions = get_predictions(predictor_sparse, df_test[['user_index','movie_index']].as_matrix())
df_test['predictions'] = predictions
df_test.head()
import sklearn.metrics as metrics
print('RMSE: ', metrics.mean_squared_error(df_test.rating, df_test.predictions)**.5)
# Training Data Residuals
residuals = (df_test.predictions - df_test.rating)
plt.hist(residuals)
plt.grid(True)
plt.xlabel('(Predicted - Actual)')
plt.ylabel('Count')
plt.title('Residuals Distribution')
plt.axvline(color='g')
```
## Get Prediction for a single user and all movies
```
# Load the one hot coded index values in svm format
test_file = r'ml-latest-small/one_hot_enc_movies.svm'
df_one_user_test = pd.read_csv(test_file,sep=' ',names=['movieId','user_index','movie_index'])
df_one_user_test.user_index = df_one_user_test.user_index.map(lambda value: int(value.split(':')[0]))
df_one_user_test.movie_index = df_one_user_test.movie_index.map(lambda value: int(value.split(':')[0]))
df_one_user_test.head()
df_one_user_test.shape[0]
%time predictions = get_predictions(predictor_sparse, df_one_user_test[['user_index','movie_index']].as_matrix())
df_one_user_test['rating_predicted'] = predictions
df_one_user_test.head()
df_movies = pd.read_csv(r'ml-latest-small/movies_genre.csv')
df_movies.head()
df_one_user_test = df_one_user_test.merge(df_movies, on='movieId')
df_one_user_test.head()
df_one_user_test.sort_values(['rating_predicted'], ascending=False)[['title','rating_predicted','genres']].head(10)
# Any Action Movies?
df_one_user_test[df_one_user_test.Action == 1].sort_values(['rating_predicted'], ascending=False)[['title','rating_predicted','genres']].head(10)
# What about comedy?
df_one_user_test[df_one_user_test.Comedy == 1].sort_values(['rating_predicted'], ascending=False)[['title','rating_predicted','genres']].head(10)
# And Drama
df_one_user_test[df_one_user_test.Drama == 1].sort_values(['rating_predicted'], ascending=False)[['title','rating_predicted','genres']].head(10)
df_one_user_test.user_index = 333
predictions = get_predictions(predictor_sparse, df_one_user_test[['user_index','movie_index']].as_matrix())
df_one_user_test['rating_predicted'] = predictions
df_one_user_test.sort_values(['rating_predicted'], ascending=False)[['title','rating_predicted','genres']].head(10)
df_one_user_test.user_index = 209
predictions = get_predictions(predictor_sparse, df_one_user_test[['user_index','movie_index']].as_matrix())
df_one_user_test['rating_predicted'] = predictions
df_one_user_test.sort_values(['rating_predicted'], ascending=False)[['title','rating_predicted','genres']].head(10)
```
| github_jupyter |
##### Copyright 2020 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# TensorFlow Addons 回调:TQDM 进度条
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://tensorflow.google.cn/addons/tutorials/tqdm_progress_bar"><img src="https://tensorflow.google.cn/images/tf_logo_32px.png">在 TensorFlow.org 上查看</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/addons/tutorials/tqdm_progress_bar.ipynb"><img src="https://tensorflow.google.cn/images/colab_logo_32px.png">在 Google Colab 中运行</a></td>
<td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/zh-cn/addons/tutorials/tqdm_progress_bar.ipynb"><img src="https://tensorflow.google.cn/images/GitHub-Mark-32px.png">在 GitHub 上查看源代码</a></td>
<td><a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/zh-cn/addons/tutorials/tqdm_progress_bar.ipynb"><img src="https://tensorflow.google.cn/images/download_logo_32px.png">下载笔记本</a></td>
</table>
## 概述
此笔记本将演示如何使用 TensorFlow Addons 中的 TQDMCallback。
## 设置
```
!pip install -q "tqdm>=4.36.1"
import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
import tqdm
# quietly deep-reload tqdm
import sys
from IPython.lib import deepreload
stdout = sys.stdout
sys.stdout = open('junk','w')
deepreload.reload(tqdm)
sys.stdout = stdout
tqdm.__version__
```
## 导入并归一化数据
```
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# normalize data
x_train, x_test = x_train / 255.0, x_test / 255.0
```
## 构建简单的 MNIST CNN 模型
```
# build the model using the Sequential API
model = Sequential()
model.add(Flatten(input_shape=(28, 28)))
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['accuracy'])
```
## 默认的 TQDMCallback 用法
```
# initialize tqdm callback with default parameters
tqdm_callback = tfa.callbacks.TQDMProgressBar()
# train the model with tqdm_callback
# make sure to set verbose = 0 to disable
# the default progress bar.
model.fit(x_train, y_train,
batch_size=64,
epochs=10,
verbose=0,
callbacks=[tqdm_callback],
validation_data=(x_test, y_test))
```
**当您运行上面的单元时,以下是预期输出** 
```
# TQDMProgressBar() also works with evaluate()
model.evaluate(x_test, y_test, batch_size=64, callbacks=[tqdm_callback], verbose=0)
```
**当您运行上面的单元时,以下是预期输出** 
| github_jupyter |
# Multiparametrisk MRI - Utforsking (a)
Version 05.01.2020. A. Lundervold and A.S. Lundervold.
# Importer biblioteker
Dette er biblioteker vi vil bruke:
```
# For å vise plots direkte i notebooks:
%matplotlib inline
# Et mye brukt plot-bibliotek:
import matplotlib
import matplotlib.pyplot as plt
# En utvidelse av matplotlib som kan generere enda penere plots:
import seaborn as sns
# Et bibliotek for effektiv manipulasjon av matriser (og mer):
import numpy as np
# For å lese, skrive og prosessere tabulære data:
import pandas as pd
# For maskinlæring:
import sklearn
# For medisinsk bildebehandling (neuro-imaging):
import nibabel
# Maskinlæring for neuro-imaging:
import nilearn
# For å lese og skrive bilder
import imageio
# For bilde-prosessering:
import skimage
```
## `NiBabel` and `Nilearn`: Neuroimaging i Python
```
import nibabel as nib
import nilearn
img = nilearn.image.load_img('../testdata/0.0-test_nifti.nii.gz')
img.shape
from nibabel.viewers import OrthoSlicer3D
OrthoSlicer3D(img.get_fdata(), affine= img.affine).show()
# To ignore an unimportant warning generated by the below code
# (remove the filter if you're curious)
import warnings
warnings.simplefilter('ignore')
from nilearn import datasets, plotting
img = datasets.fetch_localizer_button_task()['tmap']
plotting.view_img_on_surf(img, threshold='90%', surf_mesh='fsaverage')
```
## `scikit-image`: Bildebehandling i Python
Et eksempel fra <a href="http://scikit-image.org/docs/stable/auto_examples/color_exposure/plot_ihc_color_separation.html">scikit-image</a>-dokumentasjonen: **Immunohistochemical staining colors separation**
```
import matplotlib.pyplot as plt
from skimage import data
from skimage.color import rgb2hed
from matplotlib.colors import LinearSegmentedColormap
# Create an artificial color close to the original one
cmap_hema = LinearSegmentedColormap.from_list('mycmap', ['white', 'navy'])
cmap_dab = LinearSegmentedColormap.from_list('mycmap', ['white',
'saddlebrown'])
cmap_eosin = LinearSegmentedColormap.from_list('mycmap', ['darkviolet',
'white'])
ihc_rgb = data.immunohistochemistry()
ihc_hed = rgb2hed(ihc_rgb)
fig, axes = plt.subplots(2, 2, figsize=(7, 6))
ax = axes.ravel()
ax[0].imshow(ihc_rgb)
ax[0].set_title("Original image")
ax[1].imshow(ihc_hed[:, :, 0], cmap=cmap_hema)
ax[1].set_title("Hematoxylin")
ax[2].imshow(ihc_hed[:, :, 1], cmap=cmap_eosin)
ax[2].set_title("Eosin")
ax[3].imshow(ihc_hed[:, :, 2], cmap=cmap_dab)
ax[3].set_title("DAB")
for a in ax.ravel():
a.axis('off')
fig.tight_layout()
```
Manipulasjon av hematoxylin og DAB-«kanalene»:
```
import numpy as np
from skimage.exposure import rescale_intensity
# Rescale hematoxylin and DAB signals and give them a fluorescence look
h = rescale_intensity(ihc_hed[:, :, 0], out_range=(0, 1))
d = rescale_intensity(ihc_hed[:, :, 2], out_range=(0, 1))
zdh = np.dstack((np.zeros_like(h), d, h))
fig, ax = plt.subplots()
ax.imshow(zdh)
ax.set_title("Stain separated image (rescaled)")
#ax.axis('off')
plt.show()
```
## `imageio` : Python library for reading and writing image data
Vi leser inn single-slice 4-kanals MR-bilder i DICOM-format (vi skal bruke disse dataene igjen senere i kurset)
```
channels = ['FLASH', 'DESS', 'FISP', 'PSIF']
nb_channels = len(channels)
images = [imageio.imread(f'../testdata/{channel.lower()}_060.dcm') for channel in channels]
nrow, ncol = images[0].shape
fig, axes = plt.subplots(2, 2, figsize=(8, 8))
ax = axes.ravel()
for i, im in enumerate(images):
ax[i].imshow(im, cmap='gray')
ax[i].set_title(channels[i])
ax[i].axis('off')
plt.show()
# Classes (color-coded): air, gm, wm, csf, fat, mus(cle)
train_mask = imageio.imread("../testdata/flash_060_training_mask_6cla.png")
roi_mask = imageio.imread("../testdata/flash_060_brain_mask.png")
print(train_mask.shape)
fig, axes = plt.subplots(1, 3, figsize=(10, 16), sharex=True, sharey=True)
ax = axes.ravel()
ax[0].imshow(train_mask)
ax[0].set_title("Training mask - 6 classes")
ax[1].imshow(images[0], cmap='gray')
ax[1].set_title("FLASH")
ax[2].imshow(roi_mask)
ax[2].set_title("Brain ROI")
plt.show()
# Number of occurences of each unique color (class label in training mask) in descending order
from collections import Counter
Counter([tuple(colors) for i in train_mask for colors in i]).most_common()
# Count the number of occurences of oixels in ROI mask
Counter([tuple(colors) for i in roi_mask for colors in i]).most_common()
```
| github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from SCFInitialGuess.utilities.usermessages import Messenger as msg
msg.print_level = 0
from os.path import join
plt.style.use(["seaborn", "thesis"])
plt.rcParams['figure.figsize'] = (8, 4)
```
# Dataset
```
from SCFInitialGuess.utilities.dataset import extract_triu_batch, AbstractDataset
from sklearn.model_selection import train_test_split
data_path = "../../dataset/TSmall_sto3g"
postfix = "TSmall_sto3g"
dim = 26
#data_path = "../butadien/data/"
#postfix = ""
#dim = 26
S = np.load(join(data_path, "S" + postfix + ".npy"))
P = np.load(join(data_path, "P" + postfix + ".npy"))
F = np.load(join(data_path, "F" + postfix + ".npy"))
index = np.load(join(data_path, "index" + postfix + ".npy"))
molecules = np.load(join(data_path, "molecules" + postfix + ".npy"))
ind = int(0.8 * len(index))
molecules = (molecules[:ind], molecules[ind:])
def split(x, y, ind):
return x[:ind], y[:ind], x[ind:], y[ind:]
s_triu = extract_triu_batch(S, dim)
p_triu = extract_triu_batch(P, dim)
s_triu_norm, mu, std = AbstractDataset.normalize(s_triu)
s_train, p_train, s_test, p_test = split(s_triu_norm, p_triu, ind)
```
# Model
```
keras.backend.clear_session()
filepath = "../../models/" + "TSmall_sto3gmodelTSmall_sto3g_250-150-50+triu.h5"
model = keras.models.load_model(filepath)
model.summary()
```
# Guesses
```
from SCFInitialGuess.utilities.dataset import make_matrix_batch
p_nn = model.predict(s_test)
p_batch = make_matrix_batch(p_nn, dim=dim, is_triu=True).astype("float64")
from SCFInitialGuess.utilities.dataset import make_matrix_batch, extract_triu_batch
from SCFInitialGuess.nn.post_processing import multi_mc_wheeny
from pyscf.scf import hf
#s_raw = make_matrix_batch(dataset.inverse_input_transform(dataset.testing[0]), dim, False)
#p_mcw1 = np.array(list(map(lambda x: multi_mc_wheeny(x[0], x[1], n_max=1), zip(p_batch, s_raw)))).astype("float64")
#p_mcw5 = np.array(list(map(lambda x: multi_mc_wheeny(x[0], x[1], n_max=5), zip (p_batch, s_raw)))).astype("float64")
p_1e = np.array([
hf.init_guess_by_1e(mol.get_pyscf_molecule()) for mol in molecules[1]
]).astype("float64")
p_sap = np.array([
hf.init_guess_by_atom(mol.get_pyscf_molecule()) for mol in molecules[1]
]).astype("float64")
p_gwh = np.array([
hf.init_guess_by_wolfsberg_helmholtz(mol.get_pyscf_molecule()) for mol in molecules[1]
]).astype("float64")
```
# Iterations
```
from SCFInitialGuess.utilities.analysis import measure_iterations
from SCFInitialGuess.utilities.analysis import mf_initializer_diis as mf_initializer
iterations = []
print("nn")
iterations.append(measure_iterations(mf_initializer, p_batch, molecules[1]))
#print("mcw1")
#iterations.append(measure_iterations(mf_initializer, p_mcw1, molecules[1]))
#print("mcw5")
#iterations.append(measure_iterations(mf_initializer, p_mcw5, molecules[1]))
print("h_core")
iterations.append(measure_iterations(mf_initializer, p_1e, molecules[1]))
print("sap")
iterations.append(measure_iterations(mf_initializer, p_sap, molecules[1]))
print("gwh")
iterations.append(measure_iterations(mf_initializer, p_gwh, molecules[1]))
iterations = np.array(iterations).T
iterations.shape
```
# Plot
```
labels = ["NN", "H_Core", "SAD", "GWH"]
from pandas import DataFrame
from seaborn import boxplot
#frame = DataFrame([[iterations[:,i] for i in range(len(labels))]], columns=labels)
frame = DataFrame(iterations, columns=labels)
boxplot(data=iterations)
plt.xticks(np.arange(5), labels)
plt.ylabel("Iterations / 1")
plt.tight_layout()
plt.savefig("/home/jo/Repos/MastersThesis/SMatrixDescriptor/figures/IterationsBoxPlot.pdf")
plt.show()
```
# Make DataFrame
```
from SCFInitialGuess.utilities.analysis import measure_iterations
from SCFInitialGuess.utilities.analysis import mf_initializer as mf_initializer
from pandas import DataFrame
iterations = []
labels = []
x = []
x_offset = 0.5
x_delta = 2
i = 0
print("nn")
iterations += measure_iterations(mf_initializer, p_batch, molecules[1])
labels += ["NN"] * len(p_batch)
i += 1
x += [x_offset + x_delta * i] * len(p_batch)
print("h_core")
iterations += measure_iterations(mf_initializer, p_1e, molecules[1])
labels += ["H_Core"] * len(p_1e)
i += 1
x += [x_offset + x_delta * i] * len(p_1e)
print("sap")
iterations += measure_iterations(mf_initializer, p_sap, molecules[1])
labels += ["SAD"] * len(p_sap)
i += 1
x += [x_offset + x_delta * i] * len(p_sap)
print("gwh")
iterations += measure_iterations(mf_initializer, p_gwh, molecules[1])
labels += ["GWH"] * len(p_gwh)
i += 1
x += [x_offset + x_delta * i] * len(p_gwh)
enhancement = len(x) * ["Pure"]
```
## Damped
```
from SCFInitialGuess.utilities.analysis import measure_iterations
from SCFInitialGuess.utilities.analysis import mf_initializer_damping as mf_initializer
from pandas import DataFrame
x_offset = 1
x_delta = 2
i = 0
print("nn")
iterations += measure_iterations(mf_initializer, p_batch, molecules[1])
labels += ["NN"] * len(p_batch)
i += 1
x += [x_offset + x_delta * i] * len(p_batch)
print("h_core")
iterations += measure_iterations(mf_initializer, p_1e, molecules[1])
labels += ["H_Core"] * len(p_1e)
i += 1
x += [x_offset + x_delta * i] * len(p_1e)
print("sap")
iterations += measure_iterations(mf_initializer, p_sap, molecules[1])
labels += ["SAD"] * len(p_sap)
i += 1
x += [x_offset + x_delta * i] * len(p_sap)
print("gwh")
iterations += measure_iterations(mf_initializer, p_gwh, molecules[1])
labels += ["GWH"] * len(p_gwh)
i += 1
x += [x_offset + x_delta * i] * len(p_gwh)
enhancement += (len(x) - len(enhancement)) * ["Damped"]
```
## DIIS
```
from SCFInitialGuess.utilities.analysis import measure_iterations
from SCFInitialGuess.utilities.analysis import mf_initializer_diis as mf_initializer
from pandas import DataFrame
x_offset = 1.5
x_delta = 2
i = 0
print("nn")
iterations += measure_iterations(mf_initializer, p_batch, molecules[1])
labels += ["NN"] * len(p_batch)
i += 1
x += [x_offset + x_delta * i] * len(p_batch)
print("h_core")
iterations += measure_iterations(mf_initializer, p_1e, molecules[1])
labels += ["H_Core"] * len(p_1e)
i += 1
x += [x_offset + x_delta * i] * len(p_1e)
print("sap")
iterations += measure_iterations(mf_initializer, p_sap, molecules[1])
labels += ["SAD"] * len(p_sap)
i += 1
x += [x_offset + x_delta * i] * len(p_sap)
print("gwh")
iterations += measure_iterations(mf_initializer, p_gwh, molecules[1])
labels += ["GWH"] * len(p_gwh)
i += 1
x += [x_offset + x_delta * i] * len(p_gwh)
enhancement += (len(x) - len(enhancement)) * ["DIIS"]
```
# Plot
```
x_sav = x
x = []
dx = 2
for i in [-0.5, 0, 0.5]:
for j in range(4):
x += [j * dx + 1 + i] * 201
print(x[-1])
x = []
dx = 2
for i in [0, 1, 2]:
for j in [3, 0, 1, 2]:
x += [j] * 201
print(x[-1])
len(x), len(iterations), len(labels), len(enhancement)
#enhancement = ["Pure"]*804 + ["Damping"]*804 + ["DIIS"]*804
data = DataFrame(
{
"x": x,
"iterations": iterations,
#"labels": labels,
"Method": enhancement
}
)
labels = ["H_Core", "SAD", "GWH", "NN"]
from pandas import DataFrame
import seaborn as sns
sns.boxplot(data=data, x="x", y="iterations", hue="Method", width=00.7)
sns.despine(offset=10, trim=True)
plt.xticks([0, 1, 2,3], labels)
#plt.xticks(np.arange(10), np.arange(10))
plt.ylabel("Iterations / 1")
plt.xlabel("")
plt.tight_layout()
plt.legend(bbox_to_anchor=(1.02, 0.9))
plt.savefig("/home/jo/Repos/MastersThesis/SMatrixDescriptor/figures/IterationsBoxPlot2.pdf")
plt.show()
labels = ["NN", "H_core", "SAD", "GWH"]
from pandas import DataFrame
import seaborn as sns
sns.violinplot(data=data, x="x", y="iterations", hue="Method")
sns.despine(offset=10, trim=True)
plt.xticks([0, 1, 2,3], labels)
#plt.xticks(np.arange(10), np.arange(10))
plt.ylabel("Iterations / 1")
plt.xlabel("")
plt.tight_layout()
#plt.legend(bbox_to_anchor=(1.1, 0.9))
#plt.savefig("/home/jo/Repos/MastersThesis/SMatrixDescriptor/figures/IterationsBoxPlot2.pdf")
plt.show()
```
| github_jupyter |
# Use W5E5 v2.0 and daily mass-balance (with MBsandbox)
**What changed compared to last version**
- you can use now `run_constant_climate_TIModel` for the spinup instead of `run_random_climate_TIModel` (see code below in cell 10)
**What is new?**
- use variable lapse rates ('var_an_cycle') and W5E5 climate
- we can use daily temperature and precipitation input data:
- can get daily specific_mb
- works with run_with_climate_data and get daily resolution of volume
- works with run_with_hydro, but it updates only monthly at the moment and the runoff output is monthly or annual
> need to install MBsandbox: https://github.com/OGGM/massbalance-sandbox
---
Todo Lily at some point:
- write a run_from_constant_climate_TIModel function -> do you need this
Todo Sarah:
- make some tests if the output makes sense
- I copied the tests from Fabi oggm default (see hydro in test_models),
- they work except for melt_off_glacier: which is very different between store_monthly_hydro = True and False
- maybe you can do some more tests to find out if this is problematic ...
**Todo to get daily input and daily runoff output:**
- need to make a run_with_hydro_daily(), possibly just a copy of run_with_hydro with some changes ...
- use get_daily_mb from TIModel instead of get_monthly_mb -> see: https://github.com/OGGM/massbalance-sandbox/blob/master/docs/how_to_daily_input_daily_output.ipynb
- everything with months needs to be changed to days ... might get tricky because of different days in each year/month
- I guess we need to update daily ??? (takes long, but I guess: loop over each day) ???
**Todo for the spinup:**
- automated workflow that calibrates to the right volume
---
**some other thoughts in German (directed to Sarah)**
- also run_with_hydro funktioniert jetzt mit W5E5 (basiert auf GPCC)-Daten und meinem Massenbilanz-modell (wahlweise monatlich oder täglicher Klima-input). Du kannst selber auswählen welchen prcp-factor du willst und es kalibriert dann jeweils die melt_f (melt factor, equivalent zu mu_star in default OGGM). Das kalibrierte Melt_f wird im gdir-Ordner abgespeichert (susammen mit prcp-fac), und dort wird es dann aufgerufen über run_from_climate_data... . Ich hab daraus schon ein @entity task gemacht um es parallel laufen zu lassen, aber leider gibt es irgendein multiprocessing error. Deswegen nutze ich weiterhin die loop-schlaufe. Im Moment kalibriert es danach auch den glen-a factor nach dem Farinotti estimate (z.B. glen-a kann so kalibriert werden das alle gletscher aus dem Rhein-basin-Volumen im Totalem Farinotti2019 entsprechen.
- Du kannst stattdessen auch WFDE5_CRU (basierend auf CRU) als Klimadatensatz benutzen (allerdings habe ich im Moment nur v1.1 die nur von 1979 - bis Ende 2018 geht) und direkt vergleichen. Ich habe im Notebook mal einen gridpoint (für den Hintereisferner) genauer angeschaut. Da hat W5E5 nur 0.4* so viel Niederschlag wie WFDE5_CRU, aber sie korrelieren gut miteinander (corrcoef: 0.92). Also im allgemeinen wirst du bei W5E5 eher so einen prcp-fac zwischen 2-3 brauchen und bei WFDE5_CRU zwischen 1-2 oder so ... der prcp-fac hat natürlich dann Einfluss auf den runoff...
- Im Moment kannst du run_with_hydro mit dem equivalentem `run_from_climate_data_TIModel()`, `run_random_climate_TIModel()` oder `run_constant_climate_TIModel` (NEU!!!) nutzen. Der kalibrierte melt_f wird genutzt wenn du melt_f = 'from_json' nimmst.
- du kannst jetzt schon die "mb_real_daily" - option nutzen. Das heißt es werden tägliche Niederschlags und Temperaturwerte genutzt um die massenbilanz zu berechen. Mein massenbilanz-model ('TIModel') kann daily mb auch schon ausspucken (`get_daily_mb()`) allerdings kann run_with_hydro das noch nicht "verwerten". Im Moment nutzt es die monatliche Summe aus dem täglichen Modell um den runoff zu ermitteln. Damit es wirklich 'daily input daily output' wird, müsstest du wahscheinlich eine Kopie von run_with_hydro machen; - run_with_hydro_daily - dass dann über jeden Tag "loopt" und statt get_montly_mb() dann get_daily_mb() verwendet ?!
- zu deinem workflow mit dem spinup: wenn du konstantes klima anwendest über ein paar Jahre von mitte 1995 und drum herum sind die meisten gletscher fast nicht mehr da nach dem der Spinup fertig ist. Also zumindest war das bei mir so. Vielleicht könnte man ein temperature bias nehmen den man so wählt das bei dem eigentlichen run_from_climate-lauf das Gletschervolumen beim rgi-date (2003/2004) ungefähr dem Farinotti estimate entspricht. Wenn ich nur Hintereisferner nehme wäre das z.b. -0.7°C (das ist abh. von dem gewählten prcp. factor, klimadatensatz, mb type ....).
```
import numpy as np
import pandas as pd
import xarray as xr
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
import scipy
import scipy.stats as stats
import os
import oggm
from oggm import cfg, utils, workflow, tasks, graphics, entity_task
from oggm.core import massbalance, flowline, climate
from oggm.utils import (floatyear_to_date, date_to_floatyear)
# just for the graphics
SMALL_SIZE = 18
MEDIUM_SIZE = 20
BIGGER_SIZE = 24
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
# import the MSsandbox modules
from MBsandbox.mbmod_daily_oneflowline import process_w5e5_data, process_era5_daily_data, TIModel, BASENAMES
# from MBsandbox.help_func import compute_stat, minimize_bias, optimize_std_quot_brentq
from MBsandbox.help_func import minimize_bias_geodetic, optimize_std_quot_brentq_geod, melt_f_calib_geod_prep_inversion
from MBsandbox.flowline_TIModel import (run_from_climate_data_TIModel, run_constant_climate_TIModel,
run_random_climate_TIModel)
cfg.initialize()
cfg.PARAMS['use_multiprocessing'] = True
cfg.PARAMS['continue_on_error'] = False
working_dir = utils.gettempdir(dirname='OGGM_hydro', reset=False)
cfg.PATHS['working_dir'] = working_dir
# use elevation band flowlines
base_url = ('https://cluster.klima.uni-bremen.de/~oggm/gdirs/oggm_v1.4/'
'L1-L2_files/elev_bands')
# as we calibrate to geodetic estimates we use calendar years!
# need to check if this works in southern hemisphere
cfg.PARAMS['hydro_month_nh'] = 1
# get the geodetic calibration data
# short test:
# check how many glaciers have geodetic msm
pd_geodetic = utils.get_geodetic_mb_dataframe()
ref_period = '2000-01-01_2020-01-01'
pd_geodetic = pd_geodetic.loc[pd_geodetic['period'] == ref_period]
area_geod_11 = pd_geodetic[pd_geodetic.reg == 11].loc[pd_geodetic[pd_geodetic.reg == 11].dmdtda.dropna().index].area.sum()
area_all_11 = pd_geodetic[pd_geodetic.reg == 11].area.sum()
relative_area_11 = area_geod_11/area_all_11
relative_area_11
#in the new corrected geodetic dataset, there are no glaciers without geodetic estimates inside anymore!!!
df = ['RGI60-14.16678'] # RGI60-14.08190
gdirs = workflow.init_glacier_directories(df, from_prepro_level=2,
prepro_border=80,
prepro_base_url=base_url,
prepro_rgi_version='62')
df = ['RGI60-11.00890', 'RGI60-11.00897', 'RGI60-14.16678',
'RGI60-14.08183',
'RGI60-14.02796',] # list of glaciers -> can be longer ...
# this has to be done just once for a region (basin) (independent of climate, mb_type, prcp-fac ... )
init = True
if init:
gdirs = workflow.init_glacier_directories(df, from_prepro_level=2,
prepro_border=160, # 40, needed for the spinup
prepro_base_url=base_url,
prepro_rgi_version='62')
workflow.execute_entity_task(tasks.compute_downstream_line, gdirs)
workflow.execute_entity_task(tasks.compute_downstream_bedshape, gdirs)
else:
gdirs = workflow.init_glacier_directories(df)
```
### things that can be changed before calibration
```
# if you have a precipitation factor from the hydrological model you can change it here
pf = 2 # we set the precipitation factor here to 1
climate_type = 'W5E5_MSWEP' #W5E5 # 'WFDE5_CRU'
#climate_type='WFDE5_CRU' -> need to use other pf and temp_bias ...
mb_type = 'mb_real_daily' #real daily input, this would be monthly input:'mb_monthly' #'mb_real_daily' # 'mb_monthly'#
grad_type ='cte' # variable lapse rates
```
### melt_f calibration and inversion with glen-a calibration
```
# this has to be done once for each climate, mb_type, grad_type, pf option,
# then you can save the melt_f and a-factor for the runs later on
if climate_type =='W5E5' or climate_type == 'W5E5_MSWEP':
ye=2020 # till end of 2019
else:
ye=2019
calib=True
if calib:
if mb_type == 'mb_real_daily':
temporal_resol = 'daily'
else:
temporal_resol = 'monthly'
# get the climate data (either w5e5 or WFDE5_CRU)
workflow.execute_entity_task(process_w5e5_data, gdirs,
temporal_resol=temporal_resol, climate_type=climate_type)
# calibrate melt_f and get apparent mb
workflow.execute_entity_task(melt_f_calib_geod_prep_inversion, gdirs,
pf = pf, # precipitation factor
mb_type=mb_type, grad_type=grad_type,
climate_type=climate_type, residual=0,
ye=ye)
# here glen-a is calibrated to match gdirs glaciers in total
border = 80
filter = border >= 20
pd_inv_melt_f = oggm.workflow.calibrate_inversion_from_consensus(gdirs,
apply_fs_on_mismatch=False,
error_on_mismatch=False,
filter_inversion_output=filter)
workflow.execute_entity_task(tasks.init_present_time_glacier, gdirs)
a_factor = gdirs[0].get_diagnostics()['inversion_glen_a'] / cfg.PARAMS['inversion_glen_a']
# just a check if a-factor is set to the same value
np.testing.assert_allclose(a_factor, gdirs[-1].get_diagnostics()['inversion_glen_a'] / cfg.PARAMS['inversion_glen_a'])
# double check: volume sum of gdirs from Farinotti estimate is equal to oggm estimates
np.testing.assert_allclose(pd_inv_melt_f.sum()['vol_itmix_m3'], pd_inv_melt_f.sum()['vol_oggm_m3'], rtol = 5e-2)
# we use the json now and don't need a csv file
# old!
#pd_inv_melt_f['melt_f_opt']= pd_inv_melt_f.index.map(melt_f_dict) # different for each glacier
#pd_inv_melt_f['pf'] = pf # everywhere the same
#pd_inv_melt_f.to_csv('test_calib_params_{}_{}_{}.csv'.format(climate_type, mb_type, grad_type))
mbdf = gdirs[1].get_ref_mb_data(input_filesuffix='_{}_{}'.format(temporal_resol, climate_type))['ANNUAL_BALANCE']
mb_glaciological = mbdf#['ANNUAL_BALANCE']
np.shape(mb_glaciological)
type(mb_glaciological)
```
#### like that we can access the calibrated melt_f (and prcp-fac)
```
fs = '_{}_{}_{}'.format(climate_type, mb_type, grad_type)
gdir = gdirs[-1]
gdir.read_json(filename='melt_f_geod', filesuffix=fs)
fs1 = '_{}_{}'.format(temporal_resol, climate_type)
ds = xr.open_dataset(gdir.get_filepath('climate_historical', filesuffix=fs1))
ds.ref_hgt - ds.uncorrected_ref_hgt
```
## check if daily_hydro works
```
ye = 2020
from MBsandbox.flowline_TIModel import run_with_hydro_daily
workflow.execute_entity_task(run_with_hydro_daily, gdirs,
run_task=run_from_climate_data_TIModel,
Testing = True,
ys=1980, ye=2020,
store_monthly_step= False,
output_filesuffix='_daily_1980_{}_{}_{}'.format(ye, mb_type, grad_type),
# kwargs for TIModel
mb_model_sub_class=TIModel,
bias=0, # only tested with bias=0 !!!, don't change!
mb_type=mb_type,
grad_type=grad_type,
precipitation_factor=pf, melt_f='from_json',
climate_input_filesuffix=climate_type,
)
ds_runoff = utils.compile_run_output(gdirs, input_filesuffix='_daily_1980_{}_{}_{}'.format(ye, mb_type, grad_type))
ds_runoff
```
### just look at volume changes starting from rgi_date
```
y0=2004
ye_h = ye-1
# inside of run_from_climate_data_TIModel the calibrated melt_f is chosen from the melt_f_file csv file, such as:
# melt_f = pd_inv_melt_f['melt_f_opt'].loc[gdir.rgi_id]
# assert np.all(pf==pd_inv_melt_f['pf'])
workflow.execute_entity_task(run_from_climate_data_TIModel, gdirs, bias=0, #will actually point to the residual, should always be zero!
mb_model_sub_class=TIModel,
min_ys=y0, ye=ye_h,
mb_type=mb_type,
grad_type=grad_type,
precipitation_factor=pf,
melt_f='from_json', #melt_f_file=melt_f_file, # need to set these to find the right calibrated melt_f
climate_input_filesuffix=climate_type,
output_filesuffix='_{}_{}_{}'.format(climate_type, mb_type, grad_type) # can add here more options to distinguish between runs
)
ds_vol = utils.compile_run_output(gdirs, input_filesuffix='_{}_{}_{}'.format(climate_type, mb_type, grad_type))
ds_vol.sel(rgi_id=df[-1]).volume.plot()
# without hydro here
```
### similar to hydro_tutorial, but values for HEF are quite different????,
- https://oggm.org/tutorials/stable/notebooks/hydrological_output.html
- maybe need to check other prcp-fac
- could also come from different initialisation! (in the tutorial, default a-factor was used, so different starting volume used here ...)
```
# ds = ds_runoff.sel(rgi_id=df[-1])
workflow.execute_entity_task(tasks.run_with_hydro, gdirs,
run_task=run_random_climate_TIModel,
store_monthly_hydro=True,
nyears=100,
temperature_bias=0,
y0=2014, # if WFDE5_CRU need to set y0=2013 because no data for 2019
halfsize=5, seed=0,
unique_samples=True,
store_monthly_step=False,
mb_elev_feedback='annual',
output_filesuffix='_random_spinup_test',
bias=0, # only tested with bias=0 !!!, don't change!
mb_type=mb_type,
grad_type=grad_type,
precipitation_factor=pf,
melt_f='from_json', #melt_f_file=melt_f_file, # need to set these to find the right calibrated melt_f
climate_input_filesuffix=climate_type,
)
ds_runoff = utils.compile_run_output(gdirs, input_filesuffix='_random_spinup_test')
#could also use with xr.open_dataset(gdir.get_filepath('model_diagnostics', filesuffix='_random_spinup')) as ds:
# but the method above aggregates all glaciers
# The last step of hydrological output is NaN (we can't compute it for this year)
ds= ds_runoff.sel(rgi_id=df[-1]).isel(time=slice(0, -1)).load()
ds = ds.drop_vars('rgi_id')
ds = ds.isel(time=slice(0, -1)).load()
ds.volume.plot()
# the glacier will be almost gone in that climate
# now the same using constant climate --> with run_task: run_constant_climate_TIModel, but don't need `seed` and `unique samples`
workflow.execute_entity_task(tasks.run_with_hydro, gdirs,
run_task=run_constant_climate_TIModel, #run_random_climate_TIModel
store_monthly_hydro=True,
nyears=100,
temperature_bias=0,
y0=2014, # if WFDE5_CRU need to set y0=2013 because no data for 2019
halfsize=5, #seed=0,
store_monthly_step=False,
mb_elev_feedback='annual',
output_filesuffix='_random_spinup_test',
bias=0, # only tested with bias=0 !!!, don't change!
mb_type=mb_type,
grad_type=grad_type,
precipitation_factor=pf,
melt_f='from_json', #melt_f_file=melt_f_file, # need to set these to find the right calibrated melt_f
climate_input_filesuffix=climate_type,
)
ds_runoff = utils.compile_run_output(gdirs, input_filesuffix='_random_spinup_test')
#could also use with xr.open_dataset(gdir.get_filepath('model_diagnostics', filesuffix='_random_spinup')) as ds:
# but the method above aggregates all glaciers
# The last step of hydrological output is NaN (we can't compute it for this year)
ds= ds_runoff.sel(rgi_id=df[-1]).isel(time=slice(0, -1)).load()
ds = ds.drop_vars('rgi_id')
ds = ds.isel(time=slice(0, -1)).load()
ds.volume.plot()
# the glacier will be almost gone in that climate
sel_vars = [v for v in ds.variables if 'month_2d' not in ds[v].dims]
df_annual = ds[sel_vars].to_dataframe()
# Select only the runoff variables and convert them to megatonnes (instead of kg)
runoff_vars = ['melt_off_glacier', 'melt_on_glacier', 'liq_prcp_off_glacier', 'liq_prcp_on_glacier']
df_runoff = df_annual[runoff_vars] * 1e-9
f, ax = plt.subplots(figsize=(10, 6));
df_runoff.plot.area(ax=ax, color=sns.color_palette("rocket")); #, stacked=False
plt.xlabel('Years'); plt.ylabel('Runoff (Mt)'); plt.title(gdir.rgi_id);
ds_roll = ds.roll(month_2d=ds['calendar_month_2d'].data[0]-1, roll_coords=True)
ds_roll['month_2d'] = ds_roll['calendar_month_2d']
# Select only the runoff variables and convert them to megatonnes (instead of kg)
monthly_runoff = ds_roll['melt_off_glacier_monthly'] + ds_roll['melt_on_glacier_monthly'] + ds_roll['liq_prcp_off_glacier_monthly'] + ds_roll['liq_prcp_on_glacier_monthly']
monthly_runoff *= 1e-9
monthly_runoff.clip(0).plot(cmap='Blues', cbar_kwargs={'label':'Mt'}); plt.xlabel('Months'); plt.ylabel('Years');
# Pick the variables we need (the 2d ones)
sel_vars = [v for v in ds_roll.variables if 'month_2d' in ds_roll[v].dims]
# Pick the first decade and average it
df_m_s = ds_roll[sel_vars].isel(time=slice(0, 10)).mean(dim='time').to_dataframe() * 1e-9
# Rename the columns for readability
df_m_s.columns = [c.replace('_monthly', '') for c in df_m_s.columns]
# Because of floating point precision sometimes runoff can be slightly below zero, clip
df_m_s = df_m_s.clip(0)
# Same for end
df_m_e = ds_roll[sel_vars].isel(time=slice(-11, -1)).mean(dim='time').to_dataframe() * 1e-9
df_m_e.columns = [c.replace('_monthly', '') for c in df_m_s.columns]
df_m_e = df_m_e.clip(0)
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 7), sharey=True);
df_m_s[runoff_vars].plot.area(ax=ax1, legend=False, title='Year 0-10', color=sns.color_palette("rocket"));
df_m_e[runoff_vars].plot.area(ax=ax2, title='Year 90-100', color=sns.color_palette("rocket"));
ax1.set_ylabel('Monthly runoff (Mt)'); ax1.set_xlabel('Month'); ax2.set_xlabel('Month');
```
# now do the workflow of Sarah:
- repeat the spinup again:
- I use here a smaller halfsize and add a negative temperature bias
```
temp_bias = -0.2
# temp_bias for W5E5_MSWEP (with MSWEP prcp, and prcp-fac of 1) needs to be higher than for W5E5 (with prcp-fac of 2)
# you can change this and see how it influences the glacier volume
workflow.execute_entity_task(tasks.run_with_hydro, gdirs,
run_task=run_random_climate_TIModel,
store_monthly_hydro=True,
nyears=500,
y0=1984, halfsize=5,
seed=0,
temperature_bias=temp_bias,
unique_samples=True,
store_monthly_step=False,
mb_elev_feedback='annual',
output_filesuffix='_random_spinup',
bias=0, # only tested with bias=0 !!!, don't change!
mb_type=mb_type,
grad_type=grad_type,
precipitation_factor=pf, melt_f='from_json',
climate_input_filesuffix=climate_type,
)
with xr.open_dataset(gdir.get_filepath('model_diagnostics', filesuffix='_random_spinup')) as ds:
# The last step of hydrological output is NaN (we can't compute it for this year)
ds = ds.isel(time=slice(0, -1)).load()
ds_runoff = utils.compile_run_output(gdirs, input_filesuffix='_random_spinup')
# The last step of hydrological output is NaN (we can't compute it for this year)
ds= ds_runoff.sel(rgi_id=df[-1]).isel(time=slice(0, -1)).load()
ds = ds.drop_vars('rgi_id')
ds = ds.isel(time=slice(0, -1)).load()
sel_vars = [v for v in ds.variables if 'month_2d' not in ds[v].dims]
df_annual = ds[sel_vars].to_dataframe()
# Select only the runoff variables and convert them to megatonnes (instead of kg)
runoff_vars = ['melt_off_glacier', 'melt_on_glacier', 'liq_prcp_off_glacier', 'liq_prcp_on_glacier']
df_runoff = df_annual[runoff_vars] * 1e-9
f, ax = plt.subplots(figsize=(10, 6));
df_runoff.plot.area(ax=ax, color=sns.color_palette("rocket")); #, stacked=False
plt.xlabel('Years'); plt.ylabel('Runoff (Mt)'); plt.title(gdir.rgi_id);
ds.volume.plot()
# the glacier will be almost gone if no temp_bias
# want that glacier volume is higher than the inversion volume (at point 0)
```
# run the climate
```
workflow.execute_entity_task(tasks.run_with_hydro, gdirs,
run_task=run_from_climate_data_TIModel, store_monthly_hydro = True,
ys=1980, ye=ye,
init_model_filesuffix='_random_spinup', # if you want to apply the spinup need to add here the right filesuffix !!!!!!!!!!!!!!!!
store_monthly_step= False,
output_filesuffix='_1980_{}_{}_{}'.format(ye, mb_type, grad_type),
# kwargs for TIModel
mb_modelsub_class=TIModel,
bias=0, # only tested with bias=0 !!!, don't change!
mb_type=mb_type,
grad_type=grad_type,
precipitation_factor=pf, melt_f='from_json',
climate_input_filesuffix=climate_type,
)
ds_runoff = utils.compile_run_output(gdirs, input_filesuffix='_1980_{}_{}_{}'.format(ye, mb_type, grad_type))
# only select HEF
ds = ds_runoff.sel(rgi_id = df[-1])
ds = ds.drop_vars('rgi_id')
# The last step of hydrological output is NaN (we can't compute it for this year)
ds = ds.isel(time=slice(0, -1)).load()
sel_vars = [v for v in ds.variables if 'month_2d' not in ds[v].dims]
df_annual = ds[sel_vars].to_dataframe()
# Select only the runoff variables and convert them to megatonnes (instead of kg)
runoff_vars = ['melt_off_glacier', 'melt_on_glacier', 'liq_prcp_off_glacier', 'liq_prcp_on_glacier']
df_runoff = df_annual[runoff_vars] * 1e-9
f, ax = plt.subplots(figsize=(10, 6));
df_runoff.plot.area(ax=ax, color=sns.color_palette("rocket")); #, stacked=False
plt.xlabel('Years'); plt.ylabel('Runoff (Mt)'); plt.title(gdir.rgi_id);
```
- does this make sense that runoff rather increases, because peak water has been reached at some time between 2010 and 2020 ???
```
ds.volume.plot()
ds.sel(time=2004).volume
# volume estimate of Farinotti
plt.plot(2004, pd_inv_melt_f.loc[gdir.rgi_id].vol_itmix_m3, 'o', label='Farinotti estimate')
plt.legend()
```
- depending on which prcp-fac, the spin-up is not sufficient and we could apply a negative temp. bias because initial volume in 1980 should be well above the rgi_date,
- need to find a valid temp_bias that results in the right volume in 2004 (this depends on prcp_fac, mb_type, grad_type)
- e.g. if W5E5, prcp_fac =2, mb_type = 'mb_real_daily', and grad_type = 'var_an_cycle' -> temp_bias during spin up needs to be at around -0.7°C
- but if WFDE5_CRU, prcp_fac=1, rest the same -> temp_bias around -0.4°C
# some precipitation analysis
```
# extract directly the climate data (depends on climate_type)
clim = xr.open_dataset(gdir.get_filepath('climate_historical', filesuffix='_daily_{}'.format(climate_type)))
clim.prcp
clim # note that the lon_pr and lat_pr is different to the one for temp and for the gradient
# also the ref_hgt is only true for the temp/gradient part and not for the prcp time series (as other gridpoint!!!)
from oggm.cfg import SEC_IN_YEAR, SEC_IN_MONTH, SEC_IN_DAY
from MBsandbox.mbmod_daily_oneflowline import get_w5e5_file
lon, lat = (10.7584, 46.8003)
wfde5_pr_all = xr.open_dataset(get_w5e5_file(dataset='WFDE5_CRU_daily', var='prcp'))# .tp
c = (wfde5_pr_all.longitude - lon)**2 + (wfde5_pr_all.latitude - lat)**2
lat_wfde5, lon_wfde5 = (wfde5_pr_all.isel(points=c.argmin()).latitude, wfde5_pr_all.isel(points=c.argmin()).longitude)
wfde5_pr = wfde5_pr_all.isel(points=c.argmin()).sel(time=slice('1980', '2018')).tp # this is already in mm
# based on CRU
w5e5_pr_all = xr.open_dataset(get_w5e5_file(dataset='W5E5_daily', var='prcp')) #.pr
c = (w5e5_pr_all.longitude - lon)**2 + (w5e5_pr_all.latitude - lat)**2
lat_w5e5, lon_w5e5 = (w5e5_pr_all.isel(points=c.argmin()).latitude, w5e5_pr_all.isel(points=c.argmin()).longitude)
w5e5_pr = w5e5_pr_all.isel(points=c.argmin()).sel(time=slice('1980', '2018')).pr *SEC_IN_DAY
# based on GPCC prcp correction!!!
w5e5_mswep_pr_all = xr.open_dataset(get_w5e5_file(dataset='MSWEP_daily', var='prcp')) #.pr
c = (w5e5_mswep_pr_all.longitude - lon)**2 + (w5e5_mswep_pr_all.latitude - lat)**2
lat_w5e5_mswep, lon_w5e5_mswep = (w5e5_mswep_pr_all.isel(points=c.argmin()).latitude, w5e5_mswep_pr_all.isel(points=c.argmin()).longitude)
w5e5_mswep_pr = w5e5_mswep_pr_all.isel(points=c.argmin()).sel(time=slice('1980', '2018')).pr *SEC_IN_DAY
# based on mswep prcp
# choosing wfde5/w5e5 gridpoint:
w5e5_mswep_pr_wfde5_gp = xr.open_dataset(get_w5e5_file(dataset='MSWEP_daily', var='prcp')) #.pr
c = (w5e5_mswep_pr_wfde5_gp.longitude - lon_wfde5)**2 + (w5e5_mswep_pr_wfde5_gp.latitude - lat_wfde5)**2
w5e5_mswep_pr_wfde5_gp = w5e5_mswep_pr_wfde5_gp.isel(points=c.argmin()).sel(time=slice('1980', '2018')).pr *SEC_IN_DAY
day_in_m= wfde5_pr.resample({'time':'MS'}).mean().time.dt.days_in_month[:12].values
plt.figure(figsize=(12,8))
plt.plot(wfde5_pr.groupby('time.month').mean()*day_in_m, label='wfde5: lon {:0.2f}, lat {:0.2f}'.format(lon_wfde5.values, lat_wfde5.values))
plt.plot(w5e5_pr.groupby('time.month').mean()*day_in_m, label='w5e5: lon {:0.2f}, lat {:0.2f}'.format(lon_w5e5.values, lat_w5e5.values))
plt.plot(w5e5_mswep_pr.groupby('time.month').mean()*day_in_m, label='mswep: lon {:0.2f}, lat {:0.2f}'.format(lon_w5e5_mswep.values,
lat_w5e5_mswep.values))
plt.plot(w5e5_mswep_pr_wfde5_gp.groupby('time.month').mean()*day_in_m, label='mswep: lon {:0.2f}, lat {:0.2f}\n(wfde5/w5e5 gp)'.format(lon_wfde5.values,
lat_wfde5.values))
plt.legend()
plt.ylabel('mm per month')
plt.xlabel('month')
plt.title('gridpoint nearest to Hintereisferner: lon {:0.2f}, lat {:0.2f}'.format(lon, lat))
plt.savefig('hef_wfde5_w5e5_mswep_comparison.png')
wfde5_pr
w5e5_pr.mean() / wfde5_pr.mean()
#ratio of w5e5 to wfde5, that means GPCC versus CRU???
utils.corrcoef(w5e5_pr.values, wfde5_pr.values)
w5e5_mswep_pr.mean() / wfde5_pr.mean()
utils.corrcoef(w5e5_mswep_pr.values, wfde5_pr.values)
```
- need possibly higher prcp-fac for W5E5 and W5E5_MSWEP than for WFDE5_CRU in case of HEF! How is it for the Rhine basin or total Alps?
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
%matplotlib notebook
import matplotlib.pyplot as plt
try:
import pyfftw as fftw
except:
pass
import scipy as sp
import numpy as np
import llops as yp
import llops.operators as ops
yp.setDefaultDatatype('complex32')
```
# Numpy-Based Operators
## Create Object
```
sz = (2000, 2000)
x = yp.rand(sz)
```
## CPU/Numpy FFT Function Test
```
fftw.interfaces.cache.enable()
def numpy_fft(x):
return np.fft.fft2(x) / sz[0]
def scipy_fft(x):
return sp.fftpack.fft2(x) / sz[0]
def fftw_fft(x):
return fftw.interfaces.numpy_fft.fft2(x) / sz[0]
for f in [numpy_fft, scipy_fft, fftw_fft]:
print(f)
%timeit f(x)
%timeit f(f(f(x)))
%timeit f(x) + f(x) + f(x)
```
## CPU/Numpy FFT Operator Test
```
F_np = ops.FourierTransform(sz, backend='numpy', fft_backend='numpy', center=False, normalize=False)
F_sp = ops.FourierTransform(sz, backend='numpy', fft_backend='scipy', center=False, normalize=False)
F_fftw = ops.FourierTransform(sz, backend='numpy', fft_backend='fftw', center=False, normalize=False)
F_prod = (F * F * F)
F_sum = F + F + F
for F in [F_np, F_sp, F_fftw]:
print(F)
%timeit F * x
%timeit F_prod * x
%timeit F_sum * x
```
## Test Bottlenecks
```
F = ops.FourierTransform(sz, backend='numpy', fft_backend='numpy', center=False, normalize=False)
Fc = ops.FourierTransform(sz, backend='numpy', fft_backend='numpy', center=True, normalize=False)
_x = yp.rand(sz)
y = yp.zeros_like(_x)
%timeit np.fft.fft2(_x) / 1000
# # %timeit yp.Ft(_x)
# %timeit F.fft_fun(_x)
# %timeit Fc.fft_fun(_x)
%timeit F._forward(_x, y)
%timeit F.forward(_x, y)
%timeit F * _x
sz_0 = (100,100)
sz_1 = (50,50)
# Create fake object
x = yp.rand(sz_0)
# x[sz_1[0] // 4: 3* sz_1[0] // 4, sz_1[1] // 4: 3* sz_1[1] // 4] = yp.rand((sz_1[0] // 2, sz_1[1] // 2))
x /= yp.mean(yp.abs(x))
# Generate FFT operators
F_list_n = []
F_list_un = []
for fft_backend in yp.valid_fft_backends:
F_list_n.append(ops.FourierTransform(sz_0, backend='numpy', fft_backend=fft_backend, center=True, normalize=True))
F_list_un.append(ops.FourierTransform(sz_0, backend='numpy', fft_backend=fft_backend, center=True, normalize=False))
# Check inversion
assert all([yp.scalar(yp.sum(yp.abs(F.H * F * x - x))) < 1e-6 for F in F_list_un])
assert all([yp.scalar(yp.sum(yp.abs(F.H * F * x - x))) < 1e-6 for F in F_list_n])
# Check energy in Fourier domain
x_energy = yp.sum(yp.abs(x) ** 2)
energies_unnormalized = [yp.sum(yp.abs(F * x) ** 2) for F in F_list_n]
energies_normalized = [yp.sum(yp.abs(F * x) ** 2) for F in F_list_un]
print(x_energy)
print(energies_normalized)
print(energies_unnormalized)
assert all([abs(energy_normalized / yp.size(x) - x_energy) < 1e-1 for energy_normalized in energies_normalized])
assert all([abs(energy_unnormalized - x_energy) < 1e-4 * x_energy for energy_unnormalized in energies_unnormalized])
```
## Convolution Test
```
# Create blur kernel
h = yp.zeros(sz_0)
h[sz_1[0] // 2:sz_1[0] // 2 + 1, sz_1[1] // 4: 3* sz_1[1] // 4,] = 1
# Create fake object
x = yp.zeros(h.shape)
x[sz_1[0] // 4: 3* sz_1[0] // 4, sz_1[1] // 4: 3* sz_1[1] // 4] = yp.rand((sz_1[0] // 2, sz_1[1] // 2))
# Generate forward operators
A_list = [F.H * ops.Diagonalize(F * h) * F for F in F_list_un]
# Generate measurements
y_list = [A * x for A in A_list]
y_sum = [yp.scalar(yp.sum(yp.abs(A * x))) for A in A_list]
# Check values
assert all([delta < 1e-3 for delta in yp.sum(yp.abs(x)) * yp.sum(yp.abs(h)) - y_sum])
plt.figure(figsize=(8,4))
plt.subplot(121)
plt.imshow(np.abs(x))
plt.colorbar()
plt.subplot(122)
plt.imshow(np.abs(y_list[0]))
plt.colorbar()
```
# Arrayfire-Based Operators
```
sz = (2000, 2000)
```
## GPU/Arrayfire FFT Functon test
```
if 'opencl' in af.get_available_backends():
print('OpenCL:')
af.set_backend('opencl')
I2 = yp.rand(sz, backend='arrayfire')
%timeit af.signal.fft(I2)
if 'cuda' in af.get_available_backends():
print('CUDA:')
af.set_backend('cuda')
I3 = yp.rand(sz, backend='arrayfire')
%timeit af.signal.fft(I3)
%timeit af.signal.fft2_inplace(I2)
x_af = yp.rand(sz, backend='arrayfire')
y_af = yp.zeros(sz, backend='arrayfire')
# %timeit af.signal.fft(x_af)
# %timeit af.signal.fft(x_af, scale=10)
F = ops.FourierTransform(sz, backend='arrayfire', center=False, normalize=False)
%timeit F._forward(x_af, y_af)
%timeit af.signal.fft2_inplace(I2)
# F.f
# F_ocl.forward(x_af)
# x_af = yp.rand(sz, backend='arrayfire')
# F_ocl.forward(I2)
```
## GPU/Arrayfire Operator Test
```
# af.set_backend('cpu:')
# I1 = yp.rand(sz, backend='arrayfire')
# F_cpu = ops.FourierTransform(sz, backend='arrayfire', center=False, normalize=False, pad=False)
# print(af.get_backend_id(I1))
# %timeit F_cpu * I1
af.set_backend('opencl')
I2 = yp.rand(sz, backend='arrayfire')
F_ocl = ops.FourierTransform(sz, backend='arrayfire', center=False, normalize=False)
print(af.get_backend_id(I2))
%timeit F_ocl * I2
# af.set_backend('cuda')
# I3 = yp.rand(sz, backend='arrayfire')
# F_cuda = ops.FourierTransform(sz, backend='arrayfire', center=False, normalize=False, pad=False)
# print(af.get_backend_id(I3))
# %timeit F_cuda * I3
```
## GPU/Arrayfire Normalization Test
```
backend = 'numpy'
sz_0 = (100,100)
sz_1 = (50,50)
# Create fake object
x = yp.zeros(sz_0, backend=backend)
x[sz_1[0] // 4: 3* sz_1[0] // 4, sz_1[1] // 4: 3* sz_1[1] // 4] = yp.rand((sz_1[0] // 2, sz_1[1] // 2), backend=backend)
x /= yp.mean(yp.abs(x))
# Generate FFT operators
F_list_n = []
F_list_un = []
for fft_backend in yp.valid_fft_backends:
F_list_n.append(ops.FourierTransform(sz_0, backend=backend, fft_backend=fft_backend, center=True, normalize=True, pad=False))
F_list_un.append(ops.FourierTransform(sz_0, backend=backend, fft_backend=fft_backend, center=True, normalize=False, pad=False))
# Check energy in Fourier domain
x_energy = yp.sum(yp.abs(x) ** 2)
energies_unnormalized = [yp.sum(yp.abs(F * x) ** 2) / yp.size(x) for F in F_list_n]
energies_normalized = [yp.sum(yp.abs(F * x) ** 2) / yp.size(x) for F in F_list_un]
print(x_energy)
print(energies_unnormalized)
print(energies_normalized)
assert all([abs(energy_normalized - x_energy) < 1e-5 * x_energy for energy_normalized in energies_normalized])
assert all([abs(energy_unnormalized * yp.size(x) - x_energy) < 1e-4 * x_energy for energy_unnormalized in energies_unnormalized])
# Check inversion
assert all([yp.scalar(yp.sum(yp.abs(F.H * F * x - x))) < 1e-6 * x_energy for F in F_list_un])
assert all([yp.scalar(yp.sum(yp.abs(F.H * F * x - x))) < 1e-6 * x_energy for F in F_list_n])
```
## Numpy / Arrayfire Transform Similarity
```
normalize = False
sz = yp.shape(x)
x = yp.changeBackend(x, 'arrayfire')
F_af = ops.FourierTransform(sz, center=True, backend='arrayfire', normalize=normalize)
F_np = ops.FourierTransform(sz, center=True, backend='numpy', normalize=normalize)
plt.figure()
plt.subplot(221)
plt.imshow(yp.abs(yp.changeBackend(F_af * x, 'numpy')))
plt.title('Foward, af')
plt.colorbar()
plt.subplot(222)
plt.imshow(yp.abs(F_np * yp.changeBackend(x, 'numpy')))
plt.title('Foward, numpy')
plt.colorbar()
plt.subplot(223)
plt.imshow(yp.abs(yp.changeBackend(F_af.H * x, 'numpy')))
plt.title('Inverse, af')
plt.colorbar()
plt.subplot(224)
plt.imshow(yp.abs(F_np.H * yp.changeBackend(x, 'numpy')))
plt.title('Inverse, numpy')
plt.colorbar()
```
## Convolution Test
```
backend = 'arrayfire'
h = yp.zeros(sz_0, backend=backend)
h[sz_0[0] // 4 * 3, sz_0[1] // 4 * 3] = 1
# Create blur kernel
h = yp.changeBackend(h, backend)
h /= yp.sum(yp.abs(h))
# Generate forward operators
F = ops.FourierTransform(sz_0, backend=backend, center=True, normalize=False, pad=False)
A = F.H * ops.Diagonalize(h, inside_operator=F) * F
# Generate measurements
y = A * yp.changeBackend(x, backend)
y_sum = yp.scalar(yp.sum(yp.abs(y)))
# Check values
assert yp.scalar(yp.sum(yp.abs(x)) * yp.sum(yp.abs(h))) - y_sum
plt.figure(figsize=(11,4))
plt.subplot(131)
plt.imshow(np.abs(x))
plt.colorbar()
plt.subplot(132)
plt.imshow(np.abs(h))
plt.colorbar()
plt.subplot(133)
plt.imshow(np.abs(y))
plt.colorbar()
h = yp.zeros(sz_0)
h[sz_1[0] // 2:sz_1[0] // 2 + 1, sz_1[1] // 4: 3* sz_1[1] // 4,] = 1
# Create blur kernel
h = yp.changeBackend(h, 'arrayfire')
h /= yp.sum(yp.abs(h))
# Generate forward operators
F = ops.FourierTransform(sz_0, backend='arrayfire', center=False, normalize=False, pad=False)
A = F.H * ops.Diagonalize(h, inside_operator=F) * F
# Generate measurements
y = A * x
y_sum = yp.scalar(yp.sum(yp.abs(y)))
# Check values
assert yp.scalar(yp.sum(yp.abs(x)) * yp.sum(yp.abs(h))) - y_sum
plt.figure(figsize=(8,4))
plt.subplot(121)
plt.imshow(np.abs(x))
plt.colorbar()
plt.subplot(122)
plt.imshow(np.abs(y))
plt.colorbar()
```
| github_jupyter |
```
print("Hello World!")
import os
import tarfile
import urllib
import pandas as pd
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"
HOUSING_PATH = os.path.join("datasets", "housing")
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
os.makedirs(housing_path, exist_ok=True)
tgz_path = os.path.join(housing_path, "housing.tgz")
urllib.request.urlretrieve(housing_url, tgz_path)
housing_tgz = tarfile.open(tgz_path)
housing_tgz.extractall(path=housing_path)
housing_tgz.close()
fetch_housing_data()
def load_housing_data(housing_path=HOUSING_PATH):
csv_path = os.path.join(housing_path, "housing.csv")
return pd.read_csv(csv_path)
housing = load_housing_data()
# Dataframe.head() ~ housing.head() will show the first few examples in the dataframe
housing.head()
# Dataframe.info() ~ housing.info() will provide some information about the data in the dataframe.
# RangeIndex: 20640 ~ means there are 20640 entries or rows in the dataframe
# longitude: 20640 non-null float64 ~ means that the column/feature longitude has 20640 non-null float64 values
# total_bedroom: 20433 non-null float64 ~ means that 20433 of the 20640 rows have non-null float64 values, ...
# thus 207 rows are missing values
housing.info()
# Dataframe["COLUMN_NAME"].value_counts() ~ housing["ocean_proximity"].value_counts() will take the column "ocean_proximity"...
# from the housing dataframe and provide the number of occurrences for each unique value in that column
# There are 2658 housing datapoints which have the "NEAR OCEAN" value in the "ocean_proximity" column
housing["ocean_proximity"].value_counts()
# Dataframe.describe() ~ housing.describe() will provide many valuable statistics for the columns/features of the dataframe
housing.describe()
%matplotlib inline
import matplotlib.pyplot as plt
housing.hist(bins=50, figsize=(20,15))
plt.show()
import numpy as np
def split_train_test(data, test_ratio):
shuffled_indices = np.random.permutation(len(data))
test_set_size = int(len(data) * test_ratio)
test_indices = shuffled_indices[:test_set_size]
train_indices = shuffled_indices[test_set_size:]
return data.iloc[train_indices], data.iloc[test_indices]
train_set, test_set = split_train_test(housing, 0.2)
print("The number of entries in train_set = {}\n".format(len(train_set)))
print("The number of entries in train_set = {}\n".format(len(test_set)))
from zlib import crc32
def test_set_check(identifier, test_ratio):
return crc32(np.int64(identifier)) & 0xffffffff < test_ratio * 2**32
def split_train_test_by_id(data, test_ratio, id_column):
ids = data[id_column]
in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio))
return data.loc[~in_test_set], data.loc[in_test_set]
housing_with_id = housing.reset_index()
train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "index")
housing_with_id["id"] = housing["longitude"] * 1000 + housing["latitude"]
train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "id")
housing_with_id.head()
from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
housing["income_cat"] = pd.cut(housing["median_income"], bins=[0.0, 1.5, 3.0, 4.5, 6., np.inf], labels=[1, 2, 3, 4, 5])
housing["income_cat"].hist()
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing["income_cat"]):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
strat_test_set["income_cat"].value_counts() / len(strat_test_set)
for set_ in (strat_train_set, strat_test_set):
set_.drop("income_cat", axis=1, inplace=True)
housing = strat_train_set.copy()
housing.plot(kind="scatter", x="longitude", y="latitude")
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.1)
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
s=housing["population"]/100, label="population", figsize=(10,7),
c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True)
plt.legend()
corr_matrix = housing.corr()
corr_matrix["median_house_value"].sort_values(ascending=False)
from pandas.plotting import scatter_matrix
attributes = ["median_house_value","median_income","total_rooms","housing_median_age"]
scatter_matrix(housing[attributes], figsize=(12,8))
housing.plot(kind="scatter", x="median_income", y="median_house_value", alpha=0.1)
housing["rooms_per_household"] = housing["total_rooms"] / housing["households"]
housing["bedrooms_per_room"] = housing["total_bedrooms"] / housing["total_rooms"]
housing["population_per_household"] = housing["population"] / housing["households"]
corr_matrix = housing.corr()
corr_matrix["median_house_value"].sort_values(ascending=False)
f = plt.figure(figsize=(19, 15))
plt.matshow(corr_matrix, fignum=f.number)
plt.xticks(range(corr_matrix.shape[1]), corr_matrix.columns, fontsize=14, rotation=45)
plt.yticks(range(corr_matrix.shape[1]), corr_matrix.columns, fontsize=14)
cb = plt.colorbar()
cb.ax.tick_params(labelsize=14)
plt.title('Correlation Matrix', fontsize=16)
housing = strat_train_set.drop("median_house_value", axis=1)
housing_labels = strat_train_set["median_house_value"].copy()
```
# Data Cleaning
```
# total_bedrooms has missing values, we can fix that with one of these next three options
# option 1 ~ this will drop the rows from entire dataframe where the column/feature "total_bedrooms" is empty
housing.dropna(subset=["total_bedrooms"])
# option 2 ~ this will remove the entire column/feature from dataframe
housing.drop("total_bedrooms", axis=1)
# option 3 ~ this will calculate the median value for the 'total_bedroom' column/feature and replace any missing values with...
# the calculated median value. The 'inplace' flag must be true or your dataframe will not make the changes to...
# your dataframe but will just execute the command which. The 'inplace' flag will apply the changes directly...
# to your dataframe
median = housing["total_bedrooms"].median()
housing["total_bedrooms"].fillna(median, inplace=True)
# sklearn has an alternate method for filling in missing values
from sklearn.impute import SimpleImputer
# First we must create an instance of the SimpleImputer class
imputer = SimpleImputer(strategy="median")
# SimpleImputer will fail if there exists categorical data/labels, we must remove to use SimpleImputer
housing_num = housing.drop("ocean_proximity", axis=1)
# We must fit the Imputer to the remaining all numberical dataframe
imputer.fit(housing_num)
print("Imputer Statistics:\n{}\n".format(imputer.statistics_))
print("Dataframe Statistics:\n{}\n".format(housing_num.median().values))
# Now we can replace the missing values with the trained values of the imputer, this will return a numpy array
X = imputer.transform(housing_num)
# Put numpy array back into a dataframe
housing_tr = pd.DataFrame(X, columns=housing_num.columns, index=housing_num.index)
```
# Categorical Data
```
housing_cat = housing[["ocean_proximity"]]
housing_cat.head(10)
# Convert the categorical data in the 'ocean_proximity' column/feature into numerical
from sklearn.preprocessing import OrdinalEncoder
ordinal_encoder = OrdinalEncoder()
housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat)
print("The first 10 values in housing_cat_encoded: \n{}".format(housing_cat_encoded[:10]))
# This will then allow you to associate those categorical values into numerical and the OrdinalEncoder...
# saves the mapping between the two so you are able to go back and forth as needed.
print("Ordinal Encorder Categories:\n{}\n".format(ordinal_encoder.categories_))
# Machine learning will assume distance between values corresponds to similarity. So it would assume that "<1H OCEAN"...
# is more similar to "INLAND" when it is much more similar to "NEAR OCEAN".
# To Solve this we can one-hot encode
from sklearn.preprocessing import OneHotEncoder
cat_encoder = OneHotEncoder()
# housing_cat_1hot will be returned as a sparse array ~ thus the 0 data is not included, only locations where non-zero...
# this will save memory as a vast majority of the array will be 0's. You can convert into a dense array, one which...
# contains the 0's populated by using "housing_cat_1hot.toarray()"
housing_cat_1hot = cat_encoder.fit_transform(housing_cat)
# The categories are available using the fit encoder
print("One Hot Encoder Categories:\n{}\n".format(cat_encoder.categories_))
```
# Custom Transformers
```
from sklearn.base import BaseEstimator, TransformerMixin
rooms_ix, bedrooms_ix, population_ix, households_ix = 3, 4, 5, 6
class CombinedAttributesAdder(BaseEstimator, TransformerMixin):
def __init__(self, add_bedrooms_per_room=True):
self.add_bedrooms_per_room = add_bedrooms_per_room
def fit(self, X, y=None):
return self
def transform(self, X):
rooms_per_household = X[:, rooms_ix] / X[:, households_ix]
population_per_household = X[:, population_ix] / X[:, households_ix]
if self.add_bedrooms_per_room:
bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix]
return np.c_[X, rooms_per_household, population_per_household, bedrooms_per_room]
else:
return np.c_[X, rooms_per_household, population_per_household]
attr_adder = CombinedAttributesAdder(add_bedrooms_per_room=False)
housing_extra_attribs = attr_adder.transform(housing.values)
print("Housing Extra Attribs:\n{}".format(housing_extra_attribs))
```
# Transformation Pipelines
```
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
# The Pipeline class takes a list of steps, this case we use the 'imputer' first, then 'attribs_adder', then "std_scaler"
num_pipeline = Pipeline([("imputer", SimpleImputer(strategy="median")),
("attribs_adder", CombinedAttributesAdder()),
("std_scaler", StandardScaler())])
housing_num_tr = num_pipeline.fit_transform(housing_num)
# Column based transformation pipelines
from sklearn.compose import ColumnTransformer
# List of numerical column names ~ just a list of housing_num which was a dataframe we made previously containing only numerical data
num_attribs = list(housing_num)
# List of categorical columns ~ since we only have one categorical column "ocean_proximity", we manually specify it
cat_attribs = ["ocean_proximity"]
# full_pipeline works by first calling our 'num_pipeline', we specified above. This will run through its pipeline first. Since...
# this is the ColumnTransformer, it works on each column and then concatenates the results. Finally we use OneHotEncoding...
# on the categorical column.
full_pipeline = ColumnTransformer([("num", num_pipeline, num_attribs),
("cat", OneHotEncoder(), cat_attribs)])
housing_prepared = full_pipeline.fit_transform(housing)
```
# Training a Model
```
# Linear Regression is used in this example but it would require there to be a linear relationship between the data...
# for this algorithm to perform well. A root mean square error of 68628 is fairly high we can conclude a linear relationship...
# may exist but to better capture the data/patterns we need more degrees of freedom.
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(housing_prepared, housing_labels)
some_data = housing.iloc[:5]
some_labels = housing_labels.iloc[:5]
some_data_prepared = full_pipeline.transform(some_data)
print("\nPredictions:", lin_reg.predict(some_data_prepared))
print("\nLabels:", list(some_labels))
from sklearn.metrics import mean_squared_error
housing_predictions = lin_reg.predict(housing_prepared)
lin_mse = mean_squared_error(housing_labels, housing_predictions)
lin_rmse = np.sqrt(lin_mse)
print("\nLinear Regression Root Mean Square Error: {}\n".format(lin_rmse))
# Decision Tree ~ should be able to fit the data much better but typically will overfit without some form of prunning...
# Prunning removes some specified number of leaves or even hold nodes, based on how the prunning is implemented...
# Some will remove nodes where the information gain is not above a certain threshold, others may remove leaves which...
# do not contain a thresholded number of instances.
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor()
# Fitting the model is training the model
tree_reg.fit(housing_prepared, housing_labels)
housing_predictions = tree_reg.predict(housing_prepared)
tree_mse = mean_squared_error(housing_labels, housing_predictions)
tree_rmse = np.sqrt(tree_mse)
print("\n Decision Tree Regression Root Mean Square Error: {}\n".format(tree_rmse))
# We can see the Decision Tree Regressor has a RMSE of 0.0 and that is being it does not have prunning implemented, thus...
# has overfit the training data perfectly (which is bad).
```
# Cross-Validation
```
# Cross-Validation will take a subset of the dataset and train the model on that, evaluate and compare. CV=10, means we...
# will be doing this evaluation 10 times with 10 randomly selected subsets.
from sklearn.model_selection import cross_val_score
scores = cross_val_score(tree_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10)
tree_rmse_scores = np.sqrt(-scores)
def display_scores(scores):
print("\nScores: {}\n".format(scores))
print("\nMean: {}\n".format(scores.mean()))
print("\nStandard Deviation: {}\n".format(scores.std()))
display_scores(tree_rmse_scores)
lin_scores = cross_val_score(lin_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10)
lin_rmse_scores = np.sqrt(-lin_scores)
display_scores(lin_rmse_scores)
```
# Ensemble Learning
```
from sklearn.ensemble import RandomForestRegressor
forest_reg = RandomForestRegressor()
forest_reg.fit(housing_prepared, housing_labels)
forest_scores = cross_val_score(forest_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10)
forest_rmse_scores = np.sqrt(-forest_scores)
display_scores(forest_rmse_scores)
```
# GridSearch
```
from sklearn.model_selection import GridSearchCV
param_grid = [{"n_estimators": [3, 10, 30], "max_features": [2, 4, 6, 8]},
{"bootstrap": [False], "n_estimators": [3, 10], "max_features": [2, 3, 4]}]
forest_reg = RandomForestRegressor()
grid_search = GridSearchCV(forest_reg, param_grid=param_grid, cv=5,
scoring="neg_mean_squared_error", return_train_score=True)
grid_search.fit(housing_prepared, housing_labels)
cvres = grid_search.cv_results_
for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]):
print(np.sqrt(-mean_score), params)
feature_importance = grid_search.best_estimator_.feature_importances_
print("\nFeature Importance: \n{}\n".format(feature_importance))
extra_attribs = ["rooms_per_hhold", "pop_per_hhold", "bedrooms_per_room"]
cat_encoder = full_pipeline.named_transformers_["cat"]
cat_one_hot_attribs = list(cat_encoder.categories_[0])
attributes = num_attribs + extra_attribs + cat_one_hot_attribs
resultes = sorted(zip(feature_importance, attributes), reverse=True)
print("Results of Feature and Importance: \n{}\n".format(resultes))
```
# Evaluate The Model
```
final_model = grid_search.best_estimator_
X_test = strat_test_set.drop("median_house_value", axis=1)
y_test = strat_test_set["median_house_value"].copy()
X_test_prepared = full_pipeline.transform(X_test)
final_predictions = final_model.predict(X_test_prepared)
final_mse = mean_squared_error(y_test, final_predictions)
final_rmse = np.sqrt(final_mse)
print("\nThe Final Model Root Mean Squared Error: {}\n".format(final_rmse))
from scipy import stats
confidence = 0.95
squared_errors = (final_predictions - y_test) ** 2
final_results = np.sqrt(stats.t.interval(confidence, len(squared_errors) - 1,
loc=squared_errors.mean(),
scale=stats.sem(squared_errors)))
print("\nFinal Results: {}\n".format(final_results))
```
| github_jupyter |
\title{myHDL to PYNQ Fabric Only Exsample}
\author{Steven K Armour}
\maketitle
# Refrances
# Libraries and Helper functions
```
from myhdl import *
from myhdlpeek import Peeker
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sympy import *
init_printing()
import random
#https://github.com/jrjohansson/version_information
%load_ext version_information
%version_information myhdl, myhdlpeek, numpy, pandas, matplotlib, sympy, random
#helper functions to read in the .v and .vhd generated files into python
def VerilogTextReader(loc, printresult=True):
with open(f'{loc}.v', 'r') as vText:
VerilogText=vText.read()
if printresult:
print(f'***Verilog modual from {loc}.v***\n\n', VerilogText)
return VerilogText
def VHDLTextReader(loc, printresult=True):
with open(f'{loc}.vhd', 'r') as vText:
VerilogText=vText.read()
if printresult:
print(f'***VHDL modual from {loc}.vhd***\n\n', VerilogText)
return VerilogText
```
# Project 1: 1 Switch 1 LED
https://timetoexplore.net/blog/arty-fpga-verilog-01
## Constraints File
## myHDL Code
```
@block
def S0L0(sw, clk, led):
"""
FPGA Hello world of one switch controlling one LED based on
https://timetoexplore.net/blog/arty-fpga-verilog-01
Target:
ZYNQ 7000 Board (Arty, PYNQ-Z1, PYNQ-Z2) with at least 2
switchs and 4 leds
Input:
sw(2bitVec):switch input
clk(bool): clock input
Ouput:
led(4bitVec): led output
"""
@always(clk.posedge)
def logic():
if sw[0]==0:
led.next[0]=True
else:
led.next[0]=False
return instances()
```
## myHDL Testing
```
Peeker.clear()
clk=Signal(bool(0)); Peeker(clk, 'clk')
sw=Signal(intbv(0)[2:]); Peeker(sw, 'sw')
led=Signal(intbv(0)[4:]); Peeker(led, 'led')
np.random.seed(18)
swTVals=[int(i) for i in np.random.randint(0,2, 10)]
DUT=S0L0(sw, clk, led)
def S0L0_TB():
@always(delay(1))
def ClkGen():
clk.next=not clk
@instance
def stimules():
for i in range(10):
sw.next[0]=swTVals[i]
yield clk.posedge
raise StopSimulation()
return instances()
sim=Simulation(DUT, S0L0_TB(), *Peeker.instances()).run()
Peeker.to_wavedrom()
Peeker.to_dataframe()
```
## Verilog Code
```
DUT.convert()
VerilogTextReader('S0L0');
```
\begin{figure}
\centerline{\includegraphics[width=10cm]{S0L0_RTL.png}}
\caption{\label{fig:S0L0RTL} S0L0 RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{S0L0_SYN.png}}
\caption{\label{fig:S0L0SYN} S0L0 Synthesized Schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{S0L0_SYN.png}}
\caption{\label{fig:S0L0SYN} S0L0 Implementated Schematic; Xilinx Vivado 2017.4}
\end{figure}
## PYNQ-Z1 Constraints File
Below is what is found in file `constrs_S0L0.xdc`
Notice that the orgianl port names found in the PYNQ-Z1 Constraints file have been changed to the port names of the module `S0L0`
## Verilog Testbench
```
swTVal=intbv(int(''.join([str(i) for i in swTVals]), 2))[len(swTVals):]
print(f'swTest: {swTVals}, {swTVal}, {[int(i) for i in swTVal]}')
@block
def S0L0_TBV():
clk=Signal(bool(0))
sw=Signal(intbv(0)[2:])
led=Signal(intbv(0)[4:])
#test stimuli
swTVals=Signal(swTVal)
@always_comb
def print_data():
print(sw, clk, led)
DUT=S0L0(sw, clk, led)
@instance
def clk_signal():
while True:
clk.next = not clk
yield delay(1)
@instance
def stimules():
for i in range(10):
sw.next[0]=swTVals[i]
yield clk.posedge
raise StopSimulation()
return instances()
TB=S0L0_TBV()
TB.convert(hdl="Verilog", initial_values=True)
VerilogTextReader('S0L0_TBV');
```
## Board Verification
# Project 2: 2 Switchs 4 LEDS
https://timetoexplore.net/blog/arty-fpga-verilog-01
## myHDL Code
```
@block
def S2L4(sw, clk, led):
"""
FPGA Hello world of two switchs controlling four LED based on
https://timetoexplore.net/blog/arty-fpga-verilog-01
Target:
ZYNQ 7000 Board (Arty, PYNQ-Z1, PYNQ-Z2) with at least 2
switchs and 4 leds
Input:
sw(2bitVec):switch input
clk(bool): clock input
Ouput:
led(4bitVec): led output
"""
@always(clk.posedge)
def logic():
if sw[0]==0:
led.next[2:]=0
else:
led.next[2:]=3
if sw[1]==0:
led.next[4:2]=0
else:
led.next[4:2]=3
return instances()
```
## myHDL Testing
```
Peeker.clear()
clk=Signal(bool(0)); Peeker(clk, 'clk')
sw=Signal(intbv(0)[2:]); Peeker(sw, 'sw')
led=Signal(intbv(0)[4:]); Peeker(led, 'led')
np.random.seed(18)
swTVals=[int(i) for i in np.random.randint(0,4, 10)]
DUT=S2L4(sw, clk, led)
def S2L4_TB():
@always(delay(1))
def ClkGen():
clk.next=not clk
@instance
def stimules():
for i in range(10):
sw.next=swTVals[i]
yield clk.posedge
raise StopSimulation()
return instances()
sim=Simulation(DUT, S2L4_TB(), *Peeker.instances()).run()
Peeker.to_wavedrom()
Peeker.to_dataframe()
```
## Verilog Code
```
DUT.convert()
VerilogTextReader('S2L4');
```
\begin{figure}
\centerline{\includegraphics[width=10cm]{S2L4_RTL.png}}
\caption{\label{fig:S2L4RTL} S2L4 RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{S2L4_SYN.png}}
\caption{\label{fig:S2L4SYN} S2L4 Synthesized Schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{S2L4_IMP.png}}
\caption{\label{fig:S2L4SYN} S2L4 Implementated Schematic; Xilinx Vivado 2017.4}
\end{figure}
## Verilog Testbench (ToDo)
will write later when testbench conversion is improved
## PYNQ-Z1 Constraints File
using same one as in **1 Switch 1 LED**: `constrs_S0L0.xdc`
## Board Verification
# Project 3: Countdown
## myHDL Code
```
@block
def countLED(clk, led):
counter=Signal(modbv(0)[33:])
@always(clk.posedge)
def logic():
counter.next=counter+1
led.next[0]=counter[26]
led.next[1]=counter[24]
led.next[3]=counter[22]
led.next[4]=counter[20]
return instances()
```
## myHDL Testing
```
Peeker.clear()
clk=Signal(bool(0)); Peeker(clk, 'clk')
led=Signal(intbv(0)[4:]); Peeker(led, 'led')
DUT=countLED(clk, led)
'''
def countLED_TB():
@always(delay(1))
def ClkGen():
clk.next=not clk
@instance
def stimules():
i=0
while True:
if i==2**33:
raise StopSimulation()
if 1%100==0:
print(i)
i+=1
yield clk.posedge
return instances()
sim=Simulation(DUT, countLED_TB(), *Peeker.instances()).run()
'''
;
```
Need to figure out how to write/run these long simulations better in python
## Verilog Code
```
DUT.convert()
VerilogTextReader('countLED');
```
## Verilog Testbench
## PYNQ-Z1 Constraints File
Below is what is found in file `constrs_S0L0.xdc`
Notice that the orgianl port names found in the PYNQ-Z1 Constraints file have been changed to the port names of the module `S0L0`
## Board Verification
# Project 4: Basic Duty Cycle
https://timetoexplore.net/blog/arty-fpga-verilog-02
## myHDL Code
```
@block
def BDCLed(clk, led):
counter=Signal(modbv(0)[8:])
duty_led=Signal(modbv(8)[8:])
@always(clk.posedge)
def logic():
counter.next=counter+1
if counter<duty_led:
led.next=15
else:
led.next=0
return instances()
```
## myHDL Testing
```
Peeker.clear()
clk=Signal(bool(0)); Peeker(clk, 'clk')
led=Signal(intbv(0)[4:]); Peeker(led, 'led')
DUT=BDCLed(clk, led)
def BDCLed_TB():
@always(delay(1))
def ClkGen():
clk.next=not clk
@instance
def stimules():
i=0
while True:
if i==1000:
raise StopSimulation()
i+=1
yield clk.posedge
return instances()
sim=Simulation(DUT, BDCLed_TB(), *Peeker.instances()).run()
Peeker.to_wavedrom()
BDCLedData=Peeker.to_dataframe()
BDCLedData=BDCLedData[BDCLedData['clk']==1]
BDCLedData.plot(y='led');
```
## Verilog Code
```
DUT.convert()
VerilogTextReader('BDCLed');
```
## PYNQ-Z1 Constraints File
Below is what is found in file `constrs_S0L0.xdc`
Notice that the orgianl port names found in the PYNQ-Z1 Constraints file have been changed to the port names of the module `S0L0`
## Verilog Testbench
```
@block
def BDCLed_TBV():
clk=Signal(bool(0))
led=Signal(intbv(0)[4:])
@always_comb
def print_data():
print(sw, clk, led)
DUT=BDCLed(clk, led)
@instance
def clk_signal():
while True:
clk.next = not clk
yield delay(1)
@instance
def stimules():
i=0
while True:
if i==1000:
raise StopSimulation()
i+=1
yield clk.posedge
return instances()
TB=BDCLed_TBV()
TB.convert(hdl="Verilog", initial_values=True)
VerilogTextReader('BDCLed_TBV');
```
## Board Verification
# Project 5: Mid level PWM LED
## pwm myHDL Code
```
@block
def pwm(clk, dutyCount, o_state):
counter=Signal(modbv(0)[8:])
@always(clk.posedge)
def logic():
counter.next=counter+1
o_state.next=counter<dutyCount
return instances()
```
## pwm myHDL Testing
```
Peeker.clear()
clk=Signal(bool(0)); Peeker(clk, 'clk')
dutyCount=Signal(intbv(4)[8:]); Peeker(dutyCount, 'dutyCount')
o_state=Signal(bool(0)); Peeker(o_state, 'o_state')
DUT=pwm(clk, dutyCount, o_state)
def pwm_TB():
pass
```
## pwm Verilog Code
| github_jupyter |
```
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
path = "/Users/sebastianlee/Dropbox/Documents/Research/Projects/catastrophic/run/results/fig_2_data/"
ode_df = pd.read_csv(os.path.join(path, "ode_log.csv"))
network_df = pd.read_csv(os.path.join(path, "network_log.csv"))
f = 200
fig = plt.figure(figsize=(15,12))
network_error_0 = np.array(network_df["log_generalisation_error_0"])
network_error_1 = np.array(network_df["log_generalisation_error_1"])
ode_error_0 = np.array(ode_df["log_generalisation_error_0"])
ode_error_1 = np.array(ode_df["log_generalisation_error_1"])
plt.plot(range(len(network_error_0)), network_error_0, alpha=0.8, linewidth=5, color="#2A9D8F")
plt.plot(range(len(network_error_1)), network_error_1, alpha=0.8, linewidth=5, color="#E9C46A")
plt.scatter(range(len(ode_error_0))[::f], ode_error_0[::f], marker="+", color="#2A9D8F", s=400)
plt.scatter(range(len(ode_error_1))[::f], ode_error_1[::f], marker="+", color="#E9C46A", s=400)
plt.xlim(0, 10000)
plt.ylim(-4.5, -0.5)
plt.minorticks_on()
plt.grid(b=True, which='major', color='r', linestyle='-', alpha=0.2)
plt.grid(b=True, which='minor', color='gray', linestyle='--', alpha=0.2)
plt.tick_params(
axis='both', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False, # labels along the bottom edge are off
left=False,
labelleft=False
)
fig.show()
fig.savefig("ode_verification_error_crosses.pdf", dpi=100, bbox_inches='tight', pad_inches=0)
network_df.keys()
f = 200
fig = plt.figure(figsize=(15,12))
network_error_q_00 = np.array(network_df["student_self_overlap_0_0"])
network_error_q_01 = np.array(network_df["student_self_overlap_0_1"])
network_error_q_10 = np.array(network_df["student_self_overlap_1_0"])
network_error_q_11 = np.array(network_df["student_self_overlap_1_1"])
ode_error_q_00 = np.array(ode_df["student_self_overlap_0_0"])
ode_error_q_01 = np.array(ode_df["student_self_overlap_0_1"])
ode_error_q_10 = np.array(ode_df["student_self_overlap_1_0"])
ode_error_q_11 = np.array(ode_df["student_self_overlap_1_1"])
plt.plot(range(len(network_error_q_00)), network_error_q_00, alpha=0.8, linewidth=5, color="#5465ff")
plt.plot(range(len(network_error_q_01)), network_error_q_01, alpha=0.8, linewidth=5, color="#788bff")
plt.plot(range(len(network_error_q_10)), network_error_q_10, alpha=0.8, linewidth=5, color="#9bb1ff")
plt.plot(range(len(network_error_q_11)), network_error_q_11, alpha=0.8, linewidth=5, color="#bfd7ff")
plt.scatter(range(len(ode_error_q_00))[::f], ode_error_q_00[::f], color="#5465ff", marker="+", s=400)
plt.scatter(range(len(ode_error_q_01))[::f], ode_error_q_01[::f], color="#788bff", marker="+", s=400)
plt.scatter(range(len(ode_error_q_10))[::f], ode_error_q_10[::f], color="#9bb1ff", marker="+", s=400)
plt.scatter(range(len(ode_error_q_11))[::f], ode_error_q_11[::f], color="#bfd7ff", marker="+", s=400)
plt.xlim(0, 10000)
plt.ylim(0, 1.2)
plt.minorticks_on()
plt.grid(b=True, which='major', color='r', linestyle='-', alpha=0.2)
plt.grid(b=True, which='minor', color='gray', linestyle='--', alpha=0.2)
plt.tick_params(
axis='both', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False, # labels along the bottom edge are off
left=False,
labelleft=False
)
fig.show()
fig.savefig("ode_verification_q_crosses.pdf", dpi=100, bbox_inches='tight', pad_inches=0)
f = 200
fig = plt.figure(figsize=(15,12))
network_error_r_00 = np.array(network_df["student_teacher_0_overlap_0_0"])
network_error_r_10 = np.array(network_df["student_teacher_0_overlap_1_0"])
ode_error_r_00 = np.array(ode_df["student_teacher_0_overlap_0_0"])
ode_error_r_10 = np.array(ode_df["student_teacher_0_overlap_1_0"])
plt.plot(range(len(network_error_r_00)), network_error_r_00, alpha=0.8, linewidth=5, color="#245501")
plt.plot(range(len(network_error_r_10)), network_error_r_10, alpha=0.8, linewidth=5, color="#73a942")
plt.scatter(range(len(ode_error_r_00))[::f], ode_error_r_00[::f], color="#245501", marker="+", s=400)
plt.scatter(range(len(ode_error_r_10))[::f], ode_error_r_10[::f], color="#73a942", marker="+", s=400)
plt.xlim(0, 10000)
plt.ylim(-1.2, 0.05)
plt.minorticks_on()
plt.grid(b=True, which='major', color='r', linestyle='-', alpha=0.2)
plt.grid(b=True, which='minor', color='gray', linestyle='--', alpha=0.2)
plt.tick_params(
axis='both', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False, # labels along the bottom edge are off
left=False,
labelleft=False
)
fig.show()
fig.savefig("ode_verification_r_crosses.pdf", dpi=100, bbox_inches='tight', pad_inches=0)
f = 200
fig = plt.figure(figsize=(15,12))
network_error_u_00 = np.array(network_df["student_teacher_1_overlap_0_0"])
network_error_u_10 = np.array(network_df["student_teacher_1_overlap_1_0"])
ode_error_u_00 = np.array(ode_df["student_teacher_1_overlap_0_0"])
ode_error_u_10 = np.array(ode_df["student_teacher_1_overlap_1_0"])
plt.plot(range(len(network_error_u_00)), network_error_u_00, alpha=0.8, linewidth=5, color="#245501")
plt.plot(range(len(network_error_u_10)), network_error_u_10, alpha=0.8, linewidth=5, color="#73a942")
plt.scatter(range(len(ode_error_u_00))[::f], ode_error_u_00[::f], color="#245501", marker="+", s=400)
plt.scatter(range(len(ode_error_u_10))[::f], ode_error_u_10[::f], color="#73a942", marker="+", s=400)
plt.xlim(0, 10000)
plt.ylim(-1.2, 0.05)
plt.minorticks_on()
plt.grid(b=True, which='major', color='r', linestyle='-', alpha=0.2)
plt.grid(b=True, which='minor', color='gray', linestyle='--', alpha=0.2)
plt.tick_params(
axis='both', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False, # labels along the bottom edge are off
left=False,
labelleft=False
)
fig.show()
fig.savefig("ode_verification_u_crosses.pdf", dpi=100, bbox_inches='tight', pad_inches=0)
f = 200
fig = plt.figure(figsize=(15,12))
network_error_head_0_0 = np.array(network_df["student_head_0_weight_0"])
network_error_head_0_1 = np.array(network_df["student_head_0_weight_1"])
network_error_head_1_0 = np.array(network_df["student_head_1_weight_0"])
network_error_head_1_1 = np.array(network_df["student_head_1_weight_1"])
ode_error_head_0_0 = np.array(ode_df["student_head_0_weight_0"])
ode_error_head_0_1 = np.array(ode_df["student_head_0_weight_1"])
ode_error_head_1_0 = np.array(ode_df["student_head_1_weight_0"])
ode_error_head_1_1 = np.array(ode_df["student_head_1_weight_1"])
plt.plot(range(len(network_error_head_0_0)), network_error_head_0_0, alpha=0.8, linewidth=5, color="#E9C46A")
plt.plot(range(len(network_error_head_0_1)), network_error_head_0_1, alpha=0.8, linewidth=5, color="#F4A261")
plt.plot(range(len(network_error_head_1_0)), network_error_head_1_0, alpha=0.8, linewidth=5, color="#2A9D8F")
plt.plot(range(len(network_error_head_1_1)), network_error_head_1_1, alpha=0.8, linewidth=5, color="#4E8098")
plt.scatter(range(len(ode_error_head_0_0))[::f], ode_error_head_0_0[::f], color="#E9C46A", marker="+", s=400)
plt.scatter(range(len(ode_error_head_0_1))[::f], ode_error_head_0_1[::f], color="#F4A261", marker="+", s=400)
plt.scatter(range(len(ode_error_head_1_0))[::f], ode_error_head_1_0[::f], color="#2A9D8F", marker="+", s=400)
plt.scatter(range(len(ode_error_head_1_1))[::f], ode_error_head_1_1[::f], color="#4E8098", marker="+", s=400)
plt.xlim(0, 10000)
plt.ylim(-1, 1)
plt.minorticks_on()
plt.grid(b=True, which='major', color='r', linestyle='-', alpha=0.2)
plt.grid(b=True, which='minor', color='gray', linestyle='--', alpha=0.2)
plt.tick_params(
axis='both', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False, # labels along the bottom edge are off
left=False,
labelleft=False
)
fig.show()
fig.savefig("ode_verification_heads_crosses.pdf", dpi=100, bbox_inches='tight', pad_inches=0)
```
| github_jupyter |
```
import tensorflow as tf
import pandas as pd
import random
from zipfile import ZipFile
random.seed(42)
train_df = pd.read_csv("Train.csv")
test_df = pd.read_csv("Test.csv")
def addextension(nm):
return nm+".jpg"
train_df["Image_ID"] = train_df["Image_ID"].apply(addextension)
test_df["Image_ID"] = test_df["Image_ID"].apply(addextension)
print(train_df.head())
def unzip(nm):
with ZipFile(nm,"r") as zip:
zip.extractall()
unzip("Train_Images.zip")
unzip("Test_Images.zip")
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_gen = ImageDataGenerator(
horizontal_flip = True,
rotation_range = 10,
zoom_range = 0.1,
validation_split = 0.2,
)
train_ds = train_gen.flow_from_dataframe(
directory = "Train_Images",
dataframe = train_df,
x_col = "Image_ID",
y_col = "class",
target_size = (256,256),
batch_size = 32,
class_mode = "categorical",
shuffle = True,
subset = "training",
)
val_ds = train_gen.flow_from_dataframe(
directory = "Train_Images",
dataframe = train_df,
x_col = "Image_ID",
y_col = "class",
target_size = (256,256),
batch_size = 32,
class_mode = "categorical",
shuffle = True,
subset = "validation",
)
from tensorflow.keras import layers
from tensorflow.keras import Model, Input
def model(input):
x = layers.Rescaling(1./255)(input)
x = layers.Conv2D(64,3,activation="relu",padding="same",strides=(2,2))(x)
x = layers.MaxPooling2D()(x)
x = layers.Conv2D(128,3,activation="relu",padding="same",strides=(2,2))(x)
x = layers.Conv2D(128,3,activation="relu",padding="same",strides=(2,2))(x)
x = layers.Conv2D(256,3,activation="relu",padding="same",strides=(2,2))(x)
x = layers.MaxPooling2D()(x)
x = layers.Flatten()(x)
x = layers.Dense(512,activation="relu")(x)
x = layers.Dropout(0.2,seed=42)(x)
x = layers.Dense(512,activation="relu")(x)
x = layers.Dropout(0.2,seed=42)(x)
output = layers.Dense(3,activation="softmax")(x)
model = Model(input,output)
return model
model = model(Input(shape=(256,256,3)))
model.summary()
model.compile(tf.keras.optimizers.RMSprop(),tf.keras.losses.CategoricalCrossentropy(),metrics=["accuracy"])
if __name__=="__main__":
checkpoint = tf.keras.callbacks.ModelCheckpoint("makerere.h5",save_weights_only=False,save_best_only=True,monitor="val_accuracy")
model.fit(train_ds,epochs=20,validation_data=val_ds,callbacks=[checkpoint])
best = tf.keras.models.load_model("makerere.h5")
val_loss,val_acc = best.evaluate(val_ds)
print("\nVal Accuracy: {:.2f} %".format(100*val_acc))
print("Val Loss: {:.2f} %".format(100*val_loss))
```
| github_jupyter |
## Regression with BIWI head pose dataset
This is a more advanced example to show how to create custom datasets and do regression with images. Our task is to find the center of the head in each image. The data comes from the [BIWI head pose dataset](https://data.vision.ee.ethz.ch/cvl/gfanelli/head_pose/head_forest.html#db), thanks to Gabriele Fanelli et al. We have converted the images to jpeg format, so you should download the converted dataset from [this link](https://s3.amazonaws.com/fast-ai-imagelocal/biwi_head_pose.tgz).
```
%reload_ext autoreload
%autoreload 2
%matplotlib inline
from fastai import *
from fastai.vision import *
```
## Getting and converting the data
```
path = untar_data(URLs.BIWI_HEAD_POSE)
cal = np.genfromtxt(path/'01'/'rgb.cal', skip_footer=6); cal
fname = '09/frame_00667_rgb.jpg'
def img2txt_name(f): return path/f'{str(f)[:-7]}pose.txt'
img = open_image(path/fname)
img.show()
ctr = np.genfromtxt(img2txt_name(fname), skip_header=3); ctr
def convert_biwi(coords):
c1 = coords[0] * cal[0][0]/coords[2] + cal[0][2]
c2 = coords[1] * cal[1][1]/coords[2] + cal[1][2]
return tensor([c2,c1])
def get_ctr(f):
ctr = np.genfromtxt(img2txt_name(f), skip_header=3)
return convert_biwi(ctr)
def get_ip(img,pts): return ImagePoints(FlowField(img.size, pts), scale=True)
get_ctr(fname)
ctr = get_ctr(fname)
img.show(y=get_ip(img, ctr), figsize=(6, 6))
```
## Creating a dataset
```
data = (ImageItemList.from_folder(path)
.split_by_valid_func(lambda o: o.parent.name=='13')
.label_from_func(get_ctr, label_cls=PointsItemList)
.transform(get_transforms(), tfm_y=True, size=(120,160))
.databunch().normalize(imagenet_stats)
)
data.show_batch(3, figsize=(9,6))
```
## Train model
```
learn = create_cnn(data, models.resnet34)
learn.lr_find()
learn.recorder.plot()
lr = 2e-2
learn.fit_one_cycle(5, slice(lr))
learn.save('stage-1')
learn.load('stage-1');
learn.show_results()
```
## Data augmentation
```
tfms = get_transforms(max_rotate=20, max_zoom=1.5, max_lighting=0.5, max_warp=0.4, p_affine=1., p_lighting=1.)
data = (ImageItemList.from_folder(path)
.split_by_valid_func(lambda o: o.parent.name=='13')
.label_from_func(get_ctr, label_cls=PointsItemList)
.transform(tfms, tfm_y=True, size=(120,160), padding_mode='zeros')
.databunch().normalize(imagenet_stats)
)
def _plot(i,j,ax):
x,y = data.train_ds[0]
x.show(ax, y=y)
plot_multi(_plot, 3, 3, figsize=(8,6))
```
| github_jupyter |
# 4. Quantum computation
Quantum computation is a new way of doing computation which differs from the classical way. Classical computations can be implemented in several ways, the most successful one today is the circuit model of computation. This is how elements in modern computers are designed. In the circuit model, a computation is made by taking a string of bits as inputs, doing certain operations on them and giving a new string of bits as output. In the current paradigm, these operations are logical operations that follow Boole's logic. It was proved that one needs to be able to carry out a limited set of operation (namely "NOT gate", and "AND gate") in order to implement any operation (addition, multiplication, division, ... ) by a combination of operation from this set. This fundamental set of gates is called an "elementary set of gates" and is all that is required to be able to do any computation. Similarly to classical computation, quantum computation can be done using the circuit model of computation. In this case, bits are replaced by qubits and logic gates must be substituted with quantum gates which can operate on qubits while keeping intact their special quantum properties. Quantum circuits must be reversible due to the reversibility inherent in the laws of quantum mechanics.
A reversible circuit allows you to run the computation backwards and retrieve the inputs given the outputs. Classical computation can also be implemented using reversible gates but there are disadvantages with regards to the circuit size and complexity. Thus, modern computer are built with "irreversible" logic (which means it's impossible to run the computation backwards, see truth table of the "AND" gate for example) and this is the reason why the generate heat! In order to have reversible quantum gates, one must implement these gates using, what is called a "unitary operation", that is an operation which preserve the sum of the probabilities of seeing each of the measurable values of the qubits. Although, the probability of seeing any single outcome can change, their sum will always add up to one.
## 4.1 The qubit
In quantum computation the objects of the computation are quantum objects called qubits. Similarly to bits, when qubits are measured they can only take two values: $\lvert 0 \rangle$, $\lvert 1 \rangle $.
Where the brackets around the number points to the fact that these are quantum objects (see Dirac's notation).
In linear algebra representation, the state of a qubit is a vector in a two-dimensional Hilbert space. One of the possible basis for this space is the so-called computational basis which is formed by the eigenvector of the Pauli Z matrix (more details below), the $\lvert 0 \rangle$ and $\lvert 1 \rangle $ states. In matrix form, they can be written as
$$
\lvert 0 \rangle =
\begin{pmatrix}
1 \\
0
\end{pmatrix}
$$
$$
\lvert 1 \rangle =
\begin{pmatrix}
0 \\
1
\end{pmatrix}
$$
A generic vector $\lvert \psi \rangle $ in the Hilbert space can then be constructed as a linear combination of the basis vectors
$$
\lvert \psi \rangle = \alpha \lvert 0 \rangle + \beta \lvert 1 \rangle =
\begin{pmatrix}
\alpha \\
\beta
\end{pmatrix}
$$
where $\alpha$ and $\beta$ are two complex numbers.
### Superposition
Differently from the regular bits stored in a computer, which can either take the value of $"0"$ or $"1"$, during a computation qubits can be in a state $\lvert \psi \rangle$ which is a superposition of $\lvert 0 \rangle$ and $\lvert 1 \rangle$:
\begin{equation}
\lvert \psi \rangle = \alpha \lvert 0 \rangle + \beta \lvert 1 \rangle ,
\end{equation}
where $\alpha$ and $\beta$ are related to the probability of obtaining the corresponding outcome $\lvert 0 \rangle$ or $\lvert 1 \rangle$ when the qubit is measured to learn its value.
\begin{eqnarray}
\text{P}(\text{qubit state} = 0) = \lvert \alpha \rvert^{2} \\ \notag
\text{P}(\text{qubit state} = 1) = \lvert \beta \rvert^{2}
\end{eqnarray}
Which means that the value of the qubit is not determined until it is measured. This is a counter-intuitive property of quantum mechanical objects. A qubit in a superposition of different states will behave as if it possess properties of all the states in the superposition. However, when measured, the qubit will be in one of the states of the superposition, with a probability given by the modulo square of the coefficient of the corresponding state.
### Multi-qubit state
In quantum computation, one is generally interested in doing operations on a qubit register which contains a collection of qubits. To denote the state of an $n$ qubit register, one of the following equivalent notations is used:
\begin{equation}
\lvert 0 \rangle_1 \otimes \lvert 1 \rangle_2 \otimes ... \otimes \lvert 0 \rangle_n \equiv \lvert 0, 1, ..., 0 \rangle \equiv \lvert 01...0 \rangle
\end{equation}
Where each of the zeros or ones correspond to the state of one of the qubit in the register and the index counts the qubit's number. The linear algebra meaning of all these notations (although less and less explicit going from left to right) is that the Hilbert space containing the state of the multi-qubit system is a tensor product $\otimes$ of the Hilbert spaces of the single qubits and the state of the system is a Dirac ket vector in this tensor product space. That is, the state of the system is a tensor product of the state of the single qubits. So, if the Hilbert space of one qubit has dimension $2$, the Hilbert space of an $n$-qubit register has dimension $2^n$
As an example, let us consider the case of $n=2$ qubits. The matrix form of the basis of the 4-dimensional Hilbert space is given by the tensor product of the basis vectors of each of the single qubit spaces.
From the definition of tensor product between vectors given in Chapter 2, we have
$$
\lvert 00 \rangle =
\begin{pmatrix}
1 \\
0
\end{pmatrix} \otimes
\begin{pmatrix}
1 \\
0
\end{pmatrix} =
\begin{pmatrix}
1 \cdot 1 \\
1 \cdot 0 \\
0 \cdot 1 \\
0 \cdot 0
\end{pmatrix} =
\begin{pmatrix}
1 \\
0 \\
0 \\
0
\end{pmatrix}
$$
$$
\lvert 01 \rangle =
\begin{pmatrix}
1 \\
0
\end{pmatrix} \otimes
\begin{pmatrix}
0 \\
1
\end{pmatrix} =
\begin{pmatrix}
1 \cdot 0 \\
1 \cdot 1 \\
0 \cdot 0 \\
0 \cdot 1
\end{pmatrix} =
\begin{pmatrix}
0 \\
1 \\
0 \\
0
\end{pmatrix}
$$
$$
\lvert 10 \rangle =
\begin{pmatrix}
0 \\
1
\end{pmatrix} \otimes
\begin{pmatrix}
1 \\
0
\end{pmatrix} =
\begin{pmatrix}
0 \cdot 1 \\
0 \cdot 0 \\
1 \cdot 1 \\
1 \cdot 0
\end{pmatrix} =
\begin{pmatrix}
0 \\
0 \\
1 \\
0
\end{pmatrix}
$$
$$
\lvert 11 \rangle =
\begin{pmatrix}
0 \\
1
\end{pmatrix} \otimes
\begin{pmatrix}
0 \\
1
\end{pmatrix} =
\begin{pmatrix}
0 \cdot 0 \\
0 \cdot 1 \\
1 \cdot 0 \\
1 \cdot 1
\end{pmatrix} =
\begin{pmatrix}
0 \\
0 \\
0 \\
1
\end{pmatrix}
$$
The extension to $n$ qubits is then straightforward, although tedious.
### Entanglement
Another interesting property of qubits, which departs from the classical world, is that they can be entangled. If qubits are entangled with each other, the value taken by each of them is strictly related to the value taken by the other. The correlations between the values of entangled qubits is so strong that it cannot be described by classical probability theory. This is one of the most peculiar features of quantum mechanics.
In a way, entangled qubits lose their identity as individual objects, as their properties now depend on the properties of the other qubits with which they are entangled. It's not possible to separate an entangled system in independent parts and it must be treated as a new unit (in quantum mechanical terms, the state of the whole system is not separable, it cannot be factorized as product state of the state of individual systems).
To see the difference between an entangled state and a non-entangle state, consider the following two possibilities for a two-qubit state:
<ol>
<li> $\frac{1}{\sqrt{2}} \left( \lvert 0 \rangle_1 \otimes \lvert 0 \rangle_2 \right) + \frac{1}{\sqrt{2}} \left( \lvert 0 \rangle_1 \otimes \lvert 1 \rangle_2 \right) $ </li>
<li> $\frac{1}{2} \left( \lvert 0 \rangle_1 \otimes \lvert 0 \rangle_2 \right) + \frac{1}{2} \left( \lvert 1 \rangle_1 \otimes \lvert 1 \rangle_2 \right)$ </li>
</ol>
The state shown in 1. can be manipulated so that it will look like the tensor product of the state of the first qubit and the state of the second qubit. In fact, we can rewrite 1. as: $ \lvert 0 \rangle_1 \otimes \frac{1}{\sqrt{2}} \left( \lvert 0 \rangle_2 + \lvert 1 \rangle_2 \right) $. Thus, we can say that the first qubit is in the state $0$ and the second qubit is in an equal superposition of $0$ and $1$.
The same procedure cannot be done on the two-qubit state shown in 2. which cannot be manipulated so that the two-qubit state looks like a tensor product of the state of the first qubit and the state of the second qubit. Therefore, one cannot say anything about the state of a single qubit in state 2. but one has always to talk about the joint state of the two qubits. If one of them has value $0$ the other one will have value $0$ as well, and if one qubit has value $1$, the other qubit will have value $1$ too. This purely quantum correlation between the states of a system is what is called quantum entanglement.
## 4.2 Quantum gates
Quantum gates implement operations on qubits by keeping intact their quantum properties. They correspond to operators acting on the qubit register. Furthermore, they allow some of those properties to arise, for example by putting qubits in a superposition of states or entangling them with each other.
It was shown that, similarly to the classical case, it is only really necessary to be able to perform a finite set of quantum gates on the qubits to implement any possible operation on them by combining these particular quantum gates. The minimum set of quantum gates needed for computation is then called a "universal set of quantum gates".
Let's see some quantum gates:
### 4.2.1 One-qubit gates
These gates act on one of the qubits in the qubit register, leaving all other qubits unaffected.
#### Identity gate
The identity gate I leaves the state of a qubit unchanged. In matrix form this is just the identity matrix in a two-dimensional vector space
<img src="figures/4/I1.jpeg" width="150">
$$\text{1. Identity gate.}$$
$$
\hat{I} =
\begin{pmatrix}
1 & 0\\
0 & 1
\end{pmatrix}
$$
and its action on the state of a qubit is
$$
\hat{I} \lvert 0 \rangle =
\begin{pmatrix}
1 & 0\\
0 & 1
\end{pmatrix}
\begin{pmatrix}
1 \\
0
\end{pmatrix} =
\begin{pmatrix}
1 \\
0
\end{pmatrix} = \lvert 0 \rangle
$$
$$
\hat{I} \lvert 1 \rangle =
\begin{pmatrix}
1 & 0\\
0 & 1
\end{pmatrix}
\begin{pmatrix}
0 \\
1
\end{pmatrix} =
\begin{pmatrix}
0 \\
1
\end{pmatrix} = \lvert 1 \rangle
$$
#### Pauli X gate
The X gate flips the state of a qubit from $\lvert 0 \rangle \rightarrow \lvert 1 \rangle $ and $\lvert 1 \rangle \rightarrow \lvert 0 \rangle $. It is the quantum analog of the NOT gate and it is sometimes referred to as the "bit-flip gate". When considering the Bloch sphere representation of a qubit, the X gate correspond to a $\pi$ rotation around the y-axis.
<img src="figures/4/X1.jpeg" width="150">
$$\text{2. X gate.}$$
In matrix representation, the X gate is
$$
\hat{X} =
\begin{pmatrix}
0 & 1\\
1 & 0
\end{pmatrix}
$$
Its action on a qubit is
$$
\hat{X} \lvert 0 \rangle =
\begin{pmatrix}
0 & 1\\
1 & 0
\end{pmatrix}
\begin{pmatrix}
1 \\
0
\end{pmatrix} =
\begin{pmatrix}
0 \\
1
\end{pmatrix} = \lvert 1 \rangle
$$
$$
\hat{X} \lvert 1 \rangle =
\begin{pmatrix}
0 & 1\\
1 & 0
\end{pmatrix}
\begin{pmatrix}
0 \\
1
\end{pmatrix} =
\begin{pmatrix}
1 \\
0
\end{pmatrix} = \lvert 0 \rangle
$$
#### Pauli Z gate
The Z gate flips the phase of a qubit if it is in the $\lvert 1 \rangle$ state. This correspond to a $\pi$ rotation around the z-axis.
<img src="figures/4/Z1.jpeg" width="150">
$$\text{3. Z gate.}$$
In matrix representation, the Z gate is
$$
\hat{Z} =
\begin{pmatrix}
1 & 0\\
0 & -1
\end{pmatrix}
$$
The effect on the state of a qubit is
$$
\hat{Z} \lvert 0 \rangle =
\begin{pmatrix}
1 & 0\\
0 & -1
\end{pmatrix}
\begin{pmatrix}
1 \\
0
\end{pmatrix} =
\begin{pmatrix}
1 \\
0
\end{pmatrix} = \lvert 0 \rangle
$$
$$
\hat{Z} \lvert 1 \rangle =
\begin{pmatrix}
1 & 0\\
0 & -1
\end{pmatrix}
\begin{pmatrix}
0 \\
1
\end{pmatrix} =
\begin{pmatrix}
0 \\
-1
\end{pmatrix} = - \lvert 1 \rangle
$$
#### Pauli Y gate
The Y gate flips the state of a qubit and its phase and is sometimes called the " bit- and phase-flip gate".
<img src="figures/4/Y1.jpeg" width="150">
$$\text{4. Y gate.}$$
The definition of the Y gate in matrix form is
$$
\hat{Y} =
\begin{pmatrix}
0 & -i\\
i & 0
\end{pmatrix}
$$
The effect of the Y gate on the state of a qubit is
$$
\hat{Y} \lvert 0 \rangle =
\begin{pmatrix}
0 & -i\\
i & 0
\end{pmatrix}
\begin{pmatrix}
1 \\
0
\end{pmatrix} =
\begin{pmatrix}
0 \\
i
\end{pmatrix} = i \lvert 1 \rangle
$$
$$
\hat{Y} \lvert 1 \rangle =
\begin{pmatrix}
0 & -i\\
i & 0
\end{pmatrix}
\begin{pmatrix}
0 \\
1
\end{pmatrix} =
\begin{pmatrix}
-i \\
0
\end{pmatrix} = -i \lvert 0 \rangle
$$
As the name of the Y gate suggest, the Y gate itself is not an independent gate but it is the combination of the X and Z gate. In particular, let us consider
$$
i\hat{X}\hat{Z} =
i \begin{pmatrix}
0 & 1\\
1 & 0
\end{pmatrix}
\begin{pmatrix}
1 & 0\\
0 & -1
\end{pmatrix} =
i \begin{pmatrix}
0 & -1\\
1 & 0
\end{pmatrix} =
\begin{pmatrix}
0 & -i\\
i & 0
\end{pmatrix} = Y
$$
#### Hadamard gate
The Hadamard gate H puts a qubit in an equal superposition of $\lvert 0 \rangle$ and $\lvert 1 \rangle$.
<img src="figures/4/H1.jpeg" width="150">
$$\text{5. Hadamard gate.}$$
Its matrix representation is
$$
\hat{H} =
\frac{1}{\sqrt{2}}
\begin{pmatrix}
1 & 1\\
1 & -1
\end{pmatrix}
$$
Acting with the Hadamard gate on a qubit gives
$$
\hat{H} \lvert 0 \rangle =
\frac{1}{\sqrt{2}}
\begin{pmatrix}
1 & 1\\
1 & -1
\end{pmatrix}
\begin{pmatrix}
1 \\
0
\end{pmatrix} =
\frac{1}{\sqrt{2}} \begin{pmatrix}
1 \\
1
\end{pmatrix} = \frac{1}{\sqrt{2}} \left( \lvert 0 \rangle + \lvert 1 \rangle \right)
$$
$$
\hat{H} \lvert 1 \rangle =
\frac{1}{\sqrt{2}}
\begin{pmatrix}
1 & 1\\
1 & -1
\end{pmatrix}
\begin{pmatrix}
0 \\
1
\end{pmatrix} =
\frac{1}{\sqrt{2}} \begin{pmatrix}
1 \\
-1
\end{pmatrix} = \frac{1}{\sqrt{2}} \left( \lvert 0 \rangle - \lvert 1 \rangle \right)
$$
#### Rotations
Rotations around an axis ($R_x, R_y, R_z$): Rotates qubit state $\lvert \psi \rangle = \alpha \lvert 0 \rangle + \beta \lvert 1 \rangle $, by changing the coefficients $\alpha, \beta$ in a way that depends on the angle of rotation.
<img src="figures/4/R1.jpeg" width="300">
$$\text{6. Rotation gate around the $x$, $y$ and $z$ axis.}$$
In matrix form
$$
\hat{R}_x(\theta) =
\begin{pmatrix}
\cos(\theta/2) & -i\sin(\theta/2)\\
-i\sin(\theta/2) & \cos(\theta/2)
\end{pmatrix}
$$
$$
\hat{R}_y(\theta) =
\begin{pmatrix}
\cos(\theta/2) & \sin(\theta/2)\\
\sin(\theta/2) & \cos(\theta/2)
\end{pmatrix}
$$
$$
\hat{R}_z(\theta) =
\begin{pmatrix}
1 & 0 \\
0 & e^{i \theta}
\end{pmatrix}
$$
Their action is
$$ \hat{R}_x(\theta) \lvert \psi \rangle =
\begin{pmatrix}
\cos(\theta/2) & -i\sin(\theta/2)\\
-i\sin(\theta/2) & \cos(\theta/2)
\end{pmatrix}
\begin{pmatrix}
\alpha \\
\beta
\end{pmatrix} =
\begin{pmatrix}
\cos(\theta/2) \alpha -i\sin(\theta/2) \beta\\
-i\sin(\theta/2) \alpha + \cos(\theta/2) \beta
\end{pmatrix} = \left( \cos(\theta/2) \alpha -i\sin(\theta/2) \right) \lvert 0 \rangle + \left( -i\sin(\theta/2) \alpha + \cos(\theta/2) \beta \right) \lvert 1 \rangle$$
$$ \hat{R}_y(\theta) \lvert \psi \rangle =
\begin{pmatrix}
\cos(\theta/2) & \sin(\theta/2)\\
\sin(\theta/2) & \cos(\theta/2)
\end{pmatrix}
\begin{pmatrix}
\alpha \\
\beta
\end{pmatrix} =
\begin{pmatrix}
\cos(\theta/2) \alpha + \sin(\theta/2) \beta\\
\sin(\theta/2) \alpha + \cos(\theta/2) \beta
\end{pmatrix} = \left( \cos(\theta/2) \alpha + \sin(\theta/2) \right) \lvert 0 \rangle + \left( \sin(\theta/2) \alpha + \cos(\theta/2) \beta \right) \lvert 1 \rangle$$
$$ \hat{R}_z(\theta) \lvert \psi \rangle =
\begin{pmatrix}
1 & 0 \\
0 & e^{i \theta}
\end{pmatrix}
\begin{pmatrix}
\alpha \\
\beta
\end{pmatrix} =
\begin{pmatrix}
\alpha \\
e^{i \theta} \beta
\end{pmatrix} = \alpha \lvert 0 \rangle + e^{i \theta} \beta \lvert 1 \rangle $$
### 4.2.2 Multi-qubit gates
<img src="figures/4/multi_qubit1.jpeg" width="150">
$$\text{7. Two single-qubit gates. $X$ on the first qubit and $I$ on the second qubit.}$$
If we are dealing with a qubit register that contains more than a single qubit, the operators on the whole register can be obtained by taking the tensor product of the operators acting on each qubit. To avoid lengthy calculations, we work out a few examples for a two-qubit register. We have shown above the form of the basis vector of a two-qubit register.
As an example, consider the matrix representation of the X gate on the first qubit is
$$
\hat{X} \otimes \hat{I} =
\begin{pmatrix}
0 & 1 \\
1 & 0
\end{pmatrix} \otimes
\begin{pmatrix}
1 & 0 \\
0 & 1
\end{pmatrix} =
\begin{pmatrix}
0 \cdot 1 & 0 \cdot 0 & 1 \cdot 1 & 1 \cdot 0 \\
0 \cdot 0 & 0 \cdot 1 & 1 \cdot 0 & 1 \cdot 1 \\
1 \cdot 1 & 1 \cdot 0 & 0 \cdot 1 & 0 \cdot 0 \\
1 \cdot 0 & 1 \cdot 1 & 0 \cdot 0 & 0 \cdot 1
\end{pmatrix} =
\begin{pmatrix}
0 & 0 & 1 & 0\\
0 & 0 & 0 & 1\\
1 & 0 & 0 & 0\\
0 & 1 & 0 & 0
\end{pmatrix}
$$
The action of this operator on a two-qubit register will be
$$
\left( \hat{X} \otimes \hat{I} \right) \lvert 00 \rangle =
\begin{pmatrix}
0 & 0 & 1 & 0\\
0 & 0 & 0 & 1\\
1 & 0 & 0 & 0\\
0 & 1 & 0 & 0
\end{pmatrix}
\begin{pmatrix}
1 \\
0\\
0\\
0
\end{pmatrix} =
\begin{pmatrix}
0 \\
0\\
1\\
0
\end{pmatrix} =
\lvert 10 \rangle
$$
Exactly as expected. If we now want to combine different type of single qubit gates, acting on the two-qubit register, we only need to calculate the tensor product between these operators to find what is their matrix representation.
### 4.2.3 Two-qubit gates
#### Control-NOT gate
The most reknown two-qubit gate is the control-not gate or CNOT (CX) gate. The CX gate flips the state of a qubit (called $target$) conditionally on the state of another qubit (called $control$).
<img src="figures/4/CX1.jpeg" width="150">
$$\text{8. CNOT gate. The first qubit is the control and the second is the target.}$$
The matrix representation of the CX gate is the following
$$
\hat{C}X_{12} =
\begin{pmatrix}
1 & 0 & 0 & 0\\
0 & 1 & 0 & 0\\
0 & 0 & 0 & 1\\
0 & 0 & 1 & 0
\end{pmatrix}
$$
Let us see the effect of acting with the CX gate on a two-qubit register. In the matrix form shown above, the first qubit will be the control qubit and the second qubit will be the target qubit.
If the control qubit is in the state $\lvert 0 \rangle$, nothing is done to the target qubit. If the control qubit is in state $\lvert 1 \rangle$, the X gate (bit-flip) is applied to the target qubit.
$$
\hat{C}X_{12} \lvert 00 \rangle =
\begin{pmatrix}
1 & 0 & 0 & 0\\
0 & 1 & 0 & 0\\
0 & 0 & 0 & 1\\
0 & 0 & 1 & 0
\end{pmatrix}
\begin{pmatrix}
1 \\
0 \\
0 \\
0
\end{pmatrix} =
\begin{pmatrix}
1 \\
0 \\
0 \\
0
\end{pmatrix} = \lvert 00 \rangle
$$
$$
\hat{C}X_{12} \lvert 01 \rangle =
\begin{pmatrix}
1 & 0 & 0 & 0\\
0 & 1 & 0 & 0\\
0 & 0 & 0 & 1\\
0 & 0 & 1 & 0
\end{pmatrix}
\begin{pmatrix}
0 \\
1 \\
0 \\
0
\end{pmatrix} =
\begin{pmatrix}
0 \\
1 \\
0 \\
0
\end{pmatrix} = \lvert 01 \rangle
$$
$$
\hat{C}X_{12} \lvert 10 \rangle =
\begin{pmatrix}
1 & 0 & 0 & 0\\
0 & 1 & 0 & 0\\
0 & 0 & 0 & 1\\
0 & 0 & 1 & 0
\end{pmatrix}
\begin{pmatrix}
0 \\
0 \\
1 \\
0
\end{pmatrix} =
\begin{pmatrix}
0 \\
0 \\
0 \\
1
\end{pmatrix} = \lvert 11 \rangle
$$
$$
\hat{C}X_{12} \lvert 11 \rangle =
\begin{pmatrix}
1 & 0 & 0 & 0\\
0 & 1 & 0 & 0\\
0 & 0 & 0 & 1\\
0 & 0 & 1 & 0
\end{pmatrix}
\begin{pmatrix}
0 \\
0 \\
0 \\
1
\end{pmatrix} =
\begin{pmatrix}
0 \\
0 \\
1 \\
0
\end{pmatrix} = \lvert 10 \rangle
$$
There is also another way to write the action of the CNOT gate in Dirac's notation:
$$\hat{C}X_{12} \lvert x, y \rangle = \lvert x, x \oplus y \rangle $$
where $x,y= \{ 0,1 \}$. So that:
$$\hat{C}X_{12} \lvert 0, 0 \rangle = \lvert 0, 0 \oplus 0 \rangle = \lvert 0, 0 \rangle $$
$$\hat{C}X_{12} \lvert 0, 1 \rangle = \lvert 0, 1 \oplus 0 \rangle = \lvert 0, 1 \rangle $$
$$\hat{C}X_{12} \lvert 1, 0 \rangle = \lvert 0, 0 \oplus 1 \rangle = \lvert 1, 1 \rangle$$
$$\hat{C}X_{12} \lvert 1, 1 \rangle = \lvert 1, 1 \oplus 1 \rangle = \lvert 1, 0 \rangle $$
## Exercises
<ol>
<li>
Consider the generic state of a qubit $\lvert \psi \rangle = \alpha \lvert 0 \rangle + \beta \lvert 1 \rangle $. Give the values of $\alpha$ and $\beta$ (normalized to $\lvert \alpha \rvert^2 + \lvert \beta \rvert^2 = 1$) to represent the following ket-vectors
<ol>
<li>
$ \lvert 0 \rangle $
</li>
<li>
$ \lvert 1 \rangle $
</li>
<li>
equal superposition of $\lvert 0 \rangle $ and $\lvert 1 \rangle$
</li>
</ol>
</li>
<li>
Find the basis for the Hilbert space of three qubits (it has dimension 8) using the tensor product of the computational basis of the Hilbert space of a qubit.
</li>
<li>
Given a qubit in the state $\lvert \psi \rangle = \frac{\sqrt{2}}{\sqrt{6}} \lvert 0 \rangle + \frac{\sqrt{4}}{\sqrt{6}} \lvert 1 \rangle$, Calculate:
<ol>
<li>
$ \hat{X} \lvert \psi \rangle $
</li>
<li>
$\hat{Z} \lvert \psi \rangle$
</li>
<li>
$\hat{X} \lvert \psi \rangle$
</li>
<li>
$\hat{Y} \lvert \psi \rangle$
</li>
<li>
$\hat{H} \lvert \psi \rangle$
</li>
</ol>
</li>
<li>
Calculate the following multi-qubit operators in matrix form
<ol>
<li>
$ X \otimes X $
</li>
<li>
$ H \otimes H $
</li>
<li>
$ H \otimes Z $
</li>
</ol>
</li>
<li>
Given a qubit in the state $\lvert \psi \rangle = \frac{\sqrt{2}}{\sqrt{6}} \lvert 00 \rangle + \frac{\sqrt{2}}{\sqrt{6}} \lvert 01 \rangle + \frac{\sqrt{i}}{\sqrt{6}} \lvert 10 \rangle + \frac{\sqrt{1}}{\sqrt{6}} \lvert 11 \rangle$, Calculate $\hat{C}X_{12} \lvert \psi \rangle$, where the first qubit is the control qubit and the second qubit is the target qubit.
</li>
</ol>
## References
[1] R. Feynman, Simulating Physics with Computers, International Journal of Theoretical
Physics, Vol. 21, nos. 6/7, pp. 467{488 (1982).
[2] M. A. Nielsen, and I. L. Chuang, 2000, Quantum Computation
and Quantum Information (Cambridge University Press, Cambridge).
[3] A. Barenco et al., Phys. Rev. A 52, 3457 (1995).
| github_jupyter |
# Links, joints and sensors
## Links
A physical link in the simulation contains inertia, collision and visual properties. A link must be a child of a model and a model can have multiple links.
```
# Import the element creator
from pcg_gazebo.parsers.sdf import create_sdf_element
# The link is empty by default
link = create_sdf_element('link')
print(link)
# Let's create the elements dynamically at first
link = create_sdf_element('link')
# The link's name must be unique in a model
link.name = 'base_link'
print(link)
# Mass of the link in kg
link.mass = 30
# The center of mass are the cartesian coordinates in link.inertial.pose
link.center_of_mass = [0, 10, 0]
# The moments of inertia describe the elements of the 3x3 rotational inertial matrix
link.inertia.ixx = 0.5
link.inertia.iyy = 0.5
link.inertia.izz = 0.5
print(link)
# If gravity is set as true, the link will be affected by gravity
link.gravity = True
print(link)
# If kinematic is set to true, the link is kinematic only
link.kinematic = False
print(link)
# The pose of the link with respect to a frame
link.pose = [0, 0, 1, 0, 0, 0]
print(link)
# As mentioned in previous notebooks, a link can have multiple visual and collision elements
# To create an empty collision geometry, use the function add_collision as follows
link.add_collision(name='collision_1')
print(link.collisions[0])
# Set the geometry of the collision
link.collisions[0].box = create_sdf_element('box')
print(link)
# You can also add a collision geometry by creating a collision entity and
# adding it to the link as follows
collision = create_sdf_element('collision')
collision.reset(with_optional_elements=True)
collision.geometry.cylinder = create_sdf_element('cylinder')
link.add_collision('collision_2', collision)
print(link)
# You can't add collision or visual elements with duplicated names
# You can also add a collision geometry by creating a collision entity and
# adding it to the link as follows
collision = create_sdf_element('collision')
collision.reset(with_optional_elements=True)
collision.geometry.box = create_sdf_element('box')
link.add_collision('collision_2', collision)
print(link)
link.add_collision('collision_3', collision)
print(link)
# You can retrieve the collision geometry by its name
# If the name given is not found, the function will return None
print(link.get_collision_by_name('collision_1'))
print(link.get_collision_by_name('collision_10'))
# Or iterate in the collisions list
for elem in link.collisions:
print(elem)
# The same is true for visual elements, create an empty visual element by using add_visual
link.add_visual('visual_1')
print(link)
# Set the geometry of the visual element
link.visuals[0].geometry.plane = create_sdf_element('plane')
print(link)
# You can also add a collision geometry by creating a collision entity and
# adding it to the link as follows
visual = create_sdf_element('visual')
visual.reset(with_optional_elements=True)
visual.geometry.cylinder = create_sdf_element('cylinder')
link.add_visual('visual_2', visual)
print(link)
# You can retrieve the visual geometry by its name
# If the name given is not found, the function will return None
print(link.get_visual_by_name('visual_1'))
print(link.get_visual_by_name('visual_10'))
# Or iterate in the visuals list
for elem in link.visuals:
print(elem)
```
## Joints
```
# The joint is empty by default
joint = create_sdf_element('joint')
print(joint)
```
## Sensors
```
sensor = create_sdf_element('sensor')
print(sensor)
print(sensor.get_modes())
sensor.reset(mode='altimeter', with_optional_elements=True)
print(sensor)
sensor.reset(mode='camera', with_optional_elements=True)
print(sensor)
sensor.reset(mode='force_torque', with_optional_elements=True)
print(sensor)
```
| github_jupyter |
```
activations = [nn.ELU(),nn.LeakyReLU(),nn.PReLU(),nn.ReLU(),nn.ReLU6(),nn.RReLU(),nn.SELU(),nn.CELU(),nn.GELU(),nn.SiLU(),nn.Tanh()]
for activation in activations:
wandb.init(project=PROJECT_NAME,name=f'activation-{activation}')
model = Test_Model(conv1_output=32,conv2_output=8,conv3_output=64,fc1_output=512,fc3_output=256,fc2_output=512,activation=activation).to(device)
optimizer = optim.SGD(model.parameters(),lr=0.1)
criterion = nn.CrossEntropyLoss()
for _ in tqdm(range(EPOCHS)):
for i in range(0,len(X_train),BATCH_SIZE):
X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device)
y_batch = y_train[i:i+BATCH_SIZE].to(device)
model.to(device)
preds = model(X_batch.float())
preds.to(device)
loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long))
optimizer.zero_grad()
loss.backward()
optimizer.step()
wandb.log({'loss':get_loss(criterion,y_train,model,X_train),'accuracy':test(model,X_train,y_train),'val_accuracy':test(model,X_test,y_test),'val_loss':get_loss(criterion,y_test,model,X_test)})
for index in range(10):
print(torch.argmax(preds[index]))
print(y_batch[index])
print('\n')
wandb.finish()
test_index = 0
from load_data import *
# load_data()
from load_data import *
X_train,X_test,y_train,y_test = load_data()
len(X_train),len(y_train)
len(X_test),len(y_test)
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
class Test_Model(nn.Module):
def __init__(self) -> None:
super().__init__()
self.c1 = nn.Conv2d(1,64,5)
self.c2 = nn.Conv2d(64,128,5)
self.c3 = nn.Conv2d(128,256,5)
self.fc4 = nn.Linear(256*10*10,256)
self.fc6 = nn.Linear(256,128)
self.fc5 = nn.Linear(128,4)
def forward(self,X):
preds = F.max_pool2d(F.relu(self.c1(X)),(2,2))
preds = F.max_pool2d(F.relu(self.c2(preds)),(2,2))
preds = F.max_pool2d(F.relu(self.c3(preds)),(2,2))
# print(preds.shape)
preds = preds.view(-1,256*10*10)
preds = F.relu(self.fc4(preds))
preds = F.relu(self.fc6(preds))
preds = self.fc5(preds)
return preds
device = torch.device('cuda')
BATCH_SIZE = 32
IMG_SIZE = 112
model = Test_Model().to(device)
optimizer = optim.SGD(model.parameters(),lr=0.1)
criterion = nn.CrossEntropyLoss()
EPOCHS = 125
from tqdm import tqdm
PROJECT_NAME = 'Weather-Clf'
import wandb
# test_index += 1
# wandb.init(project=PROJECT_NAME,name=f'test')
# for _ in tqdm(range(EPOCHS)):
# for i in range(0,len(X_train),BATCH_SIZE):
# X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device)
# y_batch = y_train[i:i+BATCH_SIZE].to(device)
# model.to(device)
# preds = model(X_batch.float())
# preds.to(device)
# loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long))
# optimizer.zero_grad()
# loss.backward()
# optimizer.step()
# wandb.log({'loss':loss.item()})
# wandb.finish()
# for index in range(10):
# print(torch.argmax(preds[index]))
# print(y_batch[index])
# print('\n')
class Test_Model(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1,16,5)
self.conv2 = nn.Conv2d(16,32,5)
self.conv3 = nn.Conv2d(32,64,5)
self.fc1 = nn.Linear(64*10*10,16)
self.fc2 = nn.Linear(16,32)
self.fc3 = nn.Linear(32,64)
self.fc4 = nn.Linear(64,32)
self.fc5 = nn.Linear(32,6)
def forward(self,X):
preds = F.max_pool2d(F.relu(self.conv1(X)),(2,2))
preds = F.max_pool2d(F.relu(self.conv2(preds)),(2,2))
preds = F.max_pool2d(F.relu(self.conv3(preds)),(2,2))
# print(preds.shape)
preds = preds.view(-1,64*10*10)
preds = F.relu(self.fc1(preds))
preds = F.relu(self.fc2(preds))
preds = F.relu(self.fc3(preds))
preds = F.relu(self.fc4(preds))
preds = F.relu(self.fc5(preds))
return preds
model = Test_Model().to(device)
optimizer = optim.SGD(model.parameters(),lr=0.1)
criterion = nn.CrossEntropyLoss()
# test_index += 1
# wandb.init(project=PROJECT_NAME,name=f'test-{test_index}')
# for _ in tqdm(range(EPOCHS)):
# for i in range(0,len(X_train),BATCH_SIZE):
# X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device)
# y_batch = y_train[i:i+BATCH_SIZE].to(device)
# model.to(device)
# preds = model(X_batch.float())
# preds.to(device)
# loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long))
# optimizer.zero_grad()
# loss.backward()
# optimizer.step()
# wandb.log({'loss':loss.item()})
# wandb.finish()
class Test_Model(nn.Module):
def __init__(self,conv1_output=16,conv2_output=32,conv3_output=64,fc1_output=16,fc2_output=32,fc3_output=64,activation=F.relu):
super().__init__()
self.conv3_output = conv3_output
self.conv1 = nn.Conv2d(1,conv1_output,5)
self.conv2 = nn.Conv2d(conv1_output,conv2_output,5)
self.conv3 = nn.Conv2d(conv2_output,conv3_output,5)
self.fc1 = nn.Linear(conv3_output*10*10,fc1_output)
self.fc2 = nn.Linear(fc1_output,fc2_output)
self.fc3 = nn.Linear(fc2_output,fc3_output)
self.fc4 = nn.Linear(fc3_output,fc2_output)
self.fc5 = nn.Linear(fc2_output,6)
self.activation = activation
def forward(self,X):
preds = F.max_pool2d(self.activation(self.conv1(X)),(2,2))
preds = F.max_pool2d(self.activation(self.conv2(preds)),(2,2))
preds = F.max_pool2d(self.activation(self.conv3(preds)),(2,2))
# print(preds.shape)
preds = preds.view(-1,self.conv3_output*10*10)
preds = self.activation(self.fc1(preds))
preds = self.activation(self.fc2(preds))
preds = self.activation(self.fc3(preds))
preds = self.activation(self.fc4(preds))
preds = self.activation(self.fc5(preds))
return preds
# conv1_output = 32
# conv2_output = 8
# conv3_output = 64
# fc1_output = 512
# fc2_output = 512
# fc3_output = 256
# activation
# optimizer
# loss
# lr
# num of epochs
def get_loss(criterion,y,model,X):
model.to('cpu')
preds = model(X.view(-1,1,112,112).to('cpu').float())
preds.to('cpu')
loss = criterion(preds,torch.tensor(y,dtype=torch.long).to('cpu'))
loss.backward()
return loss.item()
def test(net,X,y):
device = 'cpu'
net.to(device)
correct = 0
total = 0
net.eval()
with torch.no_grad():
for i in range(len(X)):
real_class = torch.argmax(y[i]).to(device)
net_out = net(X[i].view(-1,1,112,112).to(device).float())
net_out = net_out[0]
predictied_class = torch.argmax(net_out)
if predictied_class == real_class:
correct += 1
total += 1
net.train()
net.to('cuda')
return round(correct/total,3)
EPOCHS = 3
activations = [nn.ELU(),nn.LeakyReLU(),nn.PReLU(),nn.ReLU(),nn.ReLU6(),nn.RReLU(),nn.SELU(),nn.CELU(),nn.GELU(),nn.SiLU(),nn.Tanh()]
for activation in activations:
wandb.init(project=PROJECT_NAME,name=f'activation-{activation}')
model = Test_Model(conv1_output=32,conv2_output=8,conv3_output=64,fc1_output=512,fc3_output=256,fc2_output=512,activation=activation).to(device)
optimizer = optim.SGD(model.parameters(),lr=0.1)
criterion = nn.CrossEntropyLoss()
for _ in tqdm(range(EPOCHS)):
for i in range(0,len(X_train),BATCH_SIZE):
X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device)
y_batch = y_train[i:i+BATCH_SIZE].to(device)
model.to(device)
preds = model(X_batch.float())
preds.to(device)
loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long))
optimizer.zero_grad()
loss.backward()
optimizer.step()
wandb.log({'loss':get_loss(criterion,y_train,model,X_train),'accuracy':test(model,X_train,y_train),'val_accuracy':test(model,X_test,y_test),'val_loss':get_loss(criterion,y_test,model,X_test)})
for index in range(10):
print(torch.argmax(preds[index]))
print(y_batch[index])
print('\n')
wandb.finish()
```
| github_jupyter |
## 探索电影数据集
在这个项目中,你将尝试使用所学的知识,使用 `NumPy`、`Pandas`、`matplotlib`、`seaborn` 库中的函数,来对电影数据集进行探索。
下载数据集:
[TMDb电影数据](https://s3.cn-north-1.amazonaws.com.cn/static-documents/nd101/explore+dataset/tmdb-movies.csv)
数据集各列名称的含义:
<table>
<thead><tr><th>列名称</th><th>id</th><th>imdb_id</th><th>popularity</th><th>budget</th><th>revenue</th><th>original_title</th><th>cast</th><th>homepage</th><th>director</th><th>tagline</th><th>keywords</th><th>overview</th><th>runtime</th><th>genres</th><th>production_companies</th><th>release_date</th><th>vote_count</th><th>vote_average</th><th>release_year</th><th>budget_adj</th><th>revenue_adj</th></tr></thead><tbody>
<tr><td>含义</td><td>编号</td><td>IMDB 编号</td><td>知名度</td><td>预算</td><td>票房</td><td>名称</td><td>主演</td><td>网站</td><td>导演</td><td>宣传词</td><td>关键词</td><td>简介</td><td>时常</td><td>类别</td><td>发行公司</td><td>发行日期</td><td>投票总数</td><td>投票均值</td><td>发行年份</td><td>预算(调整后)</td><td>票房(调整后)</td></tr>
</tbody></table>
**请注意,你需要提交该报告导出的 `.html`、`.ipynb` 以及 `.py` 文件。**
---
---
## 第一节 数据的导入与处理
在这一部分,你需要编写代码,使用 Pandas 读取数据,并进行预处理。
**任务1.1:** 导入库以及数据
1. 载入需要的库 `NumPy`、`Pandas`、`matplotlib`、`seaborn`。
2. 利用 `Pandas` 库,读取 `tmdb-movies.csv` 中的数据,保存为 `movie_data`。
提示:记得使用 notebook 中的魔法指令 `%matplotlib inline`,否则会导致你接下来无法打印出图像。
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
movie_data = pd.read_csv('tmdb-movies.csv')
```
---
**任务1.2: ** 了解数据
你会接触到各种各样的数据表,因此在读取之后,我们有必要通过一些简单的方法,来了解我们数据表是什么样子的。
1. 获取数据表的行列,并打印。
2. 使用 `.head()`、`.tail()`、`.sample()` 方法,观察、了解数据表的情况。
3. 使用 `.dtypes` 属性,来查看各列数据的数据类型。
4. 使用 `isnull()` 配合 `.any()` 等方法,来查看各列是否存在空值。
5. 使用 `.describe()` 方法,看看数据表中数值型的数据是怎么分布的。
```
print('movie data is of {} rows and {} columns'.format(*movie_data.shape))
movie_data.sample()
movie_data.head()
movie_data.tail()
movie_data.dtypes
print('NaNs in data')
movie_data.isnull().any()
movie_data.describe()
```
---
**任务1.3: ** 清理数据
在真实的工作场景中,数据处理往往是最为费时费力的环节。但是幸运的是,我们提供给大家的 tmdb 数据集非常的「干净」,不需要大家做特别多的数据清洗以及处理工作。在这一步中,你的核心的工作主要是对数据表中的空值进行处理。你可以使用 `.fillna()` 来填补空值,当然也可以使用 `.dropna()` 来丢弃数据表中包含空值的某些行或者列。
任务:使用适当的方法来清理空值,并将得到的数据保存。
```
print('missing values of each column')
fields = movie_data.isnull().sum().sort_values(ascending=False)
missing_fields = fields[fields > 0]
base_color = sns.color_palette()[0]
sns.barplot(missing_fields, missing_fields.index.values, color=base_color)
```
从上图可以看出,homepage字段的缺失值最多,其次是tagline,然后是keywords,homepage和imdb_id对后面的分析用处不大,可以直接删掉这两列,其他可能有用的字段缺失值就统一标记为missing吧。
```
# homepage缺失项最多,且对后续分析没什么用处,imdb_id也是,直接drop掉这2列
movie_data_cleaned = movie_data.drop(['imdb_id', 'homepage'], axis=1)
# 缺失的tagline, keywords和production_companies统一标记为'missing'
value = {
'tagline': 'missing',
'keywords': 'missing',
'production_companies': 'missing',
}
movie_data_cleaned.fillna(value=value, inplace=True)
# 剩下占比不多的空值直接drop掉,以免影响后续分析
movie_data_cleaned.dropna(inplace=True)
print('movie data after cleaned in {} rows and {} columns', *movie_data_cleaned.shape)
movie_data_cleaned.isnull().sum()
```
---
---
## 第二节 根据指定要求读取数据
相比 Excel 等数据分析软件,Pandas 的一大特长在于,能够轻松地基于复杂的逻辑选择合适的数据。因此,如何根据指定的要求,从数据表当获取适当的数据,是使用 Pandas 中非常重要的技能,也是本节重点考察大家的内容。
---
**任务2.1: ** 简单读取
1. 读取数据表中名为 `id`、`popularity`、`budget`、`runtime`、`vote_average` 列的数据。
2. 读取数据表中前1~20行以及48、49行的数据。
3. 读取数据表中第50~60行的 `popularity` 那一列的数据。
要求:每一个语句只能用一行代码实现。
```
movie_data_cleaned[['id', 'popularity', 'budget', 'runtime', 'vote_average']].head()
movie_data_cleaned.iloc[list(range(20)) + [48, 49]]
movie_data_cleaned.iloc[list(range(50, 61))]['popularity']
```
---
**任务2.2: **逻辑读取(Logical Indexing)
1. 读取数据表中 **`popularity` 大于5** 的所有数据。
2. 读取数据表中 **`popularity` 大于5** 的所有数据且**发行年份在1996年之后**的所有数据。
提示:Pandas 中的逻辑运算符如 `&`、`|`,分别代表`且`以及`或`。
要求:请使用 Logical Indexing实现。
```
movie_data_cleaned[movie_data_cleaned['popularity'] > 5]
movie_data_cleaned[(movie_data_cleaned['popularity'] > 5) & (movie_data_cleaned['release_year'] > 1996)]
```
---
**任务2.3: **分组读取
1. 对 `release_year` 进行分组,使用 [`.agg`](http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html) 获得 `revenue` 的均值。
2. 对 `director` 进行分组,使用 [`.agg`](http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html) 获得 `popularity` 的均值,从高到低排列。
要求:使用 `Groupby` 命令实现。
```
movie_data_cleaned.groupby('release_year')['revenue'].agg(['mean'])
movie_data_cleaned.groupby('director')['popularity'].agg('mean').sort_values(ascending=False)
```
---
---
## 第三节 绘图与可视化
接着你要尝试对你的数据进行图像的绘制以及可视化。这一节最重要的是,你能够选择合适的图像,对特定的可视化目标进行可视化。所谓可视化的目标,是你希望从可视化的过程中,观察到怎样的信息以及变化。例如,观察票房随着时间的变化、哪个导演最受欢迎等。
<table>
<thead><tr><th>可视化的目标</th><th>可以使用的图像</th></tr></thead><tbody>
<tr><td>表示某一属性数据的分布</td><td>饼图、直方图、散点图</td></tr>
<tr><td>表示某一属性数据随着某一个变量变化</td><td>条形图、折线图、热力图</td></tr>
<tr><td>比较多个属性的数据之间的关系</td><td>散点图、小提琴图、堆积条形图、堆积折线图</td></tr>
</tbody></table>
在这个部分,你需要根据题目中问题,选择适当的可视化图像进行绘制,并进行相应的分析。对于选做题,他们具有一定的难度,你可以尝试挑战一下~
**任务3.1:**对 `popularity` 最高的20名电影绘制其 `popularity` 值。
```
movies_top_20_pop = movie_data_cleaned.sort_values(by=['popularity'], ascending=False).head(20)
base_color = sns.color_palette()[0]
sns.barplot(data=movies_top_20_pop, x='popularity', y='original_title', color=base_color)
plt.xlabel('Popularity')
plt.ylabel('Title');
```
这里采用的是条形图来展示流行度最高的前20名电影,因为电影标题属于称名量表(nominal)而非顺序量表(ordinal),因此这里按流行度进行排序,最流行的是《侏罗纪世界》,其次是《疯狂的Max》,第三名则是《星级穿越》。
---
**任务3.2:**分析电影净利润(票房-成本)随着年份变化的情况,并简单进行分析。
```
movie_data_cleaned['net_profit'] = movie_data_cleaned['revenue'] - movie_data_cleaned['budget']
cnt_movies_by_year = movie_data_cleaned['original_title'].groupby(movie_data_cleaned['release_year']).count()
cnt_movies_by_year.plot()
plt.xlabel('Year')
plt.ylabel('Movies Released');
cnt_movies_by_year = movie_data_cleaned['net_profit'].groupby(movie_data_cleaned['release_year']).sum()
cnt_movies_by_year.plot()
plt.xlabel('Year')
plt.ylabel('Total Profit');
net_profit_by_year = movie_data_cleaned.groupby(['release_year'])['net_profit'].agg('mean')
net_profit_by_year.plot(kind='line')
plt.xlabel('Year')
plt.ylabel('Avg Profit');
```
电影的发行量和总利润每年是逐步升高的,特别是2000年以后增长很快;再结合平均利润来看,某些年份会有回落,如果某一年电影发行量比较少的, 那么每部电影对平均利润的影响会更大;如果某一年电影发行量较多, 每部电影对平均利润的影响就会更少。
---
**[选做]任务3.3:**选择最多产的10位导演(电影数量最多的),绘制他们排行前3的三部电影的票房情况,并简要进行分析。
```
movie_data_split = movie_data_cleaned['director'].str.split('|', expand=True).stack()\
.reset_index(level=0).set_index('level_0').rename(columns={0:'director'})\
.join(movie_data_cleaned[['revenue', 'original_title']])
top_10_directors = movie_data_split['original_title'].groupby(movie_data_split['director'])\
.count().sort_values(ascending=False)[:10].index
top_director_movies = movie_data_split[movie_data_split['director'].isin(top_10_directors)]
top_3_movies = top_director_movies.sort_values(by='revenue', ascending=False).groupby(['director']).head(3)
def plot_top_3_movies(data, directors):
plt.figure(figsize=(20, 40))
for index, director in enumerate(directors):
plt.subplot(len(directors), 1, index+1)
dd = data[data['director'] == director]
plt.bar(x=dd['original_title'], height=dd['revenue'])
plt.ylabel(director)
plot_top_3_movies(top_3_movies, top_10_directors.values)
```
最多产的10位导演中,前三甲分别是Woody Allen,Clint Eastwood和Steven Spielberg。大部分导演排前3的电影票房差距还是比较大的,名次越靠前,所执导的电影票房收入越高。
---
**[选做]任务3.4:**分析1968年~2015年六月电影的数量的变化。
```
after1968 = movie_data_cleaned['release_year'] >= 1968
before2015 = movie_data_cleaned['release_year'] <= 2015
inJune = movie_data_cleaned['release_date'].str.startswith('6/')
movies_in_year = movie_data_cleaned[(after1968) & (before2015) & (inJune)]
# movies_in_year.groupby(['release_year'])['original_title'].count().plot(kind='bar')
plt.figure(figsize=(10, 8))
sns.countplot(data=movies_in_year, y='release_year', color=base_color)
```
从图像上看,1968年到2015年以来,每年6月发行的电影量总体趋势上是呈上升趋势的,上世纪90年代有小幅回落,千禧年之后又有较大规模增长。
---
**[选做]任务3.5:**分析1968年~2015年六月电影 `Comedy` 和 `Drama` 两类电影的数量的变化。
```
comedy = movies_in_year['genres'].str.contains('Comedy')
drama = movies_in_year['genres'].str.contains('Drama')
movies_drama = movies_in_year[drama]
movies_comedy = movies_in_year[comedy]
plt.figure(figsize=(10, 8))
sns.countplot(data=movies_comedy, y='release_year', color=base_color)
plt.xlabel('Comedy Movies');
```
1968年到2015年期间每年6月喜剧电影发行量总体呈上升趋势,20世纪80年代有过一次小规模的爆发,到了2000年以后,喜剧电影发行量每年6月都超过了10部。
```
plt.figure(figsize=(10, 8))
sns.countplot(data=movies_drama, y='release_year', color=base_color)
plt.xlabel('Drama Movies');
```
1968年到2015年期间每年6月发行的戏剧总体也是呈上升趋势的,从1999年以后戏剧在每年6月发行量有较大增长,大部分都超过了10部。
> 注意: 当你写完了所有的代码,并且回答了所有的问题。你就可以把你的 iPython Notebook 导出成 HTML 文件。你可以在菜单栏,这样导出**File -> Download as -> HTML (.html)、Python (.py)** 把导出的 HTML、python文件 和这个 iPython notebook 一起提交给审阅者。
| github_jupyter |
```
import pickle
import pandas as pd
import numpy as np
import scipy.sparse as sp
from tqdm import tqdm_notebook as tqdm
from numba import jit, njit
```
Load already pickled data:
```
with open('data/df_retail.bin', 'rb') as f_in:
df = pickle.load(f_in)
df.columns = df.columns.str.lower()
df = df[~df.invoiceno.astype('str').str.startswith('C')].reset_index(drop=True)
df.customerid = df.customerid.fillna(-1).astype('int32')
```
Special pre-processor for sequences:
```
class LabelEncoder:
def fit(self, seq):
self.vocab = sorted(set(seq))
self.idx = {c: i + 1 for i, c in enumerate(self.vocab)}
def vocab_size(self):
return len(self.vocab) + 1
def transfrom(self, seq):
n = len(seq)
result = np.zeros(n, dtype='int32')
for i in range(n):
result[i] = self.idx.get(seq[i], 0)
return result
def fit_transform(self, seq):
self.fit(seq)
return self.transfrom(seq)
item_enc = LabelEncoder()
df.stockcode = item_enc.fit_transform(df.stockcode.astype('str'))
df.stockcode = df.stockcode.astype('int32')
```
Train-test split:
```
df_train = df[df.invoicedate < '2011-10-09'].reset_index(drop=True)
df_val = df[(df.invoicedate >= '2011-10-09') & (df.invoicedate <= '2011-11-09') ].reset_index(drop=True)
df_test = df[df.invoicedate >= '2011-11-09'].reset_index(drop=True)
df_train.shape, df_val.shape, df_test.shape
user_enc = LabelEncoder()
user_enc.fit(df_train[df_train.customerid != -1].customerid)
df_train.customerid = user_enc.transfrom(df_train.customerid)
df_val.customerid = user_enc.transfrom(df_val.customerid)
uid_train = df_train.drop_duplicates(subset='invoiceno').customerid.values
uid_val = df_val.drop_duplicates(subset='invoiceno').customerid.values
def group_indptr(df):
indptr, = np.where(df.invoiceno != df.invoiceno.shift())
indptr = np.append(indptr, len(df)).astype('int32')
return indptr
indptr_train = group_indptr(df_train)
indptr_val = group_indptr(df_val)
from collections import Counter
top_train = Counter(df_train.stockcode)
```
Simple baseline
```
def baseline(uid, indptr, items, top, k=5):
n_groups = len(uid)
n_items = len(items)
pred_all = np.zeros((n_items, k), dtype=np.int32)
for g in range(n_groups):
t = top.copy()
start = indptr[g]
end = indptr[g+1]
for i in range(start, end):
pred = [k for (k, c) in t.most_common(5)]
pred_all[i] = pred
actual = items[i]
if actual in t:
del t[actual]
return pred_all
iid_val = df_val.stockcode.values
pred_baseline = baseline(uid_val, indptr_val, iid_val, top_train, k=5)
@njit
def accuracy_k(y_true, y_pred):
n, k = y_pred.shape
acc = 0
for i in range(n):
for j in range(k):
if y_pred[i, j] == y_true[i]:
acc = acc + 1
break
return acc / n
accuracy_k(iid_val, pred_baseline)
```
RNN naive model
Data preparation
```
def pack_items(users, items_indptr, items_vals):
n = len(items_indptr) - 1
result = []
for i in range(n):
start = items_indptr[i]
end = items_indptr[i+1]
result.append(items_vals[start:end])
return result
train_items = pack_items(indptr_train, indptr_train, df_train.stockcode.values)
df_train_wrap = pd.DataFrame()
df_train_wrap['customerid'] = uid_train
df_train_wrap['items'] = train_items
df_train_wrap.head()
def pad_seq(data, num_steps):
data = np.pad(data, pad_width=(1, 0), mode='constant')
n = len(data)
if n <= num_steps:
pad_right = num_steps - n + 1
data = np.pad(data, pad_width=(0, pad_right), mode='constant')
return data
def prepare_train_data(data, num_steps):
data = pad_seq(data, num_steps)
X = []
Y = []
for i in range(num_steps, len(data)):
start = i - num_steps
X.append(data[start:i])
Y.append(data[start+1:i+1])
return X, Y
```
Now ready to do some tensorflow
```
import tensorflow as tf
rnn = tf.contrib.rnn
class Config:
num_steps = 5
num_items = item_enc.vocab_size()
num_users = user_enc.vocab_size()
init_scale = 0.1
learning_rate = 1.0
max_grad_norm = 5
num_layers = 2
hidden_size = 200
embedding_size = 200
batch_size = 20
config = Config()
train_items = df_train_wrap['items']
X_train = []
Y_train = []
for i in range(len(train_items)):
X, Y = prepare_train_data(train_items[i], config.num_steps)
X_train.extend(X)
Y_train.extend(Y)
X_train = np.array(X_train, dtype='int32')
Y_train = np.array(Y_train, dtype='int32')
```
Model graph:
```
def lstm_cell(hidden_size, is_training):
return rnn.BasicLSTMCell(hidden_size, forget_bias=0.0,
state_is_tuple=True, reuse=not is_training)
def rnn_model(inputs, hidden_size, num_layers, batch_size, num_steps, is_training):
cells = [lstm_cell(hidden_size, is_training) for _ in range(num_layers)]
cell = rnn.MultiRNNCell(cells, state_is_tuple=True)
initial_state = cell.zero_state(batch_size, tf.float32)
inputs = tf.unstack(inputs, num=num_steps, axis=1)
outputs, final_state = rnn.static_rnn(cell, inputs, initial_state=initial_state)
output = tf.reshape(tf.concat(outputs, 1), [-1, hidden_size])
return output, initial_state, final_state
def model(config, is_training):
batch_size = config.batch_size
num_steps = config.num_steps
embedding_size = config.embedding_size
hidden_size = config.hidden_size
num_items = config.num_items
place_x = tf.placeholder(shape=[batch_size, num_steps], dtype=tf.int32)
place_y = tf.placeholder(shape=[batch_size, num_steps], dtype=tf.int32)
embedding = tf.get_variable("items", [num_items, embedding_size], dtype=tf.float32)
inputs = tf.nn.embedding_lookup(embedding, place_x)
output, initial_state, final_state = \
rnn_model(inputs, hidden_size, config.num_layers, batch_size, num_steps, is_training)
W = tf.get_variable("W", [hidden_size, num_items], dtype=tf.float32)
b = tf.get_variable("b", [num_items], dtype=tf.float32)
logits = tf.nn.xw_plus_b(output, W, b)
logits = tf.reshape(logits, [batch_size, num_steps, num_items])
loss = tf.losses.sparse_softmax_cross_entropy(place_y, logits)
total_loss = tf.reduce_mean(loss)
tvars = tf.trainable_variables()
gradient = tf.gradients(total_loss, tvars)
clipped, _ = tf.clip_by_global_norm(gradient, config.max_grad_norm)
optimizer = tf.train.GradientDescentOptimizer(config.learning_rate)
global_step = tf.train.get_or_create_global_step()
train_op = optimizer.apply_gradients(zip(clipped, tvars), global_step=global_step)
out = {}
out['place_x'] = place_x
out['place_y'] = place_y
out['logits'] = logits
out['initial_state'] = initial_state
out['final_state'] = final_state
out['total_loss'] = total_loss
out['train_op'] = train_op
return out
```
Initialiation and training
```
config = Config()
config_val = Config()
config_val.batch_size = 1
config_val.num_steps = 1
graph = tf.Graph()
graph.seed = 1
with graph.as_default():
initializer = tf.random_uniform_initializer(-config.init_scale, config.init_scale)
with tf.name_scope("Train"):
with tf.variable_scope("Model", reuse=None, initializer=initializer):
train_model = model(config, is_training=True)
with tf.name_scope("Valid"):
with tf.variable_scope("Model", reuse=True, initializer=initializer):
val_model = model(config_val, is_training=False)
init = tf.global_variables_initializer()
def prepare_batches(seq, step):
n = len(seq)
res = []
for i in range(0, n, step):
res.append(seq[i:i+step])
return res
def run_epoch(session, model, X, Y, batch_size):
fetches = {
"total_loss": model['total_loss'],
"final_state": model['final_state'],
"eval_op": model['train_op']
}
num_steps = X.shape[1]
all_idx = np.arange(X.shape[0])
np.random.shuffle(all_idx)
batches = prepare_batches(all_idx, batch_size)
initial_state = session.run(model['initial_state'])
current_state = initial_state
progress = tqdm(total=len(batches))
for idx in batches:
if len(idx) < batch_size:
continue
feed_dict = {}
for i, (c, h) in enumerate(model['initial_state']):
feed_dict[c] = current_state[i].c
feed_dict[h] = current_state[i].h
feed_dict[model['place_x']] = X[idx]
feed_dict[model['place_y']] = Y[idx]
vals = session.run(fetches, feed_dict)
loss = vals["total_loss"]
current_state = vals["final_state"]
progress.update(1)
progress.set_description('%.3f' % loss)
progress.close()
session = tf.Session(config=None, graph=graph)
session.run(init)
np.random.seed(0)
run_epoch(session, train_model, X_train, Y_train, batch_size=config.batch_size)
def generate_prediction(uid, indptr, items, model, k):
n_groups = len(uid)
n_items = len(items)
pred_all = np.zeros((n_items, k), dtype=np.int32)
initial_state = session.run(model['initial_state'])
fetches = {
"logits": model['logits'],
"final_state": model['final_state'],
}
for g in tqdm(range(n_groups)):
start = indptr[g]
end = indptr[g+1]
current_state = initial_state
feed_dict = {}
for i, (c, h) in enumerate(model['initial_state']):
feed_dict[c] = current_state[i].c
feed_dict[h] = current_state[i].h
prev = np.array([[0]], dtype=np.int32)
for i in range(start, end):
feed_dict[model['place_x']] = prev
actual = items[i]
prev[0, 0] = actual
values = session.run(fetches, feed_dict)
current_state = values["final_state"]
logits = values['logits'].reshape(-1)
pred = np.argpartition(-logits, k)[:k]
pred_all[i] = pred
return pred_all
pred_lstm = generate_prediction(uid_val, indptr_val, iid_val, val_model, k=5)
accuracy_k(iid_val, pred_lstm)
```
Let's add the user features
```
X_train = []
U_train = []
Y_train = []
for t in df_train_wrap.itertuples():
X, Y = prepare_train_data(t.items, config.num_steps)
U_train.extend([t.customerid] * len(X))
X_train.extend(X)
Y_train.extend(Y)
X_train = np.array(X_train, dtype='int32')
Y_train = np.array(Y_train, dtype='int32')
U_train = np.array(U_train, dtype='int32')
def user_model(config, is_training):
batch_size = config.batch_size
num_steps = config.num_steps
embedding_size = config.embedding_size
hidden_size = config.hidden_size
num_items = config.num_items
num_users = config.num_users
place_x = tf.placeholder(shape=[batch_size, num_steps], dtype=tf.int32)
place_u = tf.placeholder(shape=[batch_size, 1], dtype=tf.int32)
place_y = tf.placeholder(shape=[batch_size, num_steps], dtype=tf.int32)
item_embedding = tf.get_variable("items", [num_items, embedding_size], dtype=tf.float32)
item_inputs = tf.nn.embedding_lookup(item_embedding, place_x)
user_embedding = tf.get_variable("users", [num_items, embedding_size], dtype=tf.float32)
u_repeat = tf.tile(place_u, [1, num_steps])
user_inputs = tf.nn.embedding_lookup(user_embedding, u_repeat)
inputs = tf.concat([user_inputs, item_inputs], axis=2)
output, initial_state, final_state = \
rnn_model(inputs, hidden_size, config.num_layers, batch_size, num_steps, is_training)
W = tf.get_variable("W", [hidden_size, num_items], dtype=tf.float32)
b = tf.get_variable("b", [num_items], dtype=tf.float32)
logits = tf.nn.xw_plus_b(output, W, b)
logits = tf.reshape(logits, [batch_size, num_steps, num_items])
loss = tf.losses.sparse_softmax_cross_entropy(place_y, logits)
total_loss = tf.reduce_mean(loss)
tvars = tf.trainable_variables()
gradient = tf.gradients(total_loss, tvars)
clipped, _ = tf.clip_by_global_norm(gradient, config.max_grad_norm)
optimizer = tf.train.GradientDescentOptimizer(config.learning_rate)
global_step = tf.train.get_or_create_global_step()
train_op = optimizer.apply_gradients(zip(clipped, tvars), global_step=global_step)
out = {}
out['place_x'] = place_x
out['place_u'] = place_u
out['place_y'] = place_y
out['logits'] = logits
out['initial_state'] = initial_state
out['final_state'] = final_state
out['total_loss'] = total_loss
out['train_op'] = train_op
return out
graph = tf.Graph()
graph.seed = 1
with graph.as_default():
initializer = tf.random_uniform_initializer(-config.init_scale, config.init_scale)
with tf.name_scope("Train"):
with tf.variable_scope("Model", reuse=None, initializer=initializer):
train_model = user_model(config, is_training=True)
with tf.name_scope("Valid"):
with tf.variable_scope("Model", reuse=True, initializer=initializer):
val_model = user_model(config_val, is_training=False)
init = tf.global_variables_initializer()
session = tf.Session(config=None, graph=graph)
session.run(init)
```
Trainining:
```
def user_model_epoch(session, model, X, U, Y, batch_size):
fetches = {
"total_loss": model['total_loss'],
"final_state": model['final_state'],
"eval_op": model['train_op']
}
num_steps = X.shape[1]
all_idx = np.arange(X.shape[0])
np.random.shuffle(all_idx)
batches = prepare_batches(all_idx, batch_size)
initial_state = session.run(model['initial_state'])
current_state = initial_state
progress = tqdm(total=len(batches))
for idx in batches:
if len(idx) < batch_size:
continue
feed_dict = {}
for i, (c, h) in enumerate(model['initial_state']):
feed_dict[c] = current_state[i].c
feed_dict[h] = current_state[i].h
feed_dict[model['place_x']] = X[idx]
feed_dict[model['place_y']] = Y[idx]
feed_dict[model['place_u']] = U[idx].reshape(-1, 1)
vals = session.run(fetches, feed_dict)
loss = vals["total_loss"]
current_state = vals["final_state"]
progress.update(1)
progress.set_description('%.3f' % loss)
progress.close()
session = tf.Session(config=None, graph=graph)
session.run(init)
np.random.seed(0)
user_model_epoch(session, train_model, X_train, U_train, Y_train, batch_size=config.batch_size)
def generate_prediction_user_model(uid, indptr, items, model, k):
n_groups = len(uid)
n_items = len(items)
pred_all = np.zeros((n_items, k), dtype=np.int32)
initial_state = session.run(model['initial_state'])
fetches = {
"logits": model['logits'],
"final_state": model['final_state'],
}
for g in tqdm(range(n_groups)):
start = indptr[g]
end = indptr[g+1]
u = uid[g]
current_state = initial_state
feed_dict = {}
feed_dict[model['place_u']] = np.array([[u]], dtype=np.int32)
for i, (c, h) in enumerate(model['initial_state']):
feed_dict[c] = current_state[i].c
feed_dict[h] = current_state[i].h
prev = np.array([[0]], dtype=np.int32)
for i in range(start, end):
feed_dict[model['place_x']] = prev
actual = items[i]
prev[0, 0] = actual
values = session.run(fetches, feed_dict)
current_state = values["final_state"]
logits = values['logits'].reshape(-1)
pred = np.argpartition(-logits, k)[:k]
pred_all[i] = pred
return pred_all
pred_lstm = generate_prediction_user_model(uid_val, indptr_val, iid_val, val_model, k=5)
accuracy_k(iid_val, pred_lstm)
```
| github_jupyter |
```
####################################################################################################
# Copyright 2019 Srijan Verma and EMBL-European Bioinformatics Institute
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
####################################################################################################
import pandas as pd
df = pd.read_csv('/ML/dataset/train_validation_data/ML_file.csv')
%matplotlib inline
import matplotlib.pyplot as plt
df.head(3)
df_features_file = pd.read_csv('/feature_selection/protein_and_other_overlap_v10/other_overlap_v10.csv', index_col=0)
df_test_file = pd.read_csv('/feature_selection/protein_and_other_overlap_v10/other_overlap_v10.csv', index_col=0)
df_features_file.head(3)
ens_all_ids = df['Gene stable ID'].tolist()
set_ens_all_ids = set(ens_all_ids)
from tqdm import tqdm
drop_index = []
drop_values = 0
for i in tqdm(range(len(df_test_file))):
if df_test_file['ENS lincRNA gene ID'][i] in set_ens_all_ids:
drop_index.append(i)
drop_values = drop_values + 1
continue
elif df_test_file['Overlap Length'][i] == 'Not Found!':
drop_index.append(i)
drop_values = drop_values + 1
continue
else:
continue
df_test_file.drop(drop_index, axis=0,inplace=True)
df_test_file.reset_index(drop=True, inplace=True)
len(df_test_file)
drop_index = []
drop_values = 0
for i in tqdm(range(len(df_features_file))):
if df_features_file['ENS lincRNA gene ID'][i] in set_ens_all_ids:
continue
else:
drop_index.append(i)
drop_values = drop_values + 1
df_features_file.drop(drop_index, axis=0,inplace=True)
df_features_file.reset_index(drop=True, inplace=True)
len(df_features_file)
neg_ids = []
pos_ids = []
for i in range(len(df)):
if df['output'][i] == 0:
neg_ids.append(df['Gene stable ID'][i])
else:
pos_ids.append(df["Gene stable ID"][i])
set_neg_ids = set(neg_ids)
set_pos_ids = set(pos_ids)
feature_output = []
for i in range(len(df_features_file)):
feature_output.append('-')
no_pos = 0
no_neg = 0
for i in tqdm(range(len(df_features_file))):
if df_features_file['ENS lincRNA gene ID'][i] in set_neg_ids:
feature_output[i] = 0
no_neg = no_neg + 1
elif df_features_file['ENS lincRNA gene ID'][i] in set_pos_ids:
feature_output[i] = 1
no_pos = no_pos + 1
no_neg
no_pos
# feature_output
df_features_file['output'] = feature_output
df_features_file["Max No. of amino acids(ENS)"] = pd.to_numeric(df_features_file["Max No. of amino acids(ENS)"])
df_features_file["Max No. of amino acids(REF)"] = pd.to_numeric(df_features_file["Max No. of amino acids(REF)"])
df_test_file["Max No. of amino acids(ENS)"] = pd.to_numeric(df_test_file["Max No. of amino acids(ENS)"])
df_test_file["Max No. of amino acids(REF)"] = pd.to_numeric(df_test_file["Max No. of amino acids(REF)"])
df_features_file['Overlap Length'] = pd.to_numeric(df_features_file['Overlap Length'])
df_test_file['Overlap Length'] = pd.to_numeric(df_test_file['Overlap Length'])
df_features_file.to_csv('/dataset/train_validation_data/ens_ref_feature_and_output_v10.csv')
df_test_file.to_csv('/dataset/prediction_results_on_test_data/test_file_with_ids.csv')
df_features_file.info()
df_features_file.describe()
print(df_features_file.columns.values)
df_features_file_without_ids = df_features_file.drop(['ENS lincRNA gene ID', 'Ref lncRNA gene ID','Chr region', 'ENS-Ref Overlap ?', 'same_opp_overlap', 'Max Transcript Index for ORF(ENS)', 'Max ORF Sequence(ENS)', 'Max Transcript Index for ORF(REF)', 'Max ORF Sequence(REF)','HGNC ID refseq lncrna?', 'HGNC ID ensembl lincrna?','Ens ID for seq alignment score', 'Ref ID for seq alignment score'], axis=1)
df_test_file_without_ids = df_test_file.drop(['ENS lincRNA gene ID', 'Ref lncRNA gene ID','Chr region', 'ENS-Ref Overlap ?', 'same_opp_overlap', 'Max Transcript Index for ORF(ENS)', 'Max ORF Sequence(ENS)', 'Max Transcript Index for ORF(REF)', 'Max ORF Sequence(REF)','HGNC ID refseq lncrna?', 'HGNC ID ensembl lincrna?','Ens ID for seq alignment score', 'Ref ID for seq alignment score'], axis=1)
df_features_file_without_ids.to_csv('/ML/dataset/train_validation_data/cleaned_training_file.csv')
df_test_file_without_ids.to_csv('/1.lncRNA/ML/dataset/prediction_results_on_test_data/cleaned_test_file.csv')
df_features_file_without_ids.info()
df_test_file_without_ids.info()
# %matplotlib inline
# import matplotlib.pyplot as plt
# plt.scatter(df_features_file['Overlap Length'],df_features_file['output'])
# plt.show()
df_features_file_without_ids.corr(method ='pearson')
df_features_file_without_ids.corr(method ='pearson').to_csv("//summerInternship2k17/GSoC/Ensembl/1.lncRNA/ML/results/corr_matrix.csv")
print(df_features_file_without_ids.groupby('output').size())
df_features_file_without_ids.hist(alpha=0.5, figsize=(20, 10))
plt.tight_layout()
plt.savefig('/ML/results/feature_histograms.png',dpi=1200)
plt.show()
df_features_file_without_ids.head(3)
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
df_features_file_without_ids.head(2)
# Split-out validation dataset
array = df_features_file_without_ids.values
X = array[:,0:24]
Y = array[:,24]
validation_size = 0.20
seed = 7
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)
test_array = df_test_file_without_ids.values
print(test_array.shape)
X_prediction_test = test_array[:,0:24]
print(X_prediction_test.shape)
X.shape
from sklearn.metrics import accuracy_score, log_loss
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from xgboost import XGBClassifier
import pandas
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.dummy import DummyClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
len(df_features_file_without_ids)
import numpy as np
labels = list(set(y_train))
counts = []
for label in labels:
counts.append(np.count_nonzero(y_train == label))
plt.pie(counts, labels=labels, autopct='%1.1f%%')
plt.savefig('/results/train_data_label_pie_chart.png')
plt.show()
classifiers = [
MultinomialNB(),
GaussianNB(),
KNeighborsClassifier(n_neighbors = 12),
DummyClassifier(),
MLPClassifier(),
XGBClassifier(),
KNeighborsClassifier(3),
LogisticRegression(),
SVC(kernel="rbf", C=0.025, probability=True),
SVC(kernel="rbf", C=0.025, probability=True),
NuSVC(probability=True),
DecisionTreeClassifier(),
RandomForestClassifier(),
AdaBoostClassifier(),
GradientBoostingClassifier(),
GaussianNB(),
LinearDiscriminantAnalysis(),
QuadraticDiscriminantAnalysis()]
# Logging for Visual Comparison
log_cols=["Classifier", "Accuracy", "Log Loss"]
log = pd.DataFrame(columns=log_cols)
for clf in classifiers:
clf.fit(X_train, y_train)
name = clf.__class__.__name__
print("="*30)
print(name)
print('****Results****')
train_predictions = clf.predict(X_test)
acc = accuracy_score(y_test, train_predictions)
print("Accuracy: {:.4%}".format(acc))
train_predictions = clf.predict_proba(X_test)
ll = log_loss(y_test, train_predictions)
print("Log Loss: {}".format(ll))
log_entry = pd.DataFrame([[name, acc*100, ll]], columns=log_cols)
log = log.append(log_entry)
print("="*30)
import seaborn as sns
sns.set_color_codes("muted")
sns.barplot(x='Accuracy', y='Classifier', data=log, color="b")
plt.xlabel('Accuracy %')
plt.title('Classifier Accuracy')
plt.savefig('/1.lncRNA/ML/results/Classifier_Accuracy.png',bbox_inches='tight',dpi=1200)
plt.show()
sns.set_color_codes("muted")
sns.barplot(x='Log Loss', y='Classifier', data=log, color="g")
plt.xlabel('Log Loss')
plt.title('Classifier Log Loss')
plt.savefig('/Ensembl/1.lncRNA/ML/results/Classifier_Log_Loss.png',bbox_inches='tight',dpi=1200)
plt.show()
# Test options and evaluation metric
seed = 7
scoring = 'accuracy'
# Spot Check Algorithms
models = []
models.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVM', SVC(gamma='auto')))
models.append(('XGB', XGBClassifier()))
models.append(('LR', LogisticRegression()))
models.append(('RF', RandomForestClassifier()))
models.append(('ADB', AdaBoostClassifier()))
models.append(('GBC', GradientBoostingClassifier()))
# evaluate each model in turn
results = []
names = []
for name, model in models:
kfold = model_selection.KFold(n_splits=10, random_state=seed)
cv_results = model_selection.cross_val_score(model, X_train, y_train, cv=kfold, scoring=scoring)
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
print(msg)
# Compare Algorithms
fig = plt.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
plt.savefig('/GSoC/Ensembl/1.lncRNA/ML/results/boxplot.png',bbox_inches='tight',dpi=1200)
plt.show()
# Make predictions on test dataset
abc = XGBClassifier()
abc.fit(X_train, y_train)
predictions = abc.predict(X_test)
print(accuracy_score(y_test, predictions))
print(confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions))
predictions.shape
false_x_test_index = []
for i in range(len(predictions)):
if predictions[i] != y_test[i]:
false_x_test_index.append(i)
false_x_test_index
cols = [7, 8, 9]
df_features_file_index = df_features_file.set_index(list(df_features_file.columns[cols]))
# df_features_file_index.loc[17270,3,90]
df_features_file_without_ids.head(2)
df_false = df_features_file_without_ids.iloc[0:1]
df_false.drop(df_false.index[[0]], inplace=True)
df_false
overlap_length = []
ens_linc_exon = []
orf_max = []
for i in tqdm(range(len(false_x_test_index))):
df_false = df_false.append(df_features_file_index.loc[X_test[false_x_test_index[i]][2],X_test[false_x_test_index[i]][3],X_test[false_x_test_index[i]][4]])
overlap_length.append(X_test[false_x_test_index[i]][2])
ens_linc_exon.append(X_test[false_x_test_index[i]][3])
orf_max.append(X_test[false_x_test_index[i]][4])
to_drop = [2,3,4]
df_false.reset_index(drop = True, inplace = True)
df_false.drop(df_false[df_false.columns[to_drop]], axis = 1, inplace = True)
df_false.insert(loc=2, column='Overlap Length', value=overlap_length)
df_false.insert(loc=3, column='No. ENS lincrna Exons which overlap RefSeq exons', value=ens_linc_exon)
df_false.insert(loc=4, column='Max ORF length(ENS)', value=orf_max)
y_test_false = []
y_predictions_false = []
for j in false_x_test_index:
y_test_false.append(y_test[j])
y_predictions_false.append(predictions[j])
df_false['True Output'] = y_test_false
df_false['Predicted Output'] = y_predictions_false
df_false.head(2)
df_false.to_csv('/Ensembl/1.lncRNA/ML/results/false_prediction_data(14).csv')
df_false.hist(alpha=0.5, figsize=(20, 10))
plt.tight_layout()
plt.savefig('/results/false_prediction_histograms.png',dpi=1200)
plt.show()
# Make predictions on test dataset
abc = XGBClassifier()
abc.fit(X_train, y_train)
Y_predictions = abc.predict(X_prediction_test)
Y_predictions[0:5]
df_test_file['predictions'] = Y_predictions
df_test_file.head(3)
df_test_file.to_csv('/ML/dataset/prediction_results_on_test_data/test_file_with_ids_and_predictions.csv')
X_train.shape
y_train.shape
Y_train = to_categorical(y_train)
Y_test = to_categorical(y_test)
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
from keras.utils import np_utils
from sklearn.preprocessing import LabelEncoder
from keras.utils.np_utils import to_categorical
from sklearn.utils import shuffle
input_dim = len(df_features_file_without_ids.columns) - 1
model = Sequential()
model.add(Dense(8, input_dim = input_dim , activation = 'relu'))
model.add(Dense(50, activation = 'relu'))
model.add(Dense(50, activation = 'relu'))
model.add(Dense(50, activation = 'relu'))
model.add(Dense(2, activation = 'softmax'))
model.compile(loss = 'categorical_crossentropy' , optimizer = 'adam' , metrics = ['accuracy'] )
model.fit(X_train, Y_train, epochs = 20, batch_size = 5)
scores = model.evaluate(X_test, Y_test)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
# first neural network with keras tutorial
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
# load the dataset
# dataset = loadtxt('pima-indians-diabetes.csv', delimiter=',')
# split into input (X) and output (y) variables
# X = dataset[:,0:8]
# y = dataset[:,8]
# define the keras model
model = Sequential()
model.add(Dense(12, input_dim=22, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the keras model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit the keras model on the dataset
model.fit(X, Y, epochs=15, batch_size=10)
# evaluate the keras model
_, accuracy = model.evaluate(X, Y)
print('Accuracy: %.2f' % (accuracy*100))
```
| github_jupyter |
Seismic data is a neat thing. You can imagine it like an ultra-sound of the subsurface. However, in an ultra-sound, we use much smaller wavelengths to image our body. Seismic data usually has wavelengths around 1m to 100m. That has some physical implications, but for now, we don't have to deal with that. It's just something to keep in mind while thinking about resolution.
Imaging salt has been a huge topic in the seismic industry, basically since they imaged salt the first time. The Society of Exploration geophysicist alone has over 10,000 publications with the [keyword salt](https://library.seg.org/action/doSearch?AllField=salt). Salt bodies are important for the hydrocarbon industry, as they usually form nice oil traps. So there's a clear motivation to delineate salt bodies in the subsurface. If you would like to do a deep dive, you can see [this publication](https://www.iongeo.com/content/documents/Resource%20Center/Articles/INT_Imaging_Salt_tutorial_141101.pdf)
Seismic data interpreters are used to interpreting on 2D or 3D images that have been heavily processed. The standard work of [seismic data analysis](https://wiki.seg.org/wiki/Seismic_Data_Analysis) is open access.
You'll find sections on Salt in there as well (https://wiki.seg.org/wiki/Salt-flank_reflections and https://wiki.seg.org/wiki/Salt_flanks). The seismic itself is pretty "old" in the publication, and you're dealing with data that is less noisy here, which is nice.
[](https://wiki.seg.org/wiki/Salt-flank_reflections#/media/File:Ch05_fig0-1.png)
Caption: Figure 5.0-1 Conflicting dips associated with salt flanks: (a) CMP stack without dip-moveout correction; (b) time migration of the stack in (a); (c) the stack with dip-moveout correction; (d) time migration of the stack in (c). CC-BY-SA Yilmaz.
Interpretation on seismic images has long used texture attributes, to identify better and highlight areas of interest. These can be seen like feature maps on the texture of the seismic. For salt, you will notice that the texture in the salt masks is rather chaotic, where the surrounding seismic is more "striped". You can think of Earth as layered. Sand gets deposited on top of existing sand. In comes salt, which is behaving very much, unlike other rocks. There is an entire research branch dedicated to salt tectonics, that is the movement of salt in the subsurface. To give you the gist, these salt diapirs form from salt layers somewhere else that were under much pressure. These started to flow (behave ductile) and find a way into other layers above. I have written a bit about salt on [my blog](http://the-geophysicist.com/the-showroom-data-for-my-thesis).
One common seismic attribute is called "chaos" or "seismic disorder". So if you talk to cynic geophysicists, you'll hear "that deep learning better outperform the Chaos attribute". A good starting point is [this publication](http://www.chopraseismic.com/wp-content/uploads/2016/08/Chopra_Marfurt_TLE_Aug2016-LowRes.pdf).
Recently, geoscience has started to adopt deep learning, and it has seen a clear boom, particularly in imaging salt. Code for automatic seismic interpretation can be found here:
+ https://github.com/waldeland/CNN-for-ASI
+ https://github.com/bolgebrygg/MalenoV
+ https://github.com/crild/facies_net
You will notice that these solutions load a specific SEG-Y file, which luckily we don't have to bother with. TGS provided some nice PNG files instead. However, you can glean some information from them how to approach seismic data. If you find you need some geophysical helpers, you can [import Bruges](https://github.com/agile-geoscience/bruges)
Let's dive in for now.
```
import os
import sys
import random
import warnings
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import cv2
from tqdm import tqdm_notebook, tnrange
from itertools import chain
from skimage.io import imread, imshow, concatenate_images
from skimage.transform import resize
from skimage.morphology import label
from keras.models import Model, load_model
from keras.layers import Input
from keras.layers.core import Lambda
from keras.layers.convolutional import Conv2D, Conv2DTranspose
from keras.layers.pooling import MaxPooling2D
from keras.layers.merge import concatenate
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras import backend as K
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
# Set some parameters
im_width = 128
im_height = 128
im_chan = 1
path_train = '../input/train/'
path_test = '../input/test/'
```
# Data Exploration
Let's look at some data. We can see that TGS chose to use very varied data by inspecting. That is great and adresses a problem in deep learning geoscience at the moment. We build models on one type of seismic and have no idea whether it generalizes.
```
ids= ['1f1cc6b3a4','5b7c160d0d','6c40978ddf','7dfdf6eeb8','7e5a6e5013']
plt.figure(figsize=(20,10))
for j, img_name in enumerate(ids):
q = j+1
img = load_img('../input/train/images/' + img_name + '.png')
img_mask = load_img('../input/train/masks/' + img_name + '.png')
plt.subplot(1,2*(1+len(ids)),q*2-1)
plt.imshow(img)
plt.subplot(1,2*(1+len(ids)),q*2)
plt.imshow(img_mask)
plt.show()
```
We have many examples without salt, as you can see by the masks that are entirely dark. That's great, an algorithm we build will then know that patches exist entirely without salt. Talk about biasing your data.
We can draw heavily on other work, instead of regurgitating the geophysics work that has been done before. I mentioned that seismic is kind of like ultrasound. So I had a look at https://www.kaggle.com/keegil/keras-u-net-starter-lb-0-277
Let's throw a Unet at our data. I am blatanly stealing from Ketil at this point. All credit goes to him and his nice code.
First we'll need to get our data into a shape that works for U-Nets. That means, it should be a power of 2. Let's do it quick and dirty for now, but eventually, consider aliasing and all that fun.
```
train_ids = next(os.walk(path_train+"images"))[2]
test_ids = next(os.walk(path_test+"images"))[2]
# Get and resize train images and masks
X_train = np.zeros((len(train_ids), im_height, im_width, im_chan), dtype=np.uint8)
Y_train = np.zeros((len(train_ids), im_height, im_width, 1), dtype=np.bool)
print('Getting and resizing train images and masks ... ')
sys.stdout.flush()
for n, id_ in tqdm_notebook(enumerate(train_ids), total=len(train_ids)):
path = path_train
img = load_img(path + '/images/' + id_)
x = img_to_array(img)[:,:,1]
x = resize(x, (128, 128, 1), mode='constant', preserve_range=True)
X_train[n] = x
mask = img_to_array(load_img(path + '/masks/' + id_))[:,:,1]
Y_train[n] = resize(mask, (128, 128, 1), mode='constant', preserve_range=True)
print('Done!')
# Check if training data looks all right
ix = random.randint(0, len(train_ids))
plt.imshow(np.dstack((X_train[ix],X_train[ix],X_train[ix])))
plt.show()
tmp = np.squeeze(Y_train[ix]).astype(np.float32)
plt.imshow(np.dstack((tmp,tmp,tmp)))
plt.show()
```
# Train Model
Our task, just like the segmentation task for nuclei, is evaluated on the mean IoU metric. This one isn't in keras, but obviously, we're stealing this one too from Ketil.
```
# Define IoU metric
def mean_iou(y_true, y_pred):
prec = []
for t in np.arange(0.5, 1.0, 0.05):
y_pred_ = tf.to_int32(y_pred > t)
score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)
K.get_session().run(tf.local_variables_initializer())
with tf.control_dependencies([up_opt]):
score = tf.identity(score)
prec.append(score)
return K.mean(K.stack(prec), axis=0)
```
This is the fun part. Building the sequential Model. The U-Net is basically looking like an Auto-Encoder with shortcuts.
We're also sprinkling in some earlystopping to prevent overfitting. If you're running this on kaggle, this is the point, you want to have GPU support.
```
# Build U-Net model
inputs = Input((im_height, im_width, im_chan))
s = Lambda(lambda x: x / 255) (inputs)
c1 = Conv2D(8, (3, 3), activation='relu', padding='same') (s)
c1 = Conv2D(8, (3, 3), activation='relu', padding='same') (c1)
p1 = MaxPooling2D((2, 2)) (c1)
c2 = Conv2D(16, (3, 3), activation='relu', padding='same') (p1)
c2 = Conv2D(16, (3, 3), activation='relu', padding='same') (c2)
p2 = MaxPooling2D((2, 2)) (c2)
c3 = Conv2D(32, (3, 3), activation='relu', padding='same') (p2)
c3 = Conv2D(32, (3, 3), activation='relu', padding='same') (c3)
p3 = MaxPooling2D((2, 2)) (c3)
c4 = Conv2D(64, (3, 3), activation='relu', padding='same') (p3)
c4 = Conv2D(64, (3, 3), activation='relu', padding='same') (c4)
p4 = MaxPooling2D(pool_size=(2, 2)) (c4)
c5 = Conv2D(128, (3, 3), activation='relu', padding='same') (p4)
c5 = Conv2D(128, (3, 3), activation='relu', padding='same') (c5)
u6 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same') (c5)
u6 = concatenate([u6, c4])
c6 = Conv2D(64, (3, 3), activation='relu', padding='same') (u6)
c6 = Conv2D(64, (3, 3), activation='relu', padding='same') (c6)
u7 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same') (c6)
u7 = concatenate([u7, c3])
c7 = Conv2D(32, (3, 3), activation='relu', padding='same') (u7)
c7 = Conv2D(32, (3, 3), activation='relu', padding='same') (c7)
u8 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same') (c7)
u8 = concatenate([u8, c2])
c8 = Conv2D(16, (3, 3), activation='relu', padding='same') (u8)
c8 = Conv2D(16, (3, 3), activation='relu', padding='same') (c8)
u9 = Conv2DTranspose(8, (2, 2), strides=(2, 2), padding='same') (c8)
u9 = concatenate([u9, c1], axis=3)
c9 = Conv2D(8, (3, 3), activation='relu', padding='same') (u9)
c9 = Conv2D(8, (3, 3), activation='relu', padding='same') (c9)
outputs = Conv2D(1, (1, 1), activation='sigmoid') (c9)
model = Model(inputs=[inputs], outputs=[outputs])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=[mean_iou])
model.summary()
earlystopper = EarlyStopping(patience=5, verbose=1)
checkpointer = ModelCheckpoint('model-tgs-salt-1.h5', verbose=1, save_best_only=True)
results = model.fit(X_train, Y_train, validation_split=0.1, batch_size=8, epochs=30,
callbacks=[earlystopper, checkpointer])
```
# Test Data
First we'll get the test data. This takes a while, it's 18000 samples.
```
# Get and resize test images
X_test = np.zeros((len(test_ids), im_height, im_width, im_chan), dtype=np.uint8)
sizes_test = []
print('Getting and resizing test images ... ')
sys.stdout.flush()
for n, id_ in tqdm_notebook(enumerate(test_ids), total=len(test_ids)):
path = path_test
img = load_img(path + '/images/' + id_)
x = img_to_array(img)[:,:,1]
sizes_test.append([x.shape[0], x.shape[1]])
x = resize(x, (128, 128, 1), mode='constant', preserve_range=True)
X_test[n] = x
print('Done!')
# Predict on train, val and test
model = load_model('model-tgs-salt-1.h5', custom_objects={'mean_iou': mean_iou})
preds_train = model.predict(X_train[:int(X_train.shape[0]*0.9)], verbose=1)
preds_val = model.predict(X_train[int(X_train.shape[0]*0.9):], verbose=1)
preds_test = model.predict(X_test, verbose=1)
# Threshold predictions
preds_train_t = (preds_train > 0.5).astype(np.uint8)
preds_val_t = (preds_val > 0.5).astype(np.uint8)
preds_test_t = (preds_test > 0.5).astype(np.uint8)
# Create list of upsampled test masks
preds_test_upsampled = []
for i in tnrange(len(preds_test)):
preds_test_upsampled.append(resize(np.squeeze(preds_test[i]),
(sizes_test[i][0], sizes_test[i][1]),
mode='constant', preserve_range=True))
preds_test_upsampled[0].shape
```
We'll look at it again, just to be sure.
```
# Perform a sanity check on some random training samples
ix = random.randint(0, len(preds_train_t))
plt.imshow(np.dstack((X_train[ix],X_train[ix],X_train[ix])))
plt.show()
tmp = np.squeeze(Y_train[ix]).astype(np.float32)
plt.imshow(np.dstack((tmp,tmp,tmp)))
plt.show()
tmp = np.squeeze(preds_train_t[ix]).astype(np.float32)
plt.imshow(np.dstack((tmp,tmp,tmp)))
plt.show()
```
# Prepare Submission
We need to prepare the submission. A nice CSV with predictions. All of this is one to one from Ketil and does not differ from any of the other segmentation tasks. Check them out to improve on this.
```
def RLenc(img, order='F', format=True):
"""
img is binary mask image, shape (r,c)
order is down-then-right, i.e. Fortran
format determines if the order needs to be preformatted (according to submission rules) or not
returns run length as an array or string (if format is True)
"""
bytes = img.reshape(img.shape[0] * img.shape[1], order=order)
runs = [] ## list of run lengths
r = 0 ## the current run length
pos = 1 ## count starts from 1 per WK
for c in bytes:
if (c == 0):
if r != 0:
runs.append((pos, r))
pos += r
r = 0
pos += 1
else:
r += 1
# if last run is unsaved (i.e. data ends with 1)
if r != 0:
runs.append((pos, r))
pos += r
r = 0
if format:
z = ''
for rr in runs:
z += '{} {} '.format(rr[0], rr[1])
return z[:-1]
else:
return runs
pred_dict = {fn[:-4]:RLenc(np.round(preds_test_upsampled[i])) for i,fn in tqdm_notebook(enumerate(test_ids))}
sub = pd.DataFrame.from_dict(pred_dict,orient='index')
sub.index.names = ['id']
sub.columns = ['rle_mask']
sub.to_csv('submission.csv')
```
| github_jupyter |
# Outlier detection
In this notebook, I present how Similarity Forest can be used for outlier detection.
KDDCup99 http network attacks dataset is used to compare its performance with Isolation Forest.
Both algorithms work similarly. Unsupervised, random splits are made to partition the data. Average depth, at which a data-point is isolated is used to score its `outlyingness`. The assumption here, is that outliers are often isolated with small number of splits - they lay in regions with lower density, so it's easier to isolate them.
The difference between the algorithms is, that Similarity Forest does not use features directly. What it does instead, is a projection of data-points on a line, drawn through two randomly chosen data-points. The procedure involves comparing the data-points using a specified similarity function. The default choice is to use dot product.
```
from simforest.outliers import IsolationSimilarityForest
from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_auc_score, confusion_matrix, precision_score, recall_score, f1_score
from sklearn.datasets import fetch_kddcup99
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import seaborn as sns
from yellowbrick.model_selection import ValidationCurve
sns.set_style('whitegrid')
plt.set_cmap('Blues')
SEED=42
import warnings
warnings.filterwarnings('ignore')
```
# The dataset
The dataset was used in KDD Cup 1999, that involved building a predictive model capable of distinguishing between ``bad`` connections, called intrusions or attacks, and ``good`` normal connections [1]. There is much more normal connections, that bad ones - they are outliers. For the purpose of this experiment, all classes of attacks are aggregated into one outlier class.
The dataset is splitted into training and test set. The features are scaled.
[1] The description comes from http://kdd.ics.uci.edu/databases/kddcup99/kddcup99.html website.
```
# Fetch data
X, y = fetch_kddcup99(subset='http', random_state=SEED, return_X_y=True)
X, y = X.astype(np.float32), y.astype('str')
# Fix classes
y_df = pd.DataFrame(y, columns=['class'])
y_df.loc[y_df['class'] != 'normal.', 'class'] = -1
y_df.loc[y_df['class'] == 'normal.', 'class'] = 1
y = y_df.values
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
y_train = y_train.ravel().astype(np.int32)
y_test = y_test.ravel().astype(np.int32)
```
We can see that there is very little outliers in the data. The model is not aware of the labels, but we can take a look at them.
```
plt.figure(figsize=(8, 6))
plt.hist(y, bins=3)
plt.title('Class distribution', fontsize=16);
```
# Performance comparison
Isolation Similarity Forest class follows the API of Scikit-Learn. The model is build using model.fit(X) function. Note that in case of outlier detection we don't provide label information to the model.
After fitting the models, we use hold-out dataset, to compare scores that the models produce with the labels. Area under ROC curve is used to compare the performance.
```
# Fit the model and score data points
SF = IsolationSimilarityForest(n_estimators=100, random_state=SEED)
SF.fit(X_train)
sf_pred = SF.decision_function(X_test)
print(f'Similarity Forest ROC-AUC score: {round(roc_auc_score(y_test, sf_pred), 3)}')
# Get class predictions
sf_class_preds = np.ones_like(sf_pred)
sf_class_preds[sf_pred <= 0] = -1
print(f'Similarity Forest precision: {round(precision_score(y_test, sf_class_preds), 3)}')
print(f'Similarity Forest recall: {round(recall_score(y_test, sf_class_preds), 3)}')
print(f'Similarity Forest f1: {round(f1_score(y_test, sf_class_preds), 3)}')
# Plot confusion matrix
plt.figure(figsize=(3, 3))
cm = confusion_matrix(y_test, sf_class_preds)
df_cm = pd.DataFrame(cm, index = ['outlier', 'normal'], columns = ['outlier', 'normal'])
sns.heatmap(df_cm, annot=True, cmap='Blues', fmt='g', cbar=False)
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Similarity Forest', fontsize=16);
# Fit the model and score data points
IF = IsolationForest(random_state=SEED)
IF.fit(X_train)
if_pred = IF.decision_function(X_test)
print(f'Isolation Forest ROC-AUC score: {round(roc_auc_score(y_test, if_pred), 3)}')
# Get class predictions
if_class_preds = np.ones_like(if_pred)
if_class_preds[if_pred <= 0] = -1
print(f'Isolation Forest precision: {round(precision_score(y_test, if_class_preds), 3)}')
print(f'Isolation Forest recall: {round(recall_score(y_test, if_class_preds), 3)}')
print(f'Isolation Forest f1: {round(f1_score(y_test, if_class_preds), 3)}')
# Plot confusion matrix
plt.figure(figsize=(3, 3))
cm = confusion_matrix(y_test, if_class_preds)
df_cm = pd.DataFrame(cm, index = ['outlier', 'normal'], columns = ['outlier', 'normal'])
sns.heatmap(df_cm, annot=True, cmap='Blues', fmt='g', cbar=False)
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Isolation Forest', fontsize=16);
```
# Contamination parameter
We can also specify `contamination` fraction in the dataset, that is the fraction of expected outliers. If such assumption is possible, we can use it.
```
# Fit the model and score data points
SF = IsolationSimilarityForest(n_estimators=100, random_state=SEED, contamination=0.1)
SF.fit(X_train)
sf_pred = SF.decision_function(X_test)
print(f'Similarity Forest ROC-AUC score: {round(roc_auc_score(y_test, sf_pred), 3)}')
# Get class predictions
sf_class_preds = np.ones_like(sf_pred)
sf_class_preds[sf_pred <= 0] = -1
print(f'Similarity Forest precision: {round(precision_score(y_test, sf_class_preds), 3)}')
print(f'Similarity Forest recall: {round(recall_score(y_test, sf_class_preds), 3)}')
print(f'Similarity Forest f1: {round(f1_score(y_test, sf_class_preds), 3)}')
# Plot confusion matrix
plt.figure(figsize=(3, 3))
cm = confusion_matrix(y_test, sf_class_preds)
df_cm = pd.DataFrame(cm, index = ['outlier', 'normal'], columns = ['outlier', 'normal'])
sns.heatmap(df_cm, annot=True, cmap='Blues', fmt='g', cbar=False)
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Similarity Forest', fontsize=16);
```
# Number of trees
The plot shows how Similarity Forest performance depends on number of trees.
```
sf_visualizer = ValidationCurve(
IsolationSimilarityForest(), param_name='n_estimators',
param_range=[10, 20, 30, 50, 70, 100], cv=5, scoring='roc_auc'
)
sf_visualizer.fit(X_train, y_train)
sf_visualizer.show();
```
| github_jupyter |
## Define the Convolutional Neural Network
After you've looked at the data you're working with and, in this case, know the shapes of the images and of the keypoints, you are ready to define a convolutional neural network that can *learn* from this data.
In this notebook and in `models.py`, you will:
1. Define a CNN with images as input and keypoints as output
2. Construct the transformed FaceKeypointsDataset, just as before
3. Train the CNN on the training data, tracking loss
4. See how the trained model performs on test data
5. If necessary, modify the CNN structure and model hyperparameters, so that it performs *well* **\***
**\*** What does *well* mean?
"Well" means that the model's loss decreases during training **and**, when applied to test image data, the model produces keypoints that closely match the true keypoints of each face. And you'll see examples of this later in the notebook.
---
## CNN Architecture
Recall that CNN's are defined by a few types of layers:
* Convolutional layers
* Maxpooling layers
* Fully-connected layers
You are required to use the above layers and encouraged to add multiple convolutional layers and things like dropout layers that may prevent overfitting. You are also encouraged to look at literature on keypoint detection, such as [this paper](https://arxiv.org/pdf/1710.00977.pdf), to help you determine the structure of your network.
### TODO: Define your model in the provided file `models.py` file
This file is mostly empty but contains the expected name and some TODO's for creating your model.
---
## PyTorch Neural Nets
To define a neural network in PyTorch, you define the layers of a model in the function `__init__` and define the feedforward behavior of a network that employs those initialized layers in the function `forward`, which takes in an input image tensor, `x`. The structure of this Net class is shown below and left for you to fill in.
Note: During training, PyTorch will be able to perform backpropagation by keeping track of the network's feedforward behavior and using autograd to calculate the update to the weights in the network.
#### Define the Layers in ` __init__`
As a reminder, a conv/pool layer may be defined like this (in `__init__`):
```
# 1 input image channel (for grayscale images), 32 output channels/feature maps, 3x3 square convolution kernel
self.conv1 = nn.Conv2d(1, 32, 3)
# maxpool that uses a square window of kernel_size=2, stride=2
self.pool = nn.MaxPool2d(2, 2)
```
#### Refer to Layers in `forward`
Then referred to in the `forward` function like this, in which the conv1 layer has a ReLu activation applied to it before maxpooling is applied:
```
x = self.pool(F.relu(self.conv1(x)))
```
Best practice is to place any layers whose weights will change during the training process in `__init__` and refer to them in the `forward` function; any layers or functions that always behave in the same way, such as a pre-defined activation function, should appear *only* in the `forward` function.
#### Why models.py
You are tasked with defining the network in the `models.py` file so that any models you define can be saved and loaded by name in different notebooks in this project directory. For example, by defining a CNN class called `Net` in `models.py`, you can then create that same architecture in this and other notebooks by simply importing the class and instantiating a model:
```
from models import Net
net = Net()
```
```
# import the usual resources
import matplotlib.pyplot as plt
import numpy as np
# watch for any changes in model.py, if it changes, re-load it automatically
%load_ext autoreload
%autoreload 2
## TODO: Define the Net in models.py
import torch
import torch.nn as nn
import torch.nn.functional as F
## TODO: Once you've define the network, you can instantiate it
# one example conv layer has been provided for you
from models import Net
net = Net()
print(net)
```
## Transform the dataset
To prepare for training, create a transformed dataset of images and keypoints.
### TODO: Define a data transform
In PyTorch, a convolutional neural network expects a torch image of a consistent size as input. For efficient training, and so your model's loss does not blow up during training, it is also suggested that you normalize the input images and keypoints. The necessary transforms have been defined in `data_load.py` and you **do not** need to modify these; take a look at this file (you'll see the same transforms that were defined and applied in Notebook 1).
To define the data transform below, use a [composition](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html#compose-transforms) of:
1. Rescaling and/or cropping the data, such that you are left with a square image (the suggested size is 224x224px)
2. Normalizing the images and keypoints; turning each RGB image into a grayscale image with a color range of [0, 1] and transforming the given keypoints into a range of [-1, 1]
3. Turning these images and keypoints into Tensors
These transformations have been defined in `data_load.py`, but it's up to you to call them and create a `data_transform` below. **This transform will be applied to the training data and, later, the test data**. It will change how you go about displaying these images and keypoints, but these steps are essential for efficient training.
As a note, should you want to perform data augmentation (which is optional in this project), and randomly rotate or shift these images, a square image size will be useful; rotating a 224x224 image by 90 degrees will result in the same shape of output.
```
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
# the dataset we created in Notebook 1 is copied in the helper file `data_load.py`
from data_load import FacialKeypointsDataset
# the transforms we defined in Notebook 1 are in the helper file `data_load.py`
from data_load import Rescale, RandomCrop, Normalize, ToTensor
## TODO: define the data_transform using transforms.Compose([all tx's, . , .])
# order matters! i.e. rescaling should come before a smaller crop
data_transform = transforms.Compose([Rescale(250),
RandomCrop(224),
Normalize(),
ToTensor()])
# testing that you've defined a transform
assert(data_transform is not None), 'Define a data_transform'
# create the transformed dataset
transformed_dataset = FacialKeypointsDataset(csv_file='data/training_frames_keypoints.csv',
root_dir='data/training/',
transform=data_transform)
print('Number of images: ', len(transformed_dataset))
# iterate through the transformed dataset and print some stats about the first few samples
for i in range(4):
sample = transformed_dataset[i]
print(i, sample['image'].size(), sample['keypoints'].size())
```
## Batching and loading data
Next, having defined the transformed dataset, we can use PyTorch's DataLoader class to load the training data in batches of whatever size as well as to shuffle the data for training the model. You can read more about the parameters of the DataLoader, in [this documentation](http://pytorch.org/docs/master/data.html).
#### Batch size
Decide on a good batch size for training your model. Try both small and large batch sizes and note how the loss decreases as the model trains.
**Note for Windows users**: Please change the `num_workers` to 0 or you may face some issues with your DataLoader failing.
```
# load training data in batches
batch_size = 10
train_loader = DataLoader(transformed_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=4)
```
## Before training
Take a look at how this model performs before it trains. You should see that the keypoints it predicts start off in one spot and don't match the keypoints on a face at all! It's interesting to visualize this behavior so that you can compare it to the model after training and see how the model has improved.
#### Load in the test dataset
The test dataset is one that this model has *not* seen before, meaning it has not trained with these images. We'll load in this test data and before and after training, see how your model performs on this set!
To visualize this test data, we have to go through some un-transformation steps to turn our images into python images from tensors and to turn our keypoints back into a recognizable range.
```
# load in the test data, using the dataset class
# AND apply the data_transform you defined above
# create the test dataset
test_dataset = FacialKeypointsDataset(csv_file='data/test_frames_keypoints.csv',
root_dir='data/test/',
transform=data_transform)
# load test data in batches
batch_size = 10
test_loader = DataLoader(test_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=4)
```
## Apply the model on a test sample
To test the model on a test sample of data, you have to follow these steps:
1. Extract the image and ground truth keypoints from a sample
2. Make sure the image is a FloatTensor, which the model expects.
3. Forward pass the image through the net to get the predicted, output keypoints.
This function test how the network performs on the first batch of test data. It returns the images, the transformed images, the predicted keypoints (produced by the model), and the ground truth keypoints.
```
# test the model on a batch of test images
def net_sample_output():
# iterate through the test dataset
for i, sample in enumerate(test_loader):
# get sample data: images and ground truth keypoints
images = sample['image']
key_pts = sample['keypoints']
# convert images to FloatTensors
images = images.type(torch.FloatTensor)
# forward pass to get net output
output_pts = net(images)
# reshape to batch_size x 68 x 2 pts
output_pts = output_pts.view(output_pts.size()[0], 68, -1)
# break after first image is tested
if i == 0:
return images, output_pts, key_pts
```
#### Debugging tips
If you get a size or dimension error here, make sure that your network outputs the expected number of keypoints! Or if you get a Tensor type error, look into changing the above code that casts the data into float types: `images = images.type(torch.FloatTensor)`.
```
# call the above function
# returns: test images, test predicted keypoints, test ground truth keypoints
test_images, test_outputs, gt_pts = net_sample_output()
# print out the dimensions of the data to see if they make sense
print(test_images.data.size())
print(test_outputs.data.size())
print(gt_pts.size())
```
## Visualize the predicted keypoints
Once we've had the model produce some predicted output keypoints, we can visualize these points in a way that's similar to how we've displayed this data before, only this time, we have to "un-transform" the image/keypoint data to display it.
Note that I've defined a *new* function, `show_all_keypoints` that displays a grayscale image, its predicted keypoints and its ground truth keypoints (if provided).
```
def show_all_keypoints(image, predicted_key_pts, gt_pts=None):
"""Show image with predicted keypoints"""
# image is grayscale
plt.imshow(image, cmap='gray')
plt.scatter(predicted_key_pts[:, 0], predicted_key_pts[:, 1], s=20, marker='.', c='m')
# plot ground truth points as green pts
if gt_pts is not None:
plt.scatter(gt_pts[:, 0], gt_pts[:, 1], s=20, marker='.', c='g')
```
#### Un-transformation
Next, you'll see a helper function. `visualize_output` that takes in a batch of images, predicted keypoints, and ground truth keypoints and displays a set of those images and their true/predicted keypoints.
This function's main role is to take batches of image and keypoint data (the input and output of your CNN), and transform them into numpy images and un-normalized keypoints (x, y) for normal display. The un-transformation process turns keypoints and images into numpy arrays from Tensors *and* it undoes the keypoint normalization done in the Normalize() transform; it's assumed that you applied these transformations when you loaded your test data.
```
# visualize the output
# by default this shows a batch of 10 images
def visualize_output(test_images, test_outputs, gt_pts=None, batch_size=10):
for i in range(batch_size):
plt.figure(figsize=(20,10))
ax = plt.subplot(1, batch_size, i+1)
# un-transform the image data
image = test_images[i].data # get the image from it's wrapper
image = image.numpy() # convert to numpy array from a Tensor
image = np.transpose(image, (1, 2, 0)) # transpose to go from torch to numpy image
# un-transform the predicted key_pts data
predicted_key_pts = test_outputs[i].data
predicted_key_pts = predicted_key_pts.numpy()
# undo normalization of keypoints
predicted_key_pts = predicted_key_pts*50.0+100
# plot ground truth points for comparison, if they exist
ground_truth_pts = None
if gt_pts is not None:
ground_truth_pts = gt_pts[i]
ground_truth_pts = ground_truth_pts*50.0+100
# call show_all_keypoints
show_all_keypoints(np.squeeze(image), predicted_key_pts, ground_truth_pts)
plt.axis('off')
plt.show()
# call it
visualize_output(test_images, test_outputs, gt_pts)
```
## Training
#### Loss function
Training a network to predict keypoints is different than training a network to predict a class; instead of outputting a distribution of classes and using cross entropy loss, you may want to choose a loss function that is suited for regression, which directly compares a predicted value and target value. Read about the various kinds of loss functions (like MSE or L1/SmoothL1 loss) in [this documentation](http://pytorch.org/docs/master/_modules/torch/nn/modules/loss.html).
### TODO: Define the loss and optimization
Next, you'll define how the model will train by deciding on the loss function and optimizer.
---
```
## TODO: Define the loss and optimization
import torch.optim as optim
learning_rate = 0.001
criterion = nn.SmoothL1Loss()
optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate, momentum = 0.9)
```
## Training and Initial Observation
Now, you'll train on your batched training data from `train_loader` for a number of epochs.
To quickly observe how your model is training and decide on whether or not you should modify it's structure or hyperparameters, you're encouraged to start off with just one or two epochs at first. As you train, note how your the model's loss behaves over time: does it decrease quickly at first and then slow down? Does it take a while to decrease in the first place? What happens if you change the batch size of your training data or modify your loss function? etc.
Use these initial observations to make changes to your model and decide on the best architecture before you train for many epochs and create a final model.
```
def train_net(n_epochs):
# prepare the net for training
net.train()
for epoch in range(n_epochs): # loop over the dataset multiple times
running_loss = 0.0
# train on batches of data, assumes you already have train_loader
for batch_i, data in enumerate(train_loader):
# get the input images and their corresponding labels
images = data['image']
key_pts = data['keypoints']
# flatten pts
key_pts = key_pts.view(key_pts.size(0), -1)
# convert variables to floats for regression loss
key_pts = key_pts.type(torch.FloatTensor)
images = images.type(torch.FloatTensor)
# forward pass to get outputs
output_pts = net(images)
# calculate the loss between predicted and target keypoints
loss = criterion(output_pts, key_pts)
# zero the parameter (weight) gradients
optimizer.zero_grad()
# backward pass to calculate the weight gradients
loss.backward()
# update the weights
optimizer.step()
# print loss statistics
# to convert loss into a scalar and add it to the running_loss, use .item()
running_loss += loss.item()
if batch_i % 10 == 9: # print every 10 batches
print('Epoch: {}, Batch: {}, Avg. Loss: {}'.format(epoch + 1, batch_i+1, running_loss/1000))
running_loss = 0.0
print('Finished Training')
# train your network
n_epochs = 1 # start small, and increase when you've decided on your model structure and hyperparams
train_net(n_epochs)
```
## Test data
See how your model performs on previously unseen, test data. We've already loaded and transformed this data, similar to the training data. Next, run your trained model on these images to see what kind of keypoints are produced. You should be able to see if your model is fitting each new face it sees, if the points are distributed randomly, or if the points have actually overfitted the training data and do not generalize.
```
# get a sample of test data again
test_images, test_outputs, gt_pts = net_sample_output()
print(test_images.data.size())
print(test_outputs.data.size())
print(gt_pts.size())
## TODO: visualize your test output
# you can use the same function as before, by un-commenting the line below:
visualize_output(test_images, test_outputs, gt_pts)
```
Once you've found a good model (or two), save your model so you can load it and use it later!
```
## TODO: change the name to something uniqe for each new model
model_dir = 'saved_models/'
model_name = 'keypoints_model_4.pt'
# after training, save your model parameters in the dir 'saved_models'
torch.save(net.state_dict(), model_dir+model_name)
print(net)
print(next(net.parameters()).is_cuda)
net.cpu()
print(next(net.parameters()).is_cuda)
## TODO: change the name to something uniqe for each new model
model_dir = 'saved_models/'
model_name = 'keypoints_model_3.pt'
# after training, save your model parameters in the dir 'saved_models'
torch.save(net.state_dict(), model_dir+model_name)
```
After you've trained a well-performing model, answer the following questions so that we have some insight into your training and architecture selection process. Answering all questions is required to pass this project.
```
import torch
print(torch.cuda.current_device())
print(torch.cuda.device_count())
print(torch.cuda.get_device_name(0))
print(torch.cuda.is_available())
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
print()
#Additional Info when using cuda
if device.type == 'cuda':
print(torch.cuda.get_device_name(0))
print('Memory Usage:')
print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
print('Cached: ', round(torch.cuda.memory_cached(0)/1024**3,1), 'GB')
#print(net)
net.to(device)
#print(net)
print(next(net.parameters()).is_cuda)
def train_net_gpu(n_epochs):
# prepare the net for training
net.train()
run_loss_save = []
for epoch in range(n_epochs): # loop over the dataset multiple times
running_loss = 0.0
# train on batches of data, assumes you already have train_loader
for batch_i, data in enumerate(train_loader):
# get the input images and their corresponding labels
images = data['image']
key_pts = data['keypoints']
# flatten pts
key_pts = key_pts.view(key_pts.size(0), -1)
# convert variables to floats for regression loss
key_pts = key_pts.type(torch.FloatTensor)
images = images.type(torch.FloatTensor)
key_pts = key_pts.to(device)
images = images.to(device)
# forward pass to get outputs
output_pts = net(images)
# calculate the loss between predicted and target keypoints
loss = criterion(output_pts, key_pts)
# zero the parameter (weight) gradients
optimizer.zero_grad()
# backward pass to calculate the weight gradients
loss.backward()
# update the weights
optimizer.step()
# print loss statistics
running_loss += loss.item()
if batch_i % 10 == 9: # print every 10 batches
print('Epoch: {}, Batch: {}, Avg. Loss: {}'.format(epoch + 1, batch_i+1, running_loss/10))
runn_loss_save
run_loss_save.append(running_loss/10) = 0.0
plt.plot(run_loss_save)
print('Finished Training')
# train your network in GPU
n_epochs = 10 # start small, and increase when you've decided on your model structure and hyperparams
train_net_gpu(n_epochs)
# test the model on a batch of test images
def net_sample_output_gpu():
# iterate through the test dataset
for i, sample in enumerate(test_loader):
# get sample data: images and ground truth keypoints
images = sample['image']
key_pts = sample['keypoints'].to(device)
# convert images to FloatTensors
images = images.type(torch.FloatTensor).to(device)
# forward pass to get net output
output_pts = net(images)
# reshape to batch_size x 68 x 2 pts
output_pts = output_pts.view(output_pts.size()[0], 68, -1)
# break after first image is tested
if i == 0:
return images, output_pts, key_pts
# get a sample of test data again
test_images, test_outputs, gt_pts = net_sample_output_gpu()
print(test_images.data.size())
print(test_outputs.data.size())
print(gt_pts.size())
# visualize the output
# by default this shows a batch of 10 images
def visualize_output_fromcpu(test_images, test_outputs, gt_pts=None, batch_size=10):
for i in range(batch_size):
plt.figure(figsize=(20,10))
ax = plt.subplot(1, batch_size, i+1)
# un-transform the image data
image = test_images[i].data.cpu() # get the image from it's wrapper
image = image.numpy() # convert to numpy array from a Tensor
image = np.transpose(image, (1, 2, 0)) # transpose to go from torch to numpy image
# un-transform the predicted key_pts data
predicted_key_pts = test_outputs[i].data.cpu()
predicted_key_pts = predicted_key_pts.numpy()
# undo normalization of keypoints
predicted_key_pts = predicted_key_pts*50.0+100
# plot ground truth points for comparison, if they exist
ground_truth_pts = None
if gt_pts is not None:
ground_truth_pts = gt_pts[i].cpu()
ground_truth_pts = ground_truth_pts*50.0+100
# call show_all_keypoints
show_all_keypoints(np.squeeze(image), predicted_key_pts, ground_truth_pts)
plt.axis('off')
plt.show()
# call it
visualize_output_fromcpu(test_images, test_outputs, gt_pts)
```
### Question 1: What optimization and loss functions did you choose and why?
**Answer**: write your answer here (double click to edit this cell)
### Question 2: What kind of network architecture did you start with and how did it change as you tried different architectures? Did you decide to add more convolutional layers or any layers to avoid overfitting the data?
**Answer**: write your answer here
### Question 3: How did you decide on the number of epochs and batch_size to train your model?
**Answer**: write your answer here
## Feature Visualization
Sometimes, neural networks are thought of as a black box, given some input, they learn to produce some output. CNN's are actually learning to recognize a variety of spatial patterns and you can visualize what each convolutional layer has been trained to recognize by looking at the weights that make up each convolutional kernel and applying those one at a time to a sample image. This technique is called feature visualization and it's useful for understanding the inner workings of a CNN.
In the cell below, you can see how to extract a single filter (by index) from your first convolutional layer. The filter should appear as a grayscale grid.
```
# Get the weights in the first conv layer, "conv1"
# if necessary, change this to reflect the name of your first conv layer
weights1 = net.conv1.weight.data
w = weights1.numpy()
filter_index = 0
print(w[filter_index][0])
print(w[filter_index][0].shape)
# display the filter weights
plt.imshow(w[filter_index][0], cmap='gray')
```
## Feature maps
Each CNN has at least one convolutional layer that is composed of stacked filters (also known as convolutional kernels). As a CNN trains, it learns what weights to include in it's convolutional kernels and when these kernels are applied to some input image, they produce a set of **feature maps**. So, feature maps are just sets of filtered images; they are the images produced by applying a convolutional kernel to an input image. These maps show us the features that the different layers of the neural network learn to extract. For example, you might imagine a convolutional kernel that detects the vertical edges of a face or another one that detects the corners of eyes. You can see what kind of features each of these kernels detects by applying them to an image. One such example is shown below; from the way it brings out the lines in an the image, you might characterize this as an edge detection filter.
<img src='images/feature_map_ex.png' width=50% height=50%/>
Next, choose a test image and filter it with one of the convolutional kernels in your trained CNN; look at the filtered output to get an idea what that particular kernel detects.
### TODO: Filter an image to see the effect of a convolutional kernel
---
```
##TODO: load in and display any image from the transformed test dataset
## TODO: Using cv's filter2D function,
## apply a specific set of filter weights (like the one displayed above) to the test image
```
### Question 4: Choose one filter from your trained CNN and apply it to a test image; what purpose do you think it plays? What kind of feature do you think it detects?
**Answer**: (does it detect vertical lines or does it blur out noise, etc.) write your answer here
---
## Moving on!
Now that you've defined and trained your model (and saved the best model), you are ready to move on to the last notebook, which combines a face detector with your saved model to create a facial keypoint detection system that can predict the keypoints on *any* face in an image!
| github_jupyter |
```
# !pip -q install ../input/pysastrawi/Sastrawi-1.0.1-py2.py3-none-any.whl
## for data
import json
import pandas as pd
import numpy as np
from sklearn .model_selection import StratifiedKFold, GroupKFold
## for plotting
import matplotlib.pyplot as plt
import seaborn as sns
## for processing
import string
import re
import nltk
from nltk.corpus import stopwords
## for bag-of-words
from sklearn import feature_extraction, model_selection, naive_bayes, pipeline, manifold, preprocessing
## for explainer
from lime import lime_text
## for word embedding
import gensim
import gensim.downloader as gensim_api
## for deep learning
import tensorflow as tf
from tensorflow.keras import models, layers, preprocessing as kprocessing
from tensorflow.keras import backend as K
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
## for bert language model
import transformers
from transformers import TFAutoModel, AutoTokenizer
from transformers import RobertaTokenizer, TFRobertaModel
# from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
import warnings
warnings.filterwarnings('ignore')
# Preprocessing function helper
# replace word that concatenate with other word
def remove_concatenate_2_words(text):
list_words = ['khusus']
for w in list_words:
text = text.replace(w, '')
return text
PUNCT_TO_REMOVE = string.punctuation
def remove_punctuation(text):
return text.translate(str.maketrans('', '', PUNCT_TO_REMOVE))
STOPWORDS_ID = set(stopwords.words('indonesian'))
STOPWORDS_EN = set(stopwords.words('english'))
def remove_stopwords(list_text):
text_not_in_ID = [word for word in list_text if word not in STOPWORDS_EN]
text = [word for word in text_not_in_ID if word not in STOPWORDS_ID]
return text
# remove big number and split text that contains word and number
def remove_big_number(list_text):
words = []
for w in list_text:
sub_w = re.split('(\d+)',w)
for item in sub_w:
try:
tmp = int(item)
if tmp < 7000:
if (tmp>1000) and (tmp % 100 == 0): # for even number
words.append(str(tmp))
elif (tmp<=1000) and (tmp>100) and (tmp % 10 == 0 ):
words.append(str(tmp))
elif (tmp<=100) and (tmp % 2 == 0):
words.append(str(tmp))
except:
words.append(item)
return words
def remove_zero_val(list_text):
return [w for w in list_text if w not in ['0']]
def remove_common_words(list_text):
common_words = "hari keren kere kw super baik jual jualan quality best free kwalitas berkualitas kualitas bagus terbaik kembali dijamin beli gratis murah free diskon ongkir cek berkualitas original asli kualitas uang jaminan jamin terjamin buatan buat kirim wilayah luar kota jawa bali jakarta surabaya bulan month year day tahun hari harian anda your nikmat singapore malaysia indonesia vietnam thailand filipina bangkok jepang buy one get dapat dua two satu meriah kirim send pengiriman paket hemat uang kembali dapat guarantee buatan lokal dalam internasional karya termurah paling murah terbaik cheap murah biaya".split(' ')
return [w for w in list_text if w not in common_words]
def remove_strange_words(list_text):
strange_words = ['aaa', 'aaaa', 'aaaaa', 'abc', 'abcd', 'bb', 'bbb', 'bbbb', 'ccc', 'cccc', 'thn', 'th', 'bln']
return [w for w in list_text if w not in strange_words]
def text_vectorizer(max_features, max_len, vocab):
# max_features: Maximum vocab size.
# max_len: Sequence length to pad the outputs to.
text_dataset = tf.data.Dataset.from_tensor_slices(vocab)
# Create the layer.
vectorize_layer = TextVectorization(
max_tokens = max_features,
output_mode = 'int',
output_sequence_length = max_len
)
vectorize_layer.adapt(text_dataset.batch(64))
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(1,), dtype=tf.string))
model.add(vectorize_layer)
return model
def utils_preprocess_text(text, flg_stemm=False, flg_lemm=True, lst_stopwords=None):
## clean (convert to lowercase and remove punctuations and characters and then strip
text = re.sub(r'[^\w\s]', '', str(text).lower().strip())
## Tokenize (convert from string to list)
lst_text = text.split()
## remove Stopwords
if lst_stopwords is not None:
for stopwords in lst_stopwords:
lst_text = [word for word in lst_text if word not in
stopwords]
## Stemming (remove -ing, -ly, ...)
if flg_stemm == True:
# english stemming
ps = nltk.stem.porter.PorterStemmer()
lst_text = [ps.stem(word) for word in lst_text]
# indonesian stemming
# factory = StemmerFactory()
# id_stemmer = factory.create_stemmer()
# lst_text = [id_stemmer.stem(word) for word in lst_text]
## Lemmatisation (convert the word into root word)
if flg_lemm == True:
lem = nltk.stem.wordnet.WordNetLemmatizer()
lst_text = [lem.lemmatize(word) for word in lst_text]
# remove_zero_val
lst_text = [w for w in lst_text if w not in ['0']]
# remove strange words
strange_words = ['aaa', 'aaaa', 'aaaaa', 'abc', 'abcd', 'bb', 'bbb', 'bbbb', 'ccc', 'cccc', 'thn', 'th', 'bln']
lst_text = [w for w in lst_text if w not in strange_words]
## back to string from list
text = " ".join(lst_text)
return text
def string_escape(s, encoding='utf-8'):
return (
s.encode('latin1') # To bytes, required by 'unicode-escape'
.decode('unicode-escape') # Perform the actual octal-escaping decode
.encode('latin1') # 1:1 mapping back to bytes
.decode(encoding)
) # Decode original encoding
lst_stopwords_en = nltk.corpus.stopwords.words("english")
lst_stopwords_id = nltk.corpus.stopwords.words("indonesian")
df = pd.read_csv('../input/shopee-product-matching/train.csv')
df['label_group'], _ = df['label_group'].factorize()
def fast_encode(texts, tokenizer, chunk_size=256, maxlen=512):
"""
https://www.kaggle.com/xhlulu/jigsaw-tpu-distilbert-with-huggingface-and-keras
"""
tokenizer.enable_truncation(max_length=maxlen)
tokenizer.enable_padding(max_length=maxlen)
all_ids = []
for i in tqdm(range(0, len(texts), chunk_size)):
text_chunk = texts[i:i+chunk_size].tolist()
encs = tokenizer.encode_batch(text_chunk)
all_ids.extend([enc.ids for enc in encs])
return np.array(all_ids)
def regular_encode(texts, tokenizer, maxlen=512):
enc_di = tokenizer.batch_encode_plus(
texts,
# add_special_tokens = True,
return_attention_mask = True,
return_token_type_ids=True,
pad_to_max_length=True,
max_length=maxlen
)
return np.array(enc_di['input_ids']), np.array(enc_di['attention_mask'])
MAX_LEN = 105
MODEL = '../input/tfroberta-base-indonesian/roberta-base-indonesian-522M'
tokenizer = RobertaTokenizer.from_pretrained(MODEL)
# preprocess df_train title & phash
df['tmp'] = df['title'].apply(lambda x: string_escape(x))
df["tmp"] = df["tmp"].apply(lambda x: utils_preprocess_text(
x, flg_stemm=False, flg_lemm=False, lst_stopwords=None))
# for BERT
ids, att_mask = regular_encode(list(df["tmp"].values), tokenizer, maxlen=MAX_LEN)
df['input_ids'] = list(ids)
df['att_mask'] = list(att_mask)
del ids, att_mask
df['tmp'] = df['title'].apply(lambda x: string_escape(x))
df['tmp'] = df['tmp'].apply(lambda x: remove_concatenate_2_words(x))
df['tmp'] = df['tmp'].str.lower()
df['tmp'] = df['tmp'].apply(lambda x: remove_punctuation(x))
df['tmp'] = df['tmp'].apply(lambda x: str(x).split())
df['tmp'] = df['tmp'].apply(lambda x: remove_stopwords(x))
# df['tmp'] = df['tmp'].apply(lambda x: remove_big_number(x))
df['tmp'] = df['tmp'].apply(lambda x: remove_zero_val(x))
# df['tmp'] = df['tmp'].apply(lambda x: remove_common_words(x))
df['tmp'] = df['tmp'].apply(lambda x: remove_strange_words(x))
df['tmp'] = df['tmp'].apply(lambda x: list(np.unique(x)))
# for mlp input
# title vocab
words = list(df['tmp'])
words = list(np.unique(np.concatenate(words)))
# Text vectorizer
model = text_vectorizer(max_features = 25000, max_len = 100, vocab = words)
list_text = [' '.join(x) for x in df['tmp']]
title_vec = model.predict(list_text)
df['title_vec'] = list(title_vec)
del model, list_text, title_vec, words
n_classes = df['label_group'].nunique()
print(f'n_classes: {n_classes}')
df.to_parquet(f'/kaggle/working/train.parquet', engine='pyarrow')
```
| github_jupyter |
# Strategy analysis example
Debugging a strategy can be time-consuming. Freqtrade offers helper functions to visualize raw data.
The following assumes you work with SampleStrategy, data for 5m timeframe from Binance and have downloaded them into the data directory in the default location.
## Setup
```
from pathlib import Path
from freqtrade.configuration import Configuration
# Customize these according to your needs.
# Initialize empty configuration object
config = Configuration.from_files([])
# Optionally, use existing configuration file
# config = Configuration.from_files(["config.json"])
# Define some constants
config["ticker_interval"] = "5m"
# Name of the strategy class
config["strategy"] = "SampleStrategy"
# Location of the data
data_location = Path(config['user_data_dir'], 'data', 'binance')
# Pair to analyze - Only use one pair here
pair = "BTC_USDT"
# Load data using values set above
from freqtrade.data.history import load_pair_history
candles = load_pair_history(datadir=data_location,
timeframe=config["ticker_interval"],
pair=pair)
# Confirm success
print("Loaded " + str(len(candles)) + f" rows of data for {pair} from {data_location}")
candles.head()
```
## Load and run strategy
* Rerun each time the strategy file is changed
```
# Load strategy using values set above
from freqtrade.resolvers import StrategyResolver
strategy = StrategyResolver.load_strategy(config)
# Generate buy/sell signals using strategy
df = strategy.analyze_ticker(candles, {'pair': pair})
df.tail()
```
### Display the trade details
* Note that using `data.head()` would also work, however most indicators have some "startup" data at the top of the dataframe.
* Some possible problems
* Columns with NaN values at the end of the dataframe
* Columns used in `crossed*()` functions with completely different units
* Comparison with full backtest
* having 200 buy signals as output for one pair from `analyze_ticker()` does not necessarily mean that 200 trades will be made during backtesting.
* Assuming you use only one condition such as, `df['rsi'] < 30` as buy condition, this will generate multiple "buy" signals for each pair in sequence (until rsi returns > 29). The bot will only buy on the first of these signals (and also only if a trade-slot ("max_open_trades") is still available), or on one of the middle signals, as soon as a "slot" becomes available.
```
# Report results
print(f"Generated {df['buy'].sum()} buy signals")
data = df.set_index('date', drop=False)
data.tail()
```
## Load existing objects into a Jupyter notebook
The following cells assume that you have already generated data using the cli.
They will allow you to drill deeper into your results, and perform analysis which otherwise would make the output very difficult to digest due to information overload.
### Load backtest results to pandas dataframe
Analyze a trades dataframe (also used below for plotting)
```
from freqtrade.data.btanalysis import load_backtest_data
# Load backtest results
trades = load_backtest_data(config["user_data_dir"] / "backtest_results/backtest-result.json")
# Show value-counts per pair
trades.groupby("pair")["sell_reason"].value_counts()
```
### Load live trading results into a pandas dataframe
In case you did already some trading and want to analyze your performance
```
from freqtrade.data.btanalysis import load_trades_from_db
# Fetch trades from database
trades = load_trades_from_db("sqlite:///tradesv3.sqlite")
# Display results
trades.groupby("pair")["sell_reason"].value_counts()
```
## Analyze the loaded trades for trade parallelism
This can be useful to find the best `max_open_trades` parameter, when used with backtesting in conjunction with `--disable-max-market-positions`.
`analyze_trade_parallelism()` returns a timeseries dataframe with an "open_trades" column, specifying the number of open trades for each candle.
```
from freqtrade.data.btanalysis import analyze_trade_parallelism
# Analyze the above
parallel_trades = analyze_trade_parallelism(trades, '5m')
parallel_trades.plot()
```
## Plot results
Freqtrade offers interactive plotting capabilities based on plotly.
```
from freqtrade.plot.plotting import generate_candlestick_graph
# Limit graph period to keep plotly quick and reactive
# Filter trades to one pair
trades_red = trades.loc[trades['pair'] == pair]
data_red = data['2019-06-01':'2019-06-10']
# Generate candlestick graph
graph = generate_candlestick_graph(pair=pair,
data=data_red,
trades=trades_red,
indicators1=['sma20', 'ema50', 'ema55'],
indicators2=['rsi', 'macd', 'macdsignal', 'macdhist']
)
# Show graph inline
# graph.show()
# Render graph in a seperate window
graph.show(renderer="browser")
```
Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.
| github_jupyter |
# Quantum phase estimation
We explain the quantum phase estimation that allows us to find the phase $\alpha$ of its eigenvalue $\lambda = e^{-i\alpha}$ when the Unitary $U$ and the eigenstate $\lvert \psi \rangle$ are prepared.
$$
U \lvert \psi \rangle = e^{-i\alpha} \lvert \psi \rangle
$$
## Quantum circuit for quantum phase estimation
The overall picture of the quantum phase estimation algorithm is as follows.
1. Preparation of quantum states as an eigenvector.
2. Eigenvalues are extracted and embedded to quantum states (phase kickback).
3. Transform the quantum states and get an eigenvalue as measured bit string (inversed quantum Fourier transform).
```
step2 step3
|0> ----H----------------------*-------iQFT---
|0> ----H--------------*-------|-------iQFT---
|0> ----H--------*-----|-------|-------iQFT---
|0> ----H--*-----|-----|-------|-------iQFT---
| | | |
| | | |
|ψ> -------U1--U2---U4-- -U2n------------
step1
```
## Phase kickback
We review the phase kickback method.
We introduce the controled unitary circuit for the unitary with the eigenvector $\lvert \psi \rangle$ and the corresponding eigenvalue $e^{2\pi i \phi}$. We'll see that the eigenvalue can be embedded to the coefficient of $\lvert 1\rangle$ of the control bit.
The eigenvalue equation for the unitary is following.
$$
U\lvert \psi \rangle = e^{2\pi i \phi} \lvert \psi \rangle
$$
Assuming the quantum state $\lvert \psi \rangle$ is prepared, the phase can be extracted with the controled unitary circuit.
First, from the initial state, the qubit from which you want to extract the result is put into a superposition state using an Hadamard gate.
$$
\lvert 0 \rangle \lvert \psi \rangle \rightarrow \frac{\lvert 0\rangle + \lvert 1 \rangle}{\sqrt{2}} \lvert \psi \rangle = \frac{\lvert 0\rangle \lvert \psi \rangle + \lvert 1 \rangle \lvert \psi \rangle}{\sqrt{2}}
$$
Next, by introducing the controlled unitary circuit, unitary is applied only to the state the control qubit is $\lvert 1\rangle$.
$$
\frac{\lvert 0\rangle \lvert \psi \rangle + \lvert 1 \rangle U \lvert \psi \rangle}{\sqrt{2}}
$$
Using eigenvalue equation, we can extract the eigenvalue to the coefficient.
$$
\frac{\lvert 0\rangle \lvert \psi \rangle + \lvert 1 \rangle e^{2\pi i \phi} \lvert \psi \rangle}{\sqrt{2}} = \frac{\lvert 0\rangle \lvert \psi \rangle + e^{2\pi i \phi} \lvert 1 \rangle \lvert \psi \rangle}{\sqrt{2}} = \frac{\lvert 0\rangle + e^{2\pi i \phi} \mid 1 \rangle}{\sqrt{2}} \lvert \psi \rangle
$$
Next,
$$
\frac{1}{\sqrt{2^n}}\sum_{k=0}^{2^n-1} e^{i2\pi k\phi}\lvert k \rangle
$$
のように、取り出したい桁に対応するkを導入すれば良いですが、これは回転角に対応しており、固有値をk回かけるということをすると、自然と対応することができます。つまり$U^k$のように同じユニタリ操作をk回実行すれば良いことになります。ということで、k回Controlled-Unitary操作を行うことで求めることができます。
$$
\frac{\lvert 0\rangle + U^k \lvert 1 \rangle}{\sqrt{2}} \lvert \psi \rangle = \frac{\lvert 0\rangle + e^{2\pi i k \phi} \lvert 1 \rangle}{\sqrt{2}} \lvert \psi \rangle
$$
これにより、対応する桁kに対してk回の制御付きユニタリゲートをかけることで実行が終了します。
## Quantum Fourier transform
We also review Quantum Fourier transform.
Quantum Fourier transform can transform the binary array input to a quantum state with a corresponding phase.
By using the inverse quantum Fourier transform, which is the inverse circuit of quantum Fourier transform, the phase transferred by the phase kickback described above can be written out as a bit string.
$$
QFT:\lvert x \rangle \mapsto \frac{1}{\sqrt{N}}\sum_{k=0}^{N-1} \omega_n^{xk}\lvert k\rangle
$$
<!--
Assuming $\omega_n = e^{\frac{2\pi i}{N}}$,
$$
{F_N=
\frac{1}{\sqrt{N}}
\left[
\begin{array}{rrrr}
1 & 1 & 1 & \cdots &1\\
1 & \omega_n&\omega_n^2&\cdots&\omega_n^{N-1}\\
1 & \omega_n^2&\omega_n^4&\cdots&\omega_n^{2(N-1)}\\
1 & \omega_n^3&\omega_n^6&\cdots&\omega_n^{3(N-1)}\\
\vdots&\vdots&\vdots&&\vdots\\
1 & \omega_n^{N-1}&\omega_n^{2(N-1)}&\cdots&\omega_n^{(N-1)(N-1)}
\end{array}
\right]
}
$$ -->
When you input bit string $x_n$ to $x_1$, the output quantum state has phases corresponding to the input bit string.
$$
QFT(\lvert x_n,x_{n-1},…,x_1 \rangle) = \frac{1}{\sqrt{N}}(\lvert 0 \rangle + e^{2\pi i [0.x_n]} \lvert 1 \rangle) \otimes … \otimes (\lvert 0 \rangle + e^{2\pi i [0.x_1x_2…x_n]} \lvert 1 \rangle)
$$
$$[0.x_1x_2…] = \frac{x_1}{2}+\frac{x_2}{2^2}+…$$
The input state (bit string) shifted by an order of magnitude is encoded to the relative phase of each qubit in the output quantum state. However, since the coefficients of $\lvert 1\rangle$ for each qubit are all absolute values of $1/\sqrt{N}$, just measuring the individual qubits will produce exactly 50% 0s and 1s.
## Phase kickback + inverse quantum Fourier transform
In quantum phase estimation, we apply the phase kickback described earlier to prepare the following state.
$$
\frac{1}{\sqrt{2^n}}\sum_{k=0}^{2^n-1} e^{i2\pi k\phi}\lvert k \rangle
$$
$\phi$ is an eigenvalue of unitary, which is what we wanted to find.
If such a state can be prepared, an inverse quantum Fourier transform can be used to convert it into a quantum state $\lvert \phi_n,\phi_{n-1},...,\phi_1\rangle$ consisting of a binary-encoded bit sequence of $\phi$.
Therefore, if we perform the measurement at the end, we can extract $\phi$.
In each term, the original phase $\phi$ is multiplied by $k$, which is the same as multiplying the eigenvalue by $k$ times.
Therefore, we can perform the same unitary operation $k$ times as $U^k$. In other words, it can be achieved by performing the Controlled-Unitary operation $k$ times.
$$
\frac{\mid 0\rangle + U^k \mid 1 \rangle}{\sqrt{2}} \mid \psi \rangle = \frac{\mid 0\rangle + e^{2\pi i k \phi} \mid 1 \rangle}{\sqrt{2}} \mid \psi \rangle
$$
Thus, we can prepare the above state by applying the corresponding $k$ times controlled unitary gate for each qubit.
## Estimate the phase of the Z-gate
Let's do exercize。First, let's prepare a Z-gate as a unitary.
$$
Z = \begin{pmatrix}
1&0\\
0&-1
\end{pmatrix}
$$
As first, we check the answer by hand.
Calculate characteristic equation
$$
det\begin{pmatrix}
1-\lambda&0\\
0&-1-\lambda
\end{pmatrix} = 0
$$
and we see that the eigenvalues are $\lambda = 1,-1$.
Eigenvectors are following.
$$
\begin{pmatrix}
1\\
0
\end{pmatrix},
\begin{pmatrix}
0\\
1
\end{pmatrix}
$$
Let's check it.
## Install blueqat
```
!pip install blueqat
```
## Circuit overview
This is an overview of the circuit.
```
|0> ----H--*--iQFT--M
|
|0> ------- Z--------
```
First, prepare two qubits, the 0th and 1st, respectively. Both qubits start in state $\lvert 0\rangle$.
1. Prepare an eigenstate for the first qubit.
2. An Hadamard gate is applied to the 0th qubit to create a superposition state.
3. Apply a CZ gate as a control unitary and kickback the phase to the 0th qubit.
4. Perform an inverse quantum Fourier transform, measure and extract the phase.
We first prepare the eigenstate $\lvert 0\rangle$. In other words, we do nothing with the initial state.
Then, the quantum Fourier transform of a single qubit is equivalent to an Hadamard gate.
(Since the Hadamard matrix is Hermitian, the inverse quantum Fourier transform in this case is also an Hadamard gate)
Thus, the implementation will look like following.
```
from blueqat import Circuit
Circuit().h[0].cz[0,1].h[0].m[:].run(shots=100)
```
Thus $\phi = 0.0$.
The eigenvalues we seek are as follows.
$$
e^{2\pi i \phi} = e^{2\pi i \cdot 0} = e^0 = 1
$$
Next, let's set the eigenstate to be prepared as $\lvert 1 \rangle$.
```
|0> --H--*--iQFT--M
|
|0> --X--Z--------
```
```
Circuit().x[1].h[0].cz[0,1].h[0].m[:].run(shots=100)
```
Now $\phi = 1/2 = 0.5$.
The eigenvalues we seek are as follows.
$$
e^{2\pi i \cdot 0.5} = -1
$$
## The case of estimating the phase of an X-gate
An X-gate is a matrix that looks like this
$$
X =
\begin{pmatrix}
0&1\\
1&0
\end{pmatrix}
$$
We first consider the following eigenvector. The eigenvalue is 1.
$$
\mid \psi \rangle =
\begin{pmatrix}
1\\
1
\end{pmatrix}
$$
The circuit is as follows
```
|0> --H--*--H--M
|
|0> --H--X-----
```
```
Circuit(2).h[:].cx[0,1].h[0].m[0].run(shots=100)
```
This is $\phi = 0.0$ and the eigenvalue is as follows.
$$
\lambda = e^0=1
$$
Next, consider the case with following eigenvector. The eigenvalue is -1.
$$
\mid \psi \rangle =
\begin{pmatrix}
1\\
-1
\end{pmatrix}
$$
```
|0> --H---*--H--M
|
|0> --HZ--X-----
```
```
Circuit(2).h[:].z[1].cx[0,1].h[0].m[0].run(shots=100)
```
Thsu $\phi = 0.5$ and the eigenvalue is as follows.
$$
\lambda = e^{2\pi i \cdot0.5}=-1
$$
| github_jupyter |
This notebook contains my replication of the results from the following paper:
Bleakley, Hoyt, and Chin, Aimee. 2010. Age at arrival, English proficiency, and social assimilation among US immigrants. American Economic Journal: Applied Economics, 2(1), 165-92.
Downloading and viewing this notebook:
-The best way to view this notebook is by downloading it and the repository it is located in from //GitHub//. Other viewing options like MyBinder or NBViewer may have issues with displaying images or coloring of certain parts (missing images can be viewed in the folder //files// on GitHub).
-The original paper, as well as the data and codes provided by the authors can be accessed here: https://www.aeaweb.org/articles?id=10.1257/app.2.1.165
```
#importing packages
import numpy as np
import pandas as pd
from statsmodels.formula.api import wls
from auxiliary import *
from auxiliary2 import *
#setting up dataframes
df_ind1 = pd.read_csv( 'data/p00use_mf_indiv1.csv')
df_ind2 = pd.read_csv( 'data/p00use_mf_indiv2.csv')
df_ind = df_ind1.append(df_ind2)
df_mat = pd.read_csv( 'data/p00use_mf_matched_with_spouse.csv')
```
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc">
<ul class="toc-item">
<li><span><a href="#1.-Introduction" data-toc-modified-id="1.-Introduction-1">1. Introduction</a></span></li>
<li><span><a href="#2.-Theoretical-Background-and-Data-Description" data-toc-modified-id="##2.-Theoretical-Background-and-Data-Description-2">2. Theoretical Background and Data Description</a></span><ul class="toc-item">
<li><span><a href="#2.1-Theoretical-Background" data-toc-modified-id="2.1-Theoretical-Background-2.1">2.1 Theoretical Background</a></span></li>
<li><span><a href="#2.2-Data-Description" data-toc-modified-id="2.2-Data-Description-2.2">2.2 Data Description</a></span></li></ul></li>
<li><span><a href="#3.-Identification-and-Empirical-Strategy" data-toc-modified-id="3.-Identification-and-Empirical-Strategy-3">3. Identification and Empirical Strategy</a></span></li>
<li><span><a href="#4.-Conceptual-issues-in-the-benchmark" data-toc-modified-id="#4.-Conceptual-issues-in-the-benchmark-4">4. Conceptual issues in the benchmark</a></span><ul class="toc-item">
<li><span><a href="#4.1-Social-outcome-and-social-assimilation" data-toc-modified-id="4.1-Social-outcome-and-social-assimilation-4.1">4.1 Social outcome and social assimilation</a></span></li>
<li><span><a href="#4.2-Exogeneity-of-age-at-arrival" data-toc-modified-id="4.2-Exogeneity-of-age-at-arrival-4.2">4.2 Exogeneity of age at arrival</a></span></li>
<li><span><a href="#4.3-Cultural-connotations-in-language" data-toc-modified-id="4.3-Cultural-connotations-in-language-4.3">4.3 Cultural connotations in language</a></span></li></ul></li>
<li><span><a href="#5.-Replication" data-toc-modified-id="#5.-Replication-5">5. Replication</a></span><ul class="toc-item"><li><span><a href="#5.1-Main-result" data-toc-modified-id="5.1-Main-result-5.1">5.1 Main result</a></span></li><li><span><a href="#5.2-Robustness-checks-in-the-benchmark" data-toc-modified-id="5.2-Robustness-checks-in-the-benchmark-5.2">5.2 Robustness checks in the benchmark</a></span></li></ul></li>
<li><span><a href="#6.-Robustness-checks-and-extensions" data-toc-modified-id="#6.-Robustness-checks-and-extensions-6">6. Robustness checks and extensions</a></span><ul class="toc-item"><li><span><a href="#6.1-Durbin-Wu-Hausman-test" data-toc-modified-id="6.1-Durbin-Wu-Hausman-test-6.1">6.1 Durbin Wu Hausman test</a></span></li><li><span><a href="#6.2-Control-for-residence-location" data-toc-modified-id="6.2-Control-for=residence-location-6.2">6.2 Control for residence location</a></span></li><li><span><a href="#6.3-English-effect-on-outcome-gap-between-immigrants-and-spouses" data-toc-modified-id="6.3-English-effect-on-outcome-gap-between-immigrants-and-spouses-6.3">6.3 English effect on outcome gap between immigrants and spouses</a></span></li></ul></li>
<li><span><a href="#7.-Conclusion" data-toc-modified-id="7.-Conclusion-7">7. Conclusion</a></span></li><li><span><a href="#8.-References" data-toc-modified-id="8.-References-8">8. References</a></span></li></ul></div>
---
# 1. Introduction
---
Among numerous scholars, Beakley and Chin (2010) discuss the effect of English proficiency on social assimilation between immigrants in the US. While it is intuitive that immigrants with better English skills would be melt in the US society more thoroughly, competitive theories can be offered to explain the correlation between the two properties. A theory is that English skill lowers the difficulty, or, as economists put it, the cost of across group social interactions. As a result, interaction with the local increases when the immigrants have better English skills. On the other hand, it can also be argued that it is the people, who prefer the destination country’s culture and society more, self-selected into immigrating into the US. And the higher English level of this group of people is another product of their endorsement towards the US culture. So the correlation is just driven by the cultural preference as a confounding factor, rather than causation.
Beakley and Chin (2010) show evidential support for the theory that English proficiency causes social integrations using 2000 census data. The empirical strategy employed is to use the age of arrival as an instrumental variable. The justification of this practice is that the age of arrival correlates with the ability to acquire a second language and at the same time, does not affect other endogenous variables. They also exploite immigrants from Anglophone countries as a control group for non-linguistic effects of age at arrival. The IV esitmation confirms the causal effect of English proficiency on social outcome. English proficiency raises the probabilities of being divorced, having a more educated, higher earning, or US-born spouse, having fewer children.
In this notebook, we will replicate this study of Beakley and Chin. After that, a discussion of the conceptual framework and robustness checks will be offered. Our analysis explores some conceptual and econometrics issues in the original study.
This notebook is structured as follows. In the next section, we present the theoretical background that raises the authors' research interest. Following that we will give a brief data description. In Section 3, we analyze the instrumental variable strategy employed and the specification of the estimations. The main highlights of this notebook are sections 4 to 7. In Section 4, we will discuss some problems of the conceptual framework of the authors. Section 5 presents our replication of the results in the benchmark. Section 6 consists of various robustness checks adn extensions based on the benchmark. in Section 7 we sum up this paper.
---
# 2. Theoretical Background and Data Description
---
## 2.1 Theoretical Background
Researchers are motivated to study the factors contributing to the social assimilation of immigrants. Previous studies, such as Gillian Stevens and Gray Swicegood (1987), Brian Duncan and Stephen J. Trejo (2007), Xin Meng and Robert G. Gregory (2005) have shown that English proficiency raises the probability of intermarriage. Duncan and Trejo (2007) particularly examine Mexican immigrants’ marital outcomes. They investigate certain characteristics of Mexican Americans. It is revealed that Mexican Americans who are married to non-Mexicans “tend to speak better English, be more educated, be more likely to work, and earn more compared to Mexican Americans married to either Mexican immigrants or US-born Mexicans”. Similar evidence to support English proficiency relationships with fertility outcomes are given by Ann Marie Sorenson et al. (1988), and Swicegood et al. (1988). Apart from marital and fertility outcomes, English proficiency also correlated with residential location outcomes, as Edward Funkhouser and Fernando A. Ramos (1993) and Maude Toussaint-Comeau and Sherrie L. W. Rhine (2004) demonstrated. The relationship between the proficiency of the dominant language in the destination country and the level of social assimilation brings significant policy implications. If knowing the mainstream language helps immigrants integrating into their new home, then policies help improving language skills can certainly enhance social harmony.
But the nature of that correlation is still debatable. The “casual hypothesis” claims that language proficiency lower the effort, or in an economics terminology - the “cost” of social interaction with the local residents. Under this partial equilibrium framework, lowering the cost of social interaction implies an increase in the consumption of it. Therefore the language proficiency causes social interaction. However, this hypothesis comes across challenges. The first one is that language proficiency is correlated with other variables that will affect the social outcome. For example, how well a person masters a second language is correlated with his ability such as IQ. It is possible that an immigrant is getting a well-paid simply because of his higher ability instead of language proficiency. Secondly, even if there is a direct relationship between language proficiency and social outcome, it still remains doubtful if it is the people have assimilated into the destination country, such as by having a spouse or a job in the destination country, can improve the English proficiency during their stay in the destination country.
## 2.2 Data Description
Our data is obtained from the 2000 US Census of Population and Housing. Measures including English level, a crucial variable for our computation of the instrumental variable, are self-reported by the respondent as a categorical variable. The census was conducted on household level. We can identify each respondent’s and the cohabiting spouse’s answer. Martial outcomes in social assimilation are therefore possible to be shown.
We subset the data to childhood immigrants currently aged from 25 to 55. A childhood immigrant is an immigrant who was under age 15 upon arrival in the US. A childhood immigrant typically did not choose to immigrate but just follow the parents’ decision. Under our definition, a childhood immigrant spent at least 11 years and at most 55 years in the US. The minimum and maximum age of observations ensure enough years are given to expose to the English environment, at the same time avoid selection biases due to retired and deceased immigrants.
We further subset the data by their origins’ English tie. A childhood immigrant who has a non-English-speaking country of birth belongs to the treatment group. A childhood immigrant whose countries of birth have English as 1) an official language and 2) predominant language, belongs to the control group
Our descriptive statistics can be shown as follows.
```
sumlist_ind = ["eng", "age", "female", "white" , "black" , "asianpi" , "other", "multi" , "hispdum" ,"yrssch", "marriedpresent" ,"divorced" ,"evermarried", "nchild", "haskid" ,"singleparent" ,"nevermarried_haskid", "share_bpld_minusself" ,"abovemean_bpld2" ,"ancestpct_minusself" ,"abovemean_ancestry2" ,"nengdom", "young9","perwt2" ]
sumlist_mat = ["spouseeng", "marriednative" ,"couplesamebpld", "couplesameancestry1", "spouseage", "spouseyrssch" ,"yrssch" ,"spouselnwage", "spouseworkedly" ,"bothworked" ,"nchild" ,"haskid", "nengdom", "young9","perwt2"]
#droppingh Null entry in english skills
df_ind['eng'].replace(' ', np.nan, inplace=True)
df_ind= df_ind.dropna(subset=['eng'])
df_ind["young9"] = np.where(df_ind.agearr<=9,1,0)
dfs_ind= df_ind[sumlist_ind]
dfs_ind.loc[(dfs_ind["nengdom"] ==1 ), 'English group'] = 'Treatment Group : Born in non-English-speaking country'
dfs_ind.loc[(dfs_ind["nengdom"] ==1 )&( dfs_ind["young9"] == 1), 'Age group'] = 'Arrived Age 0-9'
dfs_ind.loc[(dfs_ind["nengdom"] ==1 )&( dfs_ind["young9"] == 0), 'Age group'] = 'Arrived Age 10-14'
dfs_ind.loc[(dfs_ind["nengdom"] ==0 ), 'English group'] = 'Control Group: Born in English-speaking country'
dfs_ind.loc[(dfs_ind["nengdom"] ==0 )&( dfs_ind["young9"] == 1), 'Age group'] = 'Arrived Age 0-9'
dfs_ind.loc[(dfs_ind["nengdom"] ==0 )&( dfs_ind["young9"] == 0), 'Age group'] = 'Arrived Age 10-14'
dfs_ind= dfs_ind.drop(['nengdom', 'young9'], axis=1)
#droppingh Null entry in english skills
df_mat['eng'].replace(' ', np.nan, inplace=True)
df_mat= df_mat.dropna(subset=['eng'])
df_mat["young9"] = df_mat["agearr"] <=9
# keeping useful variables
dfs_mat= df_mat[sumlist_mat]
dfs_mat.loc[(dfs_mat["nengdom"] ==1 ), 'English group'] = 'Treatment Group : Born in non-English-speaking country'
dfs_mat.loc[(dfs_mat["nengdom"] ==1 )&( dfs_mat["young9"] == 1), 'Age group'] = 'Arrived Age 0-9'
dfs_mat.loc[(dfs_mat["nengdom"] ==1 )&( dfs_mat["young9"] == 0), 'Age group'] = 'Arrived Age 10-14'
dfs_mat.loc[(dfs_mat["nengdom"] ==0 ), 'English group'] = 'Control Group: Born in English-speaking country'
dfs_mat.loc[(dfs_mat["nengdom"] ==0 )&( dfs_mat["young9"] == 1), 'Age group'] = 'Arrived Age 0-9'
dfs_mat.loc[(dfs_mat["nengdom"] ==0 )&( dfs_mat["young9"] == 0), 'Age group'] = 'Arrived Age 10-14'
dfs_mat = dfs_mat.rename(columns={'nchild': 'nchild_spouse', 'haskid': 'haskid_spouse'})
dfs_mat= dfs_mat.drop(['nengdom', 'young9'], axis=1)
# the observations is to be weighted by perwt2
sumlist_ind.remove("nengdom")
sumlist_ind.remove("young9")
sumlist_ind.remove("perwt2")
sumlist_mat.remove("nengdom")
sumlist_mat.remove("young9")
sumlist_mat.remove("perwt2")
dfs_ind= dfs_ind.drop(['perwt2'], axis=1)
dfs_mat= dfs_mat.drop(['perwt2'], axis=1)
list_table1 = list(dfs_ind.columns)
list_table1.remove("English group")
list_table1.remove("Age group")
list_table2 = list(dfs_mat.columns)
list_table2.remove("English group")
list_table2.remove("Age group")
for i in list_table1:
dfs_ind = dfs_ind.rename(columns={i: Dict_for_sumlist1[i]})
for i in list_table2:
dfs_mat = dfs_mat.rename(columns={i: Dict_for_sumlist1[i]})
print("Table 1a: the mean and SD of variables for the control group and treatment group")
print("This table refers to column (4) and (1) in Table 1 of the benchmark" )
print("The mean of variables for control group and treatment group")
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
display(dfs_ind.groupby(["English group"]).mean(), dfs_mat.groupby(["English group"]).mean())
print("The standard deviation of variables for control group and treatment group")
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
display(dfs_ind.groupby(["English group"]).std(), dfs_mat.groupby(["English group"]).mean())
print("Table 1b: the mean and SD of variables for the age groups")
print("This table refers to column (5), (6), (2) and (3) in Table 1 of the benchmark" )
print("The mean of variables for age groups")
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
display(dfs_ind.groupby(["English group","Age group"]).mean(), dfs_mat.groupby(["English group","Age group"]).mean())
print("The standard deviation of variables for age groups")
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
display(dfs_ind.groupby(["English group","Age group"]).std(), dfs_mat.groupby(["English group","Age group"]).std())
```
Our descriptive statistics, althought slightly deviate from the benchmarks,give support to the age-language relationship picture we drawn. Late arrivers in treatment group and control group demonstrate a significant difference in English level, while earlier arrivers’ English level are similar.
---
# 3. Identification and Empirical Strategy
---
The challenges require advanced econometrics techniques beyond ordinary least square estimation. The authors choose to use the method of instrumental variable to tackle the issues. What stands out the benchmark compared to other literature is that the authors sensibly make use of the fact that children acquire foreign languages with ease. This strategy is supported by research in physiological studies where researchers identified the physiological feature in the brain which is known as the “critical period of language acquisition” (Eric H. Lenneberg 1967).
The social outcomes are assumed to be a function of age at arrival for non-Anglophone-origin immigrants. If a person coming from a non-English speaking country immigrates to the US at a younger age, one’s English level is going to be closer to the native speakers. It is further assumed that there is no direct effect of age of arrival on the social assimilation. Therefore age-of-arrival will be suitable IV to control for the ability effect.
Our instrumental variable is define as follows:
\begin{equation}\tag{1}
k_{ija}= max (0, a-9) * I (j\quad is\quad a\quad non-English-speaking\quad country)
\end{equation}
where *a* is age at arrival, *I*(·) is the indicator function, and *j* is country of birth
\begin{equation}\tag{2}
ENG_{ija}= \alpha_{1}+\pi_{1}k_{ija}+\delta_{1a}+\gamma_{1j}+W_{ija}'\rho_{1}+\epsilon_{1ija}
\end{equation}
for individual *i* born in country *j* arriving in the US at age *a*. $ENG_{ija}$ is a measure of English language skills, $δ_{1a}$ is a set of age-at-arrival dummies, $γ_{1j}$ is a set of country-of-birth dummies, and $w_{ija}$ is a vector of exogenous explanatory variables (e.g., age, sex, race).
The OLS esitmation is given by
\begin{equation}\tag{3}
y_{ija}= \alpha_{1}+ \beta ENG_{ija} + \delta_{a}+\gamma_{j} + W_{ija}'\rho + \epsilon_{ija}
\end{equation}
for individual *i* born in country *j* arriving in the US at age *a*. $y_{ija}$ is the outcome , $ENG_{ija}$ is a measure of English language skills (the endogenous regressor), $δ_{a}$ is a set of age-at-arrival dummies, $γ_{j}$ is a set of country-of-birth dummies, and $w_{ija}$ is a vector of exogenous explanatory variables (e.g., age, sex, race).
The OLS estimation of equation (3) will be biased because of endogeneity issue. The IV strategy we employed is to get
the first stage esitmate of $\hat{ENG_{ija}}$ using equation (2). And then use $\hat{ENG_{ija}}$ instead of $ENG_{ija}$ in the second stage estimate, i.e. equation (4)
\begin{equation}\tag{4}
y_{ija}= \alpha_{1}+ \beta^{2SLS} \hat{ENG_{ija}} + \delta_{a}+\gamma_{j} + W_{ija}'\rho + \epsilon_{ija}
\end{equation}
The estimation of ${β^{2SLS}}$ will be our target.
Our model can be visualized by a causal graph.
Figure 1. Causal graph
<img src="Graph/CausalGraph.jpg" width="700">
---
# 4. Conceptual issues in the benchmark
---
### 4.1 Social outcome and social assimilation
It seems to us that the authors are treating *social outcome* and *social assimilation* as a pair of synonymies when they are analyzing the statistics result.
It is not clear whether the variables measure the *wellness of the integration*. For example, why an immigrant having a child in the destination country implies that he or she better fitted into US society? Or why an immigrant and his or her spouse are both implies a higher level of social assimilation? We do not see any clear and strong intuition indicating the linkage between the proposed measures and our target concepts. Certainly, for some measures, a significantly low level indicates a potential integration problem. But we cannot tell if there is no problem by an increase in the level.
A thought experiment can elaborate our point. Suppose there is a group of immigrant K from a specific country. If the mean wage of K-people (when fixing other variables) is very low, then it might indicate that they on margins in the labor market. But what if the mean-wage of K-people is very high? It would also mean that they process some systematic properties that the locals do not. These properties also differentiate K-people systematically from the locals. The high mean wage does not make them more integrated into the destination society, although they are absolutely better off in terms of living standards.
An initial guess to solve the problem is to compare the difference of the mean of these variables between the immigrants and the US. If the deviation is small, then it means an immigrant is on average not having a higher or lower outcome from the locals.
However, this is not a solution neither. This issue is more complicated by the US liberal tradition. In principle, individuals are free to choose their own form of life. What does it mean if the immigrants are losing their “homeland features”? If k-people, after observing the undesirable outcome of keeping their “homeland features”, decide to abandon those. And they finally have an outcome having no difference in those outcomes than the locals. Are they really integrating in the US society in terms of the outcome? Or they are just integrating into the US on the surface, but they are not embracing the liberal spirit of the US, which more fundamental than those measure outcomes? To settle this debate, we have to go deep into a philosophical discussion of politics and culture. But that will not be our focus in this short article. We will just be cautious about the conceptual insufficiency of the result about certain outcomes.
### 4.2 Exogeneity of age at arrival
One assumption for using instrumental variable is that the instrument is as good as randomly assign and have no correlation with Y through other uncontrolled variables. The authors justify the exogeneity of age at arrival by stating that for childhood immigrants "age at arrival is not a choice variable since they did not time their own immigration, but merely come with their parents to the United State".
We remain skeptical concerning the exogeneity assumption. Maybe the children are not the ones *making the final call* on the immigrate decision. However, we can reasonably think that the parents, if being responsible, will take *the children's ability to assimilate into considerations* when they are deciding to immigrate or not. If the parents know that their children will have a very rough time living in a new country, they have a higher cost and less probability to immigrate. This is more easily found in East Asian nations (which are non-English-speaking) where the offspring's future is weighted heavily. In addition, for the potentially-non-assimilating children who have already entered secondary school and are unwilling to move with their parents, the parents can just send the children to boarding school or leave the children to relatives in the origins, if they have a lower cost to do so. So these non-assimilating children will not be included in the sample. This is more common in Asian or Middle-East countries (which are non-English-speaking) where family-collectivism is practiced. Siblings of the parents or grandparents have a larger moral responsibility to proxy the parents' role when the parents cannot take care of the children themselves.
These family characteristics, when being uncontrolled for, create self-selection bias where children that are expected to have higher social outcomes will be taking the treatment. This will lead to an overestimation of the treatment effect.
### 4.3 Cultural connotations in language
As the authors remark in the paper, controlling the effect of mastering English (language effect) cannot exclude the effect of “melting” into the US culture and institution. The authors’ solution is to incorporate immigrants from the English speaking countries as the control group, so as to control for the non-language effect. They explain their decision:
>*This is because, upon arrival in the United States, immigrants originating from English-speaking countries encounter everything that immigrants from non-English-speaking countries encounter except a new language. Thus, any difference in outcome between young and old arrivers from non-English-speaking countries that is over and above the difference from English-speaking countries can plausibly be attributed to language*. (Bleakley & Chin, 2010, p.169-170).
Singling out the language effect on immigrants from non-anglophone countries certainly has a significant methodological merit, as anglophone immigrants barely come across any enormous language barrier. But it seems to us doubtful whether the authors can really separate the language effect and the culture effect. Anglophone countries do not share the 100% same culture, however close they are.to each other. It is fairly possible that a British immigrant found the US metric system, jumbo-size Coca-Cola cups, and restaurant tipping manner very confusing. There can still be an influence of culture in the estimation of the parameters for the late-comers in treatment group.
We differ our understanding of the meaning of the parameters estimated from the authors’. Instead of claiming that the difference in outcome is completely attributed to language, we can defend our thesis better by arguing that we have to take into account the embedded cultural effect in language, by looking at the nature of language. As Morris (1949) pointed out, a (natural) language is composed of three parts: semantics, syntax and pragmatics; Semantics refers to “the relations of signs to the objects to which the signs are applicable” are; Syntax refers to “the formal relation of signs to one another”; Pragmatics is “the relations of signs to interpreters”. The authors’ mistake, as it appears to us, is to assume language skill level has only the syntaxial aspect. While anglophone immigrants have not many obstacles in the syntax of English in America, they might have problems in the pragmatics of American English. For example, when a British says “Ooh, isn’t it cold?”, what he is doing (with his words) is to invite the listener to a conversation , but an American will just encode it as merely a question about weather.
Figure 2. Relationship between language, culture and pragmatics
<img src="Graph/Venn diagram.jpg" width="600">
As it is shown by Wittgenstein (1967), “the speaking of language is part of an activity, or of a life-form”. Language is a social practice. When language users are interacting, the culture of the linguistic community is manifested. Culture is embedded in a language, through the pragmatics of it. Culture is instantiated in the language uses and culture-free language is not usable and empty. The language community, having their own culture, decide the rule of the “language game”, by which they determine who is a good speaker and who is not. In other words, to be a good language user, one has to know the culture of that linguistic community.
In our estimation, we could not separate the cultures in the pragmatics side of English in America. But a comprehensive understanding of languages implies that we do not have to so do. Rather, it accepts the cultural aspect being part of the estimator of language level. And it includes the understanding of culture when interpreting the estimation of parameters.
---
# 5. Replication
---
### 5.1 Main result
We first estimate equation (2') which is a modification of equation (2). In equation (2') the dependent variable is a social outcome rather than English proficiency.
\begin{equation}\tag{2'}
Y_{ija}= \alpha_{1}+\pi_{1}k_{ija}+\delta_{1a}+\gamma_{1j}+W_{ija}'\rho_{1}+\epsilon_{1ija}
\end{equation}
Equation (2') is a reduced-form equation that returns the effect of age at arrival on social outcomes for the treatment group in a regression setting. From Table 2, we can observe that age-at-arrival is significant to the majority of variables the authors are interested in, except for some fertility and all location outcomes. In the benchmark, the age-at-arrival effects are to be explained through language proficiency. If this hypothesis is right, further regressions, given by equation (4) should verify that.
```
df_ind['eng'].replace(' ', np.nan, inplace=True)
df_ind= df_ind.dropna(subset=['eng'])
df_ind["pwlinear"] = np.where(df_ind.agearr>=9, df_ind["agearr"]-9 ,0)
df_ind["pwlinear"].describe()
df_ind["idvar"] = df_ind["pwlinear"]*df_ind["nengdom"]
df_ind["idvar"].describe()
df_ind = (df_ind[df_ind.perwt2 !=0])
df_mat['eng'].replace(' ', np.nan, inplace=True)
df_mat= df_mat.dropna(subset=['eng'])
df_mat["young9"] = df_mat["agearr"] <=9
df_mat['eng'].replace(' ', np.nan, inplace=True)
df_mat= df_mat.dropna(subset=['eng'])
df_mat["pwlinear"] = np.where(df_mat.agearr>=9, df_mat["agearr"]-9 ,0)
df_mat["pwlinear"].describe()
df_mat["idvar"] = df_mat["pwlinear"]*df_mat["nengdom"]
df_mat["nchild_spouse"] = df_mat["nchild"]
df_mat["haskid_spouse"] = df_mat["haskid"]
df_ind["eng1"] = np.where(df_ind.eng>=1,1,0)
df_ind["eng2"] = np.where(df_ind.eng>=2,1,0)
df_ind["eng3"] = np.where(df_ind.eng>=3,1,0)
df_ind["tr9"] = df_ind["pwlinear"]*df_ind["nengdom"]
df_mat["tr9"] = df_mat["pwlinear"]*df_mat["nengdom"]
df_mat["nchild_spouse"] = df_mat["nchild"]
df_mat["haskid_spouse"] = df_mat["haskid"]
result_t2_ind = pd.DataFrame({"Dependent variable St": list_table2_ind})
for dep in list_table2_ind:
get_table2_result(df_ind, dep, result_t2_ind)
result_t2_mat = pd.DataFrame({"Dependent variable St": list_table2_mat})
for dep in list_table2_mat:
temp = get_table2_result(df_mat, dep, result_t2_mat)
result_table2 = result_t2_ind.append(result_t2_mat)
result_table2 =get_variable_full_name_table2(result_table2)
result_table2 = result_table2.sort_index(ascending=True)
get_asterisk(result_table2,"P Value", "Coef")
result_table2["Coefficient for identifying instrument variable"] = (result_table2["Parameter"].astype(str) + result_table2["Coef Sig. level"])
result_table2= result_table2[["Coefficient for identifying instrument variable","SE"]]
print("Table 2—Reduced-Form Effects")
print("This table refers to Table 2 in the benchmark")
display(result_table2)
```
The key results of the benchmark is replicated in table 3a, 3b and 3C, where we first look at the OLS and 2SLS results using equation (4) on the whole sample, male and female. English level, adjusted by the instrumental variable, affects most of the marital outcome. For example, the English skill level decreases the probability of being currently married. However, the effects on marital outcomes (that authors are interested in) do not tell a clear picture of the assimilation status of immigrants, which we explained earlier in the conceptual issues section.
```
#plot table 3
df_ind_t3 = get_1st_stage_result(df_ind)
df_mat_t3 = get_1st_stage_result(df_mat)
result_table3_ind = pd.DataFrame({"Dependent variable St": list_table3_ind})
for var in list_table3_ind:
get_ols_tsls_result(df_ind_t3, var, result_table3_ind)
result_table3_mat = pd.DataFrame({"Dependent variable St": list_table3_mat})
for var in list_table3_mat:
get_ols_tsls_result(df_mat_t3, var, result_table3_mat)
result_table3 = result_table3_ind.append(result_table3_mat)
result_table3 = get_variable_full_name_table3(result_table3)
result_table3 = result_table3.sort_index(ascending=True)
get_asteris_and_coef(result_table3,"OLS P Value", "OLS", "English effect(OLS)")
get_asteris_and_coef(result_table3,"2SLS P Value", "2SLS", "English effect(2SLS)")
print("Table 3a —Effect of English-Language Skills on Marriage Outcomes")
print("This table refers to the column (1) and (2) in Table (3),(4),(5) in the benchmark")
result_table3[["English effect(OLS)", "OLS SE" , "English effect(2SLS)", "2SLS SE", "2SLS Adj R sq"]]
# plot table 3 female sample
df_ind_t3_female = df_ind[df_ind["female"] == 1]
df_mat_t3_female = df_mat[df_mat["female"] == 1]
df_ind_t3_female = get_1st_stage_result(df_ind_t3_female)
df_mat_t3_female = get_1st_stage_result(df_mat_t3_female)
result_table3_female_ind = pd.DataFrame({"Dependent variable St": list_table3_ind})
for var in list_table3_ind:
(temp_ols, temp_2SLS) = get_ols_tsls_result(df_ind_t3_female, var, result_table3_female_ind)
result_table3_female_mat = pd.DataFrame({"Dependent variable St": list_table3_mat})
for var in list_table3_mat:
(temp_ols, temp_2SLS) = get_ols_tsls_result(df_mat_t3_female, var, result_table3_female_mat)
result_table3_female = result_table3_female_ind.append(result_table3_female_mat)
result_table3_female = get_variable_full_name_table3(result_table3_female)
result_table3_female = result_table3_female.sort_index(ascending=True, sort_remaining =False)
get_asteris_and_coef(result_table3_female,"OLS P Value", "OLS", "English effect(OLS)")
get_asteris_and_coef(result_table3_female,"2SLS P Value", "2SLS", "English effect(2SLS)")
print("Table 3b —Effect of English-Language Skills on Marriage Outcomes, female sample")
print("This table refers to the column (3) and (4) in Table (3),(4),(5) in the benchmark")
result_table3_female[["English effect(OLS)", "OLS SE" , "English effect(2SLS)", "2SLS SE", "2SLS Adj R sq"]]
# plot table 3 male sample
df_ind_t3_male = df_ind[df_ind["female"] == 0]
df_mat_t3_male = df_mat[df_mat["female"] == 0]
df_ind_t3_male = get_1st_stage_result(df_ind_t3_male)
df_mat_t3_male = get_1st_stage_result(df_mat_t3_male)
result_table3_male_ind = pd.DataFrame({"Dependent variable St": list_table3_ind})
for var in list_table3_ind:
(temp_ols, temp_2SLS) = get_ols_tsls_result(df_ind_t3_male, var, result_table3_male_ind)
result_table3_male_mat = pd.DataFrame({"Dependent variable St": list_table3_mat})
for var in list_table3_mat:
(temp_ols, temp_2SLS) = get_ols_tsls_result(df_mat_t3_male, var, result_table3_male_mat)
result_table3_male = result_table3_male_ind.append(result_table3_male_mat)
result_table3_male = get_variable_full_name_table3(result_table3_male)
result_table3_male = result_table3_male.sort_index(ascending=True, sort_remaining =False)
get_asteris_and_coef(result_table3_male,"OLS P Value", "OLS", "English effect(OLS)")
get_asteris_and_coef(result_table3_male,"2SLS P Value", "2SLS", "English effect(2SLS)")
print("Table 3c —Effect of English-Language Skills on Marriage Outcomes, male sample")
print("This table refers to the column (5) and (6) in Table (3),(4),(5) in the benchmark")
result_table3_male[["English effect(OLS)", "OLS SE" , "English effect(2SLS)", "2SLS SE", "2SLS Adj R sq"]]
```
The coefficients for “Spouse English-speaking ability”, “Spouse is US-born” and “Spouse has the same country of birth” are more direct indicators to an immigrant’s status: His or her English level moves in the same direction with the spouse English ability and the probability of the spouse being US-born, and it moves in the opposite direction with the probability of marrying someone from the same country of birth. These results imply that English level helps an immigrant to depart from the social circle of his or her countrypeople and be able to build relationships, in one most intimate form, with the US locals. Similarly, English also improves the spouse labor outcome, such as wage and employment status. It is worth noticing that for female immigrants, higher English level statistically significantly decreases the age of their spouses, while we do not observe a significant effect for male respondents.
English level does not bring significant effects to fertility outcomes, except for the decrease in the number of children. It might be caused by the fact that the mean age in the treatment group (36.54) is slightly less than that in the control group (38.403). In addition, English skills bear no demonstrative improvement in ethnic enclaving or resident location outcomes. The technicality issue is that due to data privacy, the lowest level of geographic aggregation measure “public-use microdata area” (PUMA), which is an area containing at least 100,000 people. As a result, our definition for a neighborhood becomes too big, leading to the unsatisfactory theoretical ground for our estimation.
However, in the authors’ analysis, the adjusted R-square of each estimation is not presented. As soon as we pay attention to the goodness-of-fit, we discover that equation (4) does a poor job in giving precise predictions. 2SLS estimations on an outcome such as “is currently married with spouse present”, “is currently divorced”, “has a child living in the same household”, “is a single parent” and “spouse worked last year” have an adjusted R-squared less than 0.04, which as a sign that there is just too much residual. The poor goodness-of-fit of the outcome with currently married (or divorced) might be consistent with our previous analysis. The effect of English on an immigrant’s decision on marriage is ambiguous, as there are reasonable theories to predict the opposite results.
### 5.2 Robustness checks in the benchmark
It is possible that in table 3a,3b and 3c there are uncontrol features for the treatment group (childhood immigrants from non-English-speaking countries) that will be included in the 2SLS estimator. The authors consider alternative hypotheses for robustness check, in order to eliminate the non-language effect in the estimations. The robustness checks done by the authors are summarized in table 4a. The results in alternative specifications, as shown in table 4b, are similar to the baseline 2SLS analysis.
Table 4a — Summary of robustness check in the benchmark: Feature, movitivation and solution
<img src="Graph/TableRobustness.jpg" width="800">
```
####################get baseline result (from table 3 )
result_table4_baseline = result_table3[["English effect(2SLS)", "2SLS SE"]]
# result_table4_baseline = result_table4_baseline.rename(columns={"English effect(2SLS)":"Base results (1)","2SLS SE":"2SLS SE"},inplace = True)
####################get result with control in origin's GDP
df_ind_GDP = df_ind
df_mat_GDP = df_mat
df_ind_GDP['lngdp'].replace(' ', np.nan, inplace=True)
df_ind_GDP= df_ind_GDP.dropna(subset=['lngdp'])
df_mat_GDP['lngdp'].replace(' ', np.nan, inplace=True)
df_mat_GDP= df_mat_GDP.dropna(subset=['lngdp'])
df_ind_GDP["pwxgdp"]=(df_ind_GDP["pwlinear"]*df_ind_GDP["lngdp"])/100
df_mat_GDP["pwxgdp"]=(df_mat_GDP["pwlinear"]*df_mat_GDP["lngdp"])/100
df_ind_GDP = get_first_stage_result_table4(df_ind_GDP ,"pwxgdp" )
df_mat_GDP = get_first_stage_result_table4(df_mat_GDP, "pwxgdp")
result_ind = pd.DataFrame({"Dependent variable St": list_table3_ind})
for var in list_table3_ind:
(temp_2SLS) = get_tsls_result_table4(df_ind_GDP, var, result_ind,"pwxgdp")
result_mat = pd.DataFrame({"Dependent variable St": list_table3_mat})
for var in list_table3_mat:
(temp_2SLS) = get_tsls_result_table4(df_mat_GDP, var, result_mat,"pwxgdp")
result_table4_control_GDP = result_ind.append(result_mat)
result_table4_control_GDP = get_variable_full_name_table3(result_table4_control_GDP)
get_asteris_and_coef(result_table4_control_GDP,"2SLS P Value", "2SLS", "Control for origin GDP × age at arrival (2)")
result_table4_control_GDP = result_table4_control_GDP[["Control for origin GDP × age at arrival (2)", "2SLS SE"]]
####################get result with control in origin's fertility
df_ind_tfr = df_ind
df_mat_tfr = df_mat
df_ind_tfr['tfr82'].replace(' ', np.nan, inplace=True)
df_ind_tfr= df_ind_tfr.dropna(subset=['tfr82'])
df_mat_tfr['tfr82'].replace(' ', np.nan, inplace=True)
df_mat_tfr= df_mat_tfr.dropna(subset=['tfr82'])
df_ind_tfr["pwxtfr"]=(df_ind_tfr["pwlinear"]*df_ind_tfr["tfr82"])
df_mat_tfr["pwxtfr"]=(df_mat_tfr["pwlinear"]*df_mat_tfr["tfr82"])
df_ind_tfr = get_first_stage_result_table4(df_ind_tfr ,"pwxtfr" )
df_mat_tfr = get_first_stage_result_table4(df_mat_tfr, "pwxtfr")
result_ind = pd.DataFrame({"Dependent variable St": list_table3_ind})
for var in list_table3_ind:
(temp_2SLS) = get_tsls_result_table4(df_ind_tfr, var, result_ind,"pwxtfr")
result_mat = pd.DataFrame({"Dependent variable St": list_table3_mat})
for var in list_table3_mat:
(temp_2SLS) = get_tsls_result_table4(df_mat_tfr, var, result_mat,"pwxtfr")
result_table4_control_fertility = result_ind.append(result_mat)
result_table4_control_fertility = get_variable_full_name_table3(result_table4_control_fertility)
get_asteris_and_coef(result_table4_control_fertility,"2SLS P Value", "2SLS", "Control for origin fertility × age at arrival (3)")
result_table4_control_fertility = result_table4_control_fertility[["Control for origin fertility × age at arrival (3)", "2SLS SE"]]
####################get result dropping immigrants from Canada
df_ind_no_CA = df_ind
df_mat_no_CA = df_mat
df_ind_no_CA = (df_ind_no_CA[df_ind_no_CA.bpld !=15000])
df_mat_no_CA = (df_mat_no_CA[df_mat_no_CA.bpld !=15000])
df_ind_no_CA = get_first_stage_result_table4(df_ind_no_CA )
df_mat_no_CA = get_first_stage_result_table4(df_mat_no_CA)
result_ind = pd.DataFrame({"Dependent variable St": list_table3_ind})
for var in list_table3_ind:
(temp_2SLS) = get_tsls_result_table4(df_ind_no_CA, var, result_ind)
result_mat = pd.DataFrame({"Dependent variable St": list_table3_mat})
for var in list_table3_mat:
(temp_2SLS) = get_tsls_result_table4(df_mat_no_CA, var, result_mat)
result_table4_no_CA = result_ind.append(result_mat)
result_table4_no_CA = get_variable_full_name_table3(result_table4_no_CA)
get_asteris_and_coef(result_table4_no_CA,"2SLS P Value", "2SLS", "Drop Canada (4)")
result_table4_no_CA = result_table4_no_CA[["Drop Canada (4)", "2SLS SE"]]
####################get result dropping immigrants from Mexico
df_ind_no_Mex = df_ind
df_mat_no_Mex = df_mat
df_ind_no_Mex = (df_ind_no_Mex[df_ind_no_Mex.bpld !=20000])
df_mat_no_Mex = (df_mat_no_Mex[df_mat_no_Mex.bpld !=20000])
df_ind_no_Mex = get_first_stage_result_table4(df_ind_no_Mex)
df_mat_no_Mex = get_first_stage_result_table4(df_mat_no_Mex)
result_ind = pd.DataFrame({"Dependent variable St": list_table3_ind})
for var in list_table3_ind:
(temp_2SLS) = get_tsls_result_table4(df_ind_no_Mex, var, result_ind)
result_mat = pd.DataFrame({"Dependent variable St": list_table3_mat})
for var in list_table3_mat:
(temp_2SLS) = get_tsls_result_table4(df_mat_no_Mex, var, result_mat)
result_table4_no_Mex = result_ind.append(result_mat)
result_table4_no_Mex = get_variable_full_name_table3(result_table4_no_Mex)
get_asteris_and_coef(result_table4_no_Mex,"2SLS P Value", "2SLS", "Drop Mexico (5)")
result_table4_no_Mex = result_table4_no_Mex[["Drop Mexico (5)", "2SLS SE"]]
result_table4_no_Mex
result_table4_baseline=result_table4_baseline.rename(columns={ "English effect(2SLS)":"Base results (1)", "2SLS SE": "SE(1)"})
result_table4_control_GDP=result_table4_control_GDP.rename(columns={"2SLS SE": "SE(2)"})
result_table4_control_fertility=result_table4_control_fertility.rename(columns={"2SLS SE": "SE(3)"})
result_table4_no_CA=result_table4_no_CA.rename(columns={"2SLS SE": "SE(4)"})
result_table4_no_Mex=result_table4_no_Mex.rename(columns={"2SLS SE": "SE(5)"})
result_table4 = pd.merge(result_table4_baseline, result_table4_control_GDP,
left_on=["Panel",'Dependent variable'], right_on = ["Panel",'Dependent variable'], how = 'left')
result_table4 = pd.merge(result_table4, result_table4_control_fertility,
left_on=["Panel",'Dependent variable'], right_on = ["Panel",'Dependent variable'], how = 'left')
result_table4 = pd.merge(result_table4, result_table4_no_CA,
left_on=["Panel",'Dependent variable'], right_on = ["Panel",'Dependent variable'], how = 'left')
result_table4 = pd.merge(result_table4, result_table4_no_Mex,
left_on=["Panel",'Dependent variable'], right_on = ["Panel",'Dependent variable'], how = 'left')
result_table4 = result_table4.sort_index(ascending=True, sort_remaining =False)
print("Table 4b — 2SLS Effect of English Using Alternative Samples and Specifications")
print("This table refers to Table (6) in the benchmark")
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
display(result_table4)
```
---
# 6. Robustness checks and extensions
---
### 6.1 Durbin Wu Hausman test
We first examine the endogeneity of English proficiency, or in other words, whether employing IV add merits to our analysis. Although the benchmark authors test for endogeneity by comparing OLS and IV estimate, we can also test for endogeneity in a more formal way by running the Durbin–Wu–Hausman test on English proficiency.
As stated before, our equation (2) is:
\begin{equation}\tag{2}
ENG_{ija}= \alpha_{1}+\pi_{1}k_{ija}+\delta_{1a}+\gamma_{1j}+W_{ija}'\rho_{1}+\epsilon_{1ija}
\end{equation}
By equation (2), we get the estimation of $\epsilon_{1ija}$ ie. $\hat{\epsilon_{1ija}}$
Durbin–Wu–Hausman test result given by
\begin{equation}\tag{5}
y_{ija}= \alpha_{1}+ \beta {ENG_{ija}}+ \omega\hat{\epsilon_{ija}} + \delta_{a}+\gamma_{j} + W_{ija}'\rho + \mu_{ija}
\end{equation}
The estimation of $\omega$ will be our target.
```
#DWH Test
fit_st1 = wls( "eng ~ idvar + C(agearr) + C(age) + C(bpld) + female + black + asianpi + other + multi + hispdum", data=df_ind, weights=df_ind["perwt2"] ).fit(cov_type='cluster', cov_kwds={'groups': df_ind['bpld']}, use_t=False)
df_ind['Epsilon'] = fit_st1.resid
df_ind['eng_hat'] = fit_st1.predict(df_ind)
result_DWH_ind = pd.DataFrame({"Dependent variable St": list_table3_ind})
for var in list_table3_ind:
get_Durbin_Wu_Hausman_result(df_ind, var,result_DWH_ind )
fit_st1 = wls( "eng ~ idvar + C(agearr) + C(age) + C(bpld) + female + black + asianpi + other + multi + hispdum", data=df_mat, weights=df_mat["perwt2"] ).fit(cov_type='cluster', cov_kwds={'groups': df_mat['bpld']}, use_t=False)
df_mat['Epsilon'] = fit_st1.resid
df_mat['eng_hat'] = fit_st1.predict(df_mat)
result_DWH_mat = pd.DataFrame({"Dependent variable St": list_table3_mat})
for var in list_table3_mat:
get_Durbin_Wu_Hausman_result(df_mat, var,result_DWH_mat )
result_DWH = result_DWH_ind.append(result_DWH_mat)
result_DWH = get_variable_full_name_table3(result_DWH)
result_DWH = result_DWH.sort_index(ascending=True, sort_remaining =False)
get_asteris_and_coef(result_DWH,"Epsilon P Value", "Epsilon", "Epsilon")
result_DWH=result_DWH[["Epsilon","Epsilon SE"]]
print("Table 5 —Durbin Wu Hausman test result")
result_DWH
```
The test evaluate the endogeneity of English proficiency by verifying the economic and statistics significance of the coefficient for epsilon hat. If $\hat{\omega}$ is significant, it is implied that that endogenous regressors' effects on the estimates are significant, and an IV strategy is needed. Vice versa, if residual is not statistically significantly different from zero, so conclude that there is no endogeneity bias in the OLS estimates. Using DWH test, we discovered that with regard to quite a lot of outcomes, we have no statistical reasons to use English proficiency as the instrument. The exceptions are “Spouse English-speaking ability ordinal measure”, “Spouse years of schooling” , “Spouse age”, “Number of children living in same household”.
However, although the DWH test result is not satisfactory, we might still defend using this IV approach by arguing an "economics theory comes first" attitude. The statistical failure is a result caused by the imperfectness of the data on hand and possibly committing variable biases. As long as the economics reasoning is backed by a strong economics theory and intuition, we should feel confident employing the current IV.
### 6.2 Control for residence location
It is known that different states have different cultures and policies, and therefore different acceptance towards immigrants. Some states have an immigrant tradition such as Los Angeles and New York while some do not. It is possible that some locations of residence are more popular within non-English-speaking immigrants. For example, California has a lot of Asian immigrants because of the location and its immigrant heritage. Likewise, Mexican and South American immigrants are clustered in southern states such as Texas, New Mexico and Florida. States with a stronger immigrants heritage are easier for immigrants to assimilate. So the result might be biased. We therefore include a vector of dummy variables of state of residence and interaction between birthplace and state of residence into the model.
```
result_R2_ind = pd.DataFrame({"Dependent variable St": list_table3_ind})
fit_st1 = wls( "eng ~ idvar + C(agearr) + C(age) + C(bpld)+ C(statefip)*pwlinear + female + black + asianpi + other + multi + hispdum", data=df_ind, weights=df_ind["perwt2"] ).fit(cov_type='cluster', cov_kwds={'groups': df_ind['bpld']}, use_t=False)
df_ind['eng_hat'] = fit_st1.predict(df_ind)
for var in list_table3_ind:
get_ols_tsls_result_Robust2(df_ind, var, result_R2_ind)
result_R2_mat = pd.DataFrame({"Dependent variable St": list_table3_mat})
fit_st1 = wls( "eng ~ idvar + C(agearr) + C(age) + C(bpld)+ C(statefip)*pwlinear + female + black + asianpi + other + multi + hispdum", data=df_mat, weights=df_mat["perwt2"] ).fit(cov_type='cluster', cov_kwds={'groups': df_mat['bpld']}, use_t=False)
df_mat['eng_hat'] = fit_st1.predict(df_mat)
for var in list_table3_mat:
get_ols_tsls_result_Robust2(df_mat, var, result_R2_mat)
result_R2 = result_R2_ind.append(result_R2_mat)
result_R2 = get_variable_full_name_table3(result_R2)
result_R2 = result_R2.sort_index(ascending=True, sort_remaining =False)
get_asteris_and_coef(result_R2,"2SLS P Value", "2SLS", "English effect(2SLS)")
result_R2 = result_R2[["English effect(2SLS)", "2SLS SE"]]
print("Table 6 — English effect with control on the residence location (state level)")
result_R2
```
The result is displayed in table 6. We can observe similar outcomes from the baseline model presented in table 4_. One exception is the English effect on the variable “spouse has the same primary ancestry”. In the baseline model, the effect is -0.181 and insignificant at 10% level. When we control for the interaction term, effect is -0.225 and significant at 5% level.
### 6.3 English effect on outcome gap between immigrants and spouses
We extend the authors' analysis to other outcomes that we are interested in. We use the baseline model to investigate the gap of age, years of schooling, and income between spouses. These three gaps can be seen as a proxy for age closeness, education closeness and economic closeness between a couple. Apart from the bassline model, we also add controls for the immigrants’ level and their partners’ level of the dependent variables and observe the effect.
```
df_mat_R3 = df_mat
df_mat_R3['age'].replace(' ', np.nan, inplace=True)
df_mat_R3= df_mat_R3.dropna(subset=['age'])
df_mat_R3['spouseage'].replace(' ', np.nan, inplace=True)
df_mat_R3= df_mat_R3.dropna(subset=['spouseage'])
df_mat_R3['yrssch'].replace(' ', np.nan, inplace=True)
df_mat_R3= df_mat_R3.dropna(subset=['yrssch'])
df_mat_R3['spouseyrssch'].replace(' ', np.nan, inplace=True)
df_mat_R3= df_mat_R3.dropna(subset=['spouseyrssch'])
df_mat_R3['lnwagely'].replace(' ', np.nan, inplace=True)
df_mat_R3= df_mat_R3.dropna(subset=['lnwagely'])
df_mat_R3['spouselnwage'].replace(' ', np.nan, inplace=True)
df_mat_R3= df_mat_R3.dropna(subset=['spouselnwage'])
df_mat_R3["Wage_difference"] = abs(df_mat_R3["lnwagely"] - df_mat_R3["spouselnwage"])
df_mat_R3["Age_difference"] = abs(df_mat_R3["age"] - df_mat_R3["spouseage"])
df_mat_R3["Education_difference"] = abs(df_mat_R3["yrssch"] - df_mat_R3["spouseyrssch"])
list_mat_R3 = ["Wage_difference", "Age_difference", "Education_difference" ]
result_mat_R3 = pd.DataFrame({"Dependent variable St": list_mat_R3})
get_tsls_result_table4(df_mat_R3, "Wage_difference", result_mat_R3,"lnwagely + spouselnwage" )
get_tsls_result_table4(df_mat_R3, "Education_difference", result_mat_R3, "yrssch +spouseyrssch ")
get_tsls_result_table4(df_mat_R3, "Age_difference", result_mat_R3,"spouseage" )
get_asterisk(result_mat_R3,"2SLS P Value", "2SLS")
result_mat_R3["2SLS Parameter (Full Sample)"] = (result_mat_R3["2SLS Parameter"].astype(str) + result_mat_R3["2SLS Sig. level"])
result_mat_R3=result_mat_R3.rename(columns={ "Dependent variable St":"Dependent variable", "2SLS SE": "SE (Full Sample)"})
result_mat_R3 = result_mat_R3.set_index('Dependent variable')
result_mat_R3= result_mat_R3[["2SLS Parameter (Full Sample)", "SE (Full Sample)"]]
# subset female sample
df_mat_R3_female = df_mat_R3[df_mat_R3["female"] == 1]
result_mat_R3_female = pd.DataFrame({"Dependent variable St": list_mat_R3})
get_tsls_result_table4(df_mat_R3_female, "Wage_difference", result_mat_R3_female,"lnwagely + spouselnwage" )
get_tsls_result_table4(df_mat_R3_female, "Education_difference", result_mat_R3_female, "yrssch +spouseyrssch ")
get_tsls_result_table4(df_mat_R3_female, "Age_difference", result_mat_R3_female,"spouseage" )
get_asterisk(result_mat_R3_female,"2SLS P Value", "2SLS")
result_mat_R3_female["2SLS Parameter (Female Sample)"] = (result_mat_R3_female["2SLS Parameter"].astype(str) + result_mat_R3_female["2SLS Sig. level"])
result_mat_R3_female=result_mat_R3_female.rename(columns={ "Dependent variable St":"Dependent variable", "2SLS SE": "SE (Female Sample)"})
result_mat_R3_female = result_mat_R3_female.set_index('Dependent variable')
result_mat_R3_female= result_mat_R3_female[["2SLS Parameter (Female Sample)", "SE (Female Sample)"]]
# subset male sample
df_mat_R3_male = df_mat_R3[df_mat_R3["female"] == 0]
result_mat_R3_male = pd.DataFrame({"Dependent variable St": list_mat_R3})
get_tsls_result_table4(df_mat_R3_male, "Wage_difference", result_mat_R3_male,"lnwagely + spouselnwage" )
get_tsls_result_table4(df_mat_R3_male, "Education_difference", result_mat_R3_male, "yrssch +spouseyrssch ")
get_tsls_result_table4(df_mat_R3_male, "Age_difference", result_mat_R3_male,"spouseage" )
get_asterisk(result_mat_R3_male,"2SLS P Value", "2SLS")
result_mat_R3_male["2SLS Parameter (Male Sample)"] = (result_mat_R3_male["2SLS Parameter"].astype(str) + result_mat_R3_male["2SLS Sig. level"])
result_mat_R3_male=result_mat_R3_male.rename(columns={ "Dependent variable St":"Dependent variable", "2SLS SE": "SE (Male Sample)"})
result_mat_R3_male = result_mat_R3_male.set_index('Dependent variable')
result_mat_R3_male= result_mat_R3_male[["2SLS Parameter (Male Sample)", "SE (Male Sample)"]]
result_mat_R3 = pd.merge(result_mat_R3, result_mat_R3_female,
left_on=['Dependent variable'], right_on = ['Dependent variable'], how = 'left')
result_mat_R3 = pd.merge(result_mat_R3, result_mat_R3_male,
left_on=['Dependent variable'], right_on = ['Dependent variable'], how = 'left')
print("Table 7 — English effect on the outcome gap with spouse")
result_mat_R3
```
From the results we know that English level does not inflict significant effects on age and economic closeness. But it affects education closeness significantly. A simple explanation can be offered: English skills have a significant effect on communications and consequently exchanges of ideas. The cost of communication decreases if one’s English level is better. As a result, immigrants will consume more intelligence closeness.
Suppose the three kinds of closeness are among the goods in deciding the utility of marriage (other goods will be, for example, the appearance of the partner). To consume education or intelligence closeness, one has to pay for the effort of communication. An increase in English level lowers the cost for communication, so the relative price of intelligence level closeness decrease. If intelligence closeness is not a Giffen good, then more of it will be consumed. However when it comes to age closeness or economic closeness, the increase of English level has no effect on the cost of these two goods. That explains why the English skill effects on the age gap and income gap are not significant. We can also observe that the magnitude of English effect is much stronger for male than for female immigrants. The differential can probably be explained by different utility curves of marriage between females and males.
---
# 7. Conclusion
---
The benchmark investigates the relationships between English proficiency and some social aspects of an immigrants in the US. The authors choose the age of arrival as the instrument to control for omitted variables bias and reverse causality problems. Although some doubts call for attention regarding endogeneity issues (section 6.1), nevertheless we still have theoretical reasons to retain the IV approach proposed by the benchmark. The IV results pass a lot of robustness checks (section 5.2 & 6.2). It is clearly demonstrated that English proficiency causes increases in certain outcomes, especially some marital and fertility outcomes (section 5.1 & 6.3). However, we have seen the conceptual pitfalls of the benchmark.
The outcomes might not be satisfactory measurements for the level of social assimilation, despite being social outcomes. Some outcomes do not imply the degree of integration. That significantly limits the policy implications of the paper. We agree with most theses with the benchmark but differ in conceptual issues. As the aim of this replication paper is not to explore theories in immigration and population economics, we leave the project of defining good measurements for social assimilations to future researchers.
---
# 8. References
---
* **Bleakley, Hoyt, and Chin, Aimee**. 2010. Age at arrival, English proficiency, and social assimilation among US immigrants. *American Economic Journal: Applied Economics*, 2(1), 165-92.
* **Duncan, Brian, and Stephen J. Trejo**. 2007. “Ethnic Identification, Intermarriage, and Unmeasured Progress by Mexican Americans.” In *Mexican Immigration to the United States*, ed. George J. Borjas, 229–67. Chicago, IL: University of Chicago Press and National Bureau of Economic Research.
* **Funkhouser, Edward, and Fernando A. Ramos**. 1993. “The Choice of Migration Destination: Dominican and Cuban Immigrants to the Mainland United States and Puerto Rico.” *International Migration Review*, 27(3): 537–56.
* **Lenneberg, Eric**. 1967. *Biological foundations of language*. New York (N.Y.): Wiley.
* **Morris, Charles.**. 1967. *Foundations of the theory of signs* (International encyclopedia of unified science 1/2). University of Chicago press.
* **Sorenson, Ann Marie**. 1988. “The Fertility and Language Characteristics of Mexican-American and Non-Hispanic Husbands and Wives.” *Sociological Quarterly*, 29(1): 111–30.
* **Stevens, Gillian, and Gray Swicegood**. 1987. “The Linguistic Context of Ethnic Endogamy.” *American Sociological Review*, 52(1): 73–82.
* **Swicegood, Gray, Frank D. Bean, Elizabeth Hervey Stephen, and Wolfgang Opitz**. 1988. “Language Usage and Fertility in Mexican-Origin Population of the United States.” *Demography*, 25(1): 17–33.
* **Toussaint-Comeau, Maude, and Sherrie L. W. Rhine**. 2004. “Tenure Choice with Location Selection: The Case of Hispanic Neighborhoods in Chicago.” *Contemporary Economic Policy*, 22(1): 95–110.
* **Wittgenstein, Ludwig**. 1968. *Philosophical investigations* (Repr. ed.). Oxford: Blackwell.
| github_jupyter |
# 16 - Regression Discontinuity Design
We don't stop to think about it much, but it is impressive how smooth nature is. You can't grow a tree without first getting a bud, you can't teleport from one place to another, a wound takes its time to heal. Even in the social realm, smoothness seems to be the norm. You can't grow a business in one day, consistency and hard work are required to build wealth and it takes years before you learn how linear regression works. Under normal circumstances, nature is very cohesive and doesn't jump around much.
> When the intelligent and animal souls are held together in one embrace, they can be kept from separating.
\- Tao Te Ching, Lao Tzu.
Which means that **when we do see jumps and spikes, they are probably artificial** and often man-made situations. These events are usually accompanied by counterfactuals to the normal way of things: if a weird thing happens, this gives us some insight into what would have happened if nature was to work in a different way. Exploring these artificial jumps is at the core of Regression Discontinuity Design.

The basic setup goes like this. Imagine that you have a treatment variable \\(T\\) and potential outcomes \\(Y_0\\) and \\(Y_1\\). The treatment T is a discontinuous function of an observed running variable \\(R\\) such that
$
D_i = \mathcal{1}\{R_i>c\}
$
In other words, this is saying that treatment is zero when \\(R\\) is below a threshold \\(c\\) and one otherwise. This means that we get to observe \\(Y_1\\) when \\(R>c\\) and \\(Y_0\\) when \\(R<c\\). To wrap our head around this, think about the potential outcomes as 2 functions that we can't observe entirely. Both \\(Y_0(R)\\) and \\(Y_1(R)\\) are there, we just can't see that. The threshold acts as a switch that allows us to see one or the other of those function, but never both, much like in the image below:

The idea of regression discontinuity is to compare the outcome just above and just below the threshold to identify the treatment effect at the threshold. This is called a **sharp RD** design, since the probability of getting the treatment jumps from 0 to 1 at the threshold, but we could also think about a **fuzzy RD** design, where the probability also jumps, but is a less dramatic manner.
## Is Alcohol Killing You?
A very relevant public policy question is what should be the minimal drinking age. Most countries, Brazil included, set it to be 18 year, but in the US (most states) it is currently 21. So, is it the case that the US is being overly prudent and that they should lower their minimal drinking age? Or is it the case that other countries should make their legal drinking age higher?
One way to look at this question is from a [mortality rate perspective (Carpenter and Dobkin, 2009)](https://www.aeaweb.org/articles?id=10.1257/app.1.1.164). From the public policy standpoint, one could argue that we should lower the mortality rate as much as possible. If alcohol consumption increases the mortality rate by a lot, we should avoid lowering the minimum drinking age. This would be consistent with the objective of lowering deaths caused by alcohol consumption.
To estimate the impacts of alcohol on death, we could use the fact that legal drinking age imposes a discontinuity on nature. In the US, those just under 21 years don't drink (or drink much less) while those just older than 21 do drink. This means that the probability of drinking jumps at 21 years and that is something we can explore with an RDD.
```
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
from matplotlib import style
from matplotlib import pyplot as plt
import seaborn as sns
import statsmodels.formula.api as smf
%matplotlib inline
style.use("fivethirtyeight")
```
To do so we can grab some mortality data aggregated by age. Each row is the average age of a group of people and the average mortality by all causes (`all`), by moving vehicle accident (`mva`) and by suicide (`suicide`).
```
drinking = pd.read_csv("./data/drinking.csv")
drinking.head()[["agecell", "all", "mva", "suicide"]]
```
Just to aid visibility (and for another important reason we will see later) we will centralize the running variable `agecell` at the threshold 21.
```
drinking["agecell"] -= 21
```
If we plot the multiple outcome variables (`all`, `mva`, `suicide`) with the runing variable on the x axis, we get some visual cue about some sort of jump in mortality as we cross the legal drinking age.
```
plt.figure(figsize=(8,8))
ax = plt.subplot(3,1,1)
drinking.plot.scatter(x="agecell", y="all", ax=ax)
plt.title("Death Cause by Age (Centered at 0)")
ax = plt.subplot(3,1,2, sharex=ax)
drinking.plot.scatter(x="agecell", y="mva", ax=ax)
ax = plt.subplot(3,1,3, sharex=ax)
drinking.plot.scatter(x="agecell", y="suicide", ax=ax);
```
There are some cues, but we need more than that. What exactly is the effect of drinking on mortality at the threshold? And what is the standard error on that estimate?
## RDD Estimation
The key assumption that RDD relies on is the smoothness of the potential outcome at the threshold. Formally, the limits of the potential outcomes as the running variable approaches the threshold from the right and from the left should be the same.
$$
\lim_{r \to c^-} E[Y_{ti}|R_i=r] = \lim_{r \to c^+} E[Y_{ti}|R_i=r]
$$
If this holds true, we can find the causal effect at the threshold
$$
\begin{align}
\lim_{r \to c^+} E[Y_{ti}|R_i=r] - \lim_{r \to c^-} E[Y_{ti}|R_i=r]=&\lim_{r \to c^+} E[Y_{1i}|R_i=r] - \lim_{r \to c^-} E[Y_{0i}|R_i=r] \\
=& E[Y_{1i}|R_i=r] - E[Y_{0i}|R_i=r] \\
=& E[Y_{1i} - Y_{0i}|R_i=r]
\end{align}
$$
This is, in its own way, a sort of Local Average Treatment Effect (LATE), since we can only know it at the threshold. In this setting, we can think of RDD as a local randomized trial. For those at the threshold, the treatment could have gone either way and, by chance, some people fell below the threshold, and some people fell above. In our example, at the same point in time, some people are just above 21 years and some people are just below 21. What determines this is if someone was born some days later or not, which is pretty random. For this reason, RDD provides a very compelling causal story. It is not the golden standard of RCT, but it is close.
Now, to estimate the treatment effect at the threshold, all we need to do is estimate both of the limits in the formula above and compare them. The simplest way to do that is by running a linear regression

To make it work, we interact a dummy for being above the threshold with the running variable
$
y_i = \beta_0 + \beta_1 r_i + \beta_2 \mathcal{1}\{r_i>c\} + \beta_3 \mathcal{1}\{r_i>c\} r_i
$
Essentially, this is the same as fitting a linear regression above the threshold and another below it. The parameter \\(\beta_0\\) is the intercept of the regression below the threshold and \\(\beta_0+\beta_2\\) is the intercept for the regression above the threshold.
Here is where the trick of centering the running variable at the threshold comes into play. After this pre-processing step, the threshold becomes zero. This causes the intercept \\(\beta_0\\) to be the predicted value at the threshold, for the regression below it. In other words, \\(\beta_0=\lim_{r \to c^-} E[Y_{ti}|R_i=r]\\). By the same reasoning, \\(\beta_0+\beta_2\\) is the limit of the outcome from above. Wich means, that
$
\lim_{r \to c^+} E[Y_{ti}|R_i=r] - \lim_{r \to c^-} E[Y_{ti}|R_i=r]=\beta_2=E[ATE|R=c]
$
Here is what this looks like in code for the case where we want to estimate the effect of alcohol consumption on death by all causes at 21 years.
```
rdd_df = drinking.assign(threshold=(drinking["agecell"] > 0).astype(int))
model = smf.wls("all~agecell*threshold", rdd_df).fit()
model.summary().tables[1]
```
This model is telling us that mortality increases by 7.6627 points with the consumption of alcohol. Another way of putting this is that alcohol increases the chance of death by all causes by 8% ((7.6627+93.6184)/93.6184). Notice that this also gives us standard errors for our causal effect estimate. In this case, the effect is statistically significant, since the p-value is below 0.01.
If we want to verify this model visually, we can show the predicted values on the data that we have. You can see that it is as though we had 2 regression models: one for those above the threshold and one for below it.
```
ax = drinking.plot.scatter(x="agecell", y="all", color="C0")
drinking.assign(predictions=model.fittedvalues).plot(x="agecell", y="predictions", ax=ax, color="C1")
plt.title("Regression Discontinuity");
```
If we do the same for the other causes, this is what we get.
```
plt.figure(figsize=(8,8))
for p, cause in enumerate(["all", "mva", "suicide"], 1):
ax = plt.subplot(3,1,p)
drinking.plot.scatter(x="agecell", y=cause, ax=ax)
m = smf.wls(f"{cause}~agecell*threshold", rdd_df).fit()
ate_pct = 100*((m.params["threshold"] + m.params["Intercept"])/m.params["Intercept"] - 1)
drinking.assign(predictions=m.fittedvalues).plot(x="agecell", y="predictions", ax=ax, color="C1")
plt.title(f"Impact of Alcohol on Death: {np.round(ate_pct, 2)}%")
plt.tight_layout()
```
RDD is telling us that alcohol increases the chance of deth by suicide and car accidents by 15%, wich is a pretty significant ammount. These results are compelling arguments to not lower the drinking age, if we want to minimize mortality rates.
### Kernel Weighting
Regression Discontinuity relies heavily on the extrapolations properties of linear regression. Since we are looking at the values at the beginning and end of 2 regression lines, we better get those limits right. What can happen is that regression might focus too much on fitting the other data points at the cost of a poor fit at the threshold. If this happens, we might get the wrong measure of the treatment effect.
One way to solve this is to give higher weights for the points that are closer to the threshold. There are many ways to do this, but a popular one is to reweight the samples with the **triangular kernel**
$
K(R, c, h) = \mathcal{1}\{|R-c| \leq h\} * \bigg(1-\frac{|R-c|}{h}\bigg)
$
The first part of this kernel is an indicator function to whether we are close to the threshold. How close? This is determined by a bandwidth parameter \\(h\\). The second part of this kernel is a weighting function. As we move away from the threshold, the weights get smaller and smaller. These weights are divided by the bandwidth. If the bandwidth is large, the weights get smaller at a slower rate. If the bandwidth is small, the weights quickly go to zero.
To make it easier to understand, here is what the weights look like for this kernel applied to our problem. I've set the bandwidth to be 1 here, meaning we will only consider data from people that are no older than 22 years and no younger than 20 years.
```
def kernel(R, c, h):
indicator = (np.abs(R-c) <= h).astype(float)
return indicator * (1 - np.abs(R-c)/h)
plt.plot(drinking["agecell"], kernel(drinking["agecell"], c=0, h=1))
plt.xlabel("agecell")
plt.ylabel("Weight")
plt.title("Kernel Weight by Age");
```
If we apply these weights to our original problem, the impact of alcohol gets bigger, at least for all causes. It jumps from 7.6627 to 9.7004. The result remains very significant. Also, notice that I'm using `wls` instead of `ols`
```
model = smf.wls("all~agecell*threshold", rdd_df,
weights=kernel(drinking["agecell"], c=0, h=1)).fit()
model.summary().tables[1]
ax = drinking.plot.scatter(x="agecell", y="all", color="C0")
drinking.assign(predictions=model.fittedvalues).plot(x="agecell", y="predictions", ax=ax, color="C1")
plt.title("Regression Discontinuity (Local Regression)");
```
And here is what it looks like for the other causes of death. Notice how the regression on the right is more negatively sloped since it disconsiders the right most points.
```
plt.figure(figsize=(8,8))
weights = kernel(drinking["agecell"], c=0, h=1)
for p, cause in enumerate(["all", "mva", "suicide"], 1):
ax = plt.subplot(3,1,p)
drinking.plot.scatter(x="agecell", y=cause, ax=ax)
m = smf.wls(f"{cause}~agecell*threshold", rdd_df, weights=weights).fit()
ate_pct = 100*((m.params["threshold"] + m.params["Intercept"])/m.params["Intercept"] - 1)
drinking.assign(predictions=m.fittedvalues).plot(x="agecell", y="predictions", ax=ax, color="C1")
plt.title(f"Impact of Alcohol on Death: {np.round(ate_pct, 2)}%")
plt.tight_layout()
```
With the exception of suicide, it looks like adding the kernel weight made the negative impact on alcohol bigger. Once again, if we want to minimize the death rate, we should NOT recommend lowering the legal drinking age, since there is a clear impact of alcohol on the death rates.
This simple case covers what happens when regression discontinuity design works perfectly. Next, we will see some diagnostics that we should run in order to check how much we can trust RDD and talk about a topic that is very dear to our heart: the effect of education on earnings.
## Sheepskin Effect and Fuzzy RDD
When it comes to the effect of education on earnings, there are two major views in economics. The first one is the widely known argument that education increases human capital, increasing productivity and thus, earnings. In this view, education actually changes you for the better. Another view is that education is simply a signaling mechanism. It just puts you through all these hard tests and academic tasks. If you can make it, it signals to the market that you are a good employee. In this way, education doesn't make you more productive. It only tells the market how productive you have always been. What matters here is the diploma. If you have it, you will be paid more. We refer to this as the **sheepskin effect**, since diplomas were printed in sheepskin in the past.
To test this hypothesis, [Clark and Martorell](https://faculty.smu.edu/millimet/classes/eco7321/papers/clark%20martorell%202014.pdf) used regression discontinuity to measure the effect of graduating 12th grade on earnings. In order to do that, they had to think about some running variable where students that fall above it graduate and those who fall below it, don't. They found such data in the Texas education system.
In order to graduate in Texas, one has to pass an exam. Testing starts at 10th grade and students can do it multiple times, but eventually, they face a last chance exam at the end of 12th grade. The idea was to get data from students who took those last chance exams and compare those that had barely failed it to those that barely passed it. These students will have very similar human capital, but different signaling credentials. Namely, those that barely passed it, will receive a diploma.
```
sheepskin = pd.read_csv("./data/sheepskin.csv")[["avgearnings", "minscore", "receivehsd", "n"]]
sheepskin.head()
```
One again, this data is grouped by the running variable. It contains not only the running variable (`minscore`, already centered at zero) and the outcome (`avgearnings`), but it also has the probability of receiving a diploma in that score cell and the size of the call (`n`). So, for example, out of the 12 students in the cell -30 below the score threshold, only 5 were able to get the diploma (12 * 0,416).
This means that there is some slippage in the treatment assignment. Some students that are below the passing threshold managed to get the diploma anyway. Here, the regression discontinuity is **fuzzy**, rather than sharp. Notice how the probability of getting the diploma doesn't jump from zero to one at the threshold. But it does jump from something like 50% to 90%.
```
sheepskin.plot.scatter(x="minscore", y="receivehsd", figsize=(10,5))
plt.xlabel("Test Scores Relative to Cut off")
plt.ylabel("Fraction Receiving Diplomas")
plt.title("Last-chance Exams");
```
We can think of fuzzy RD as a sort of non compliance. Passing the threshold should make everyone receive the diploma, but some students, the never takers, don't get it. Likewise, being below the threshold should prevent you from getting a diploma, but some students, the allways takers, manage to get it anyway.
Just like when we have the potential outcome, we have the potential treatment status in this situation. \\(T_1\\) is the treatment everyone would have received had they been above the threshold. \\(T_0\\) is the treatment everyone would have received had they been below the threshold. As you've might have noticed, we can think of the **threshold as an Instrumental Variable**. Just as in IV, if we naively estimate the treatment effect, it will be biased towards zero.

The probability of treatment being less than one, even above the threshold, makes the outcome we observe less than the true potential outcome \\(Y_1\\). By the same token, the outcome we observe below the threshold is higher than the true potential outcome \\(Y_0\\). This makes it look like the treatment effect at the threshold is smaller than it actually is and we will have to use IV techniques to correct for that.
Just like when we've assumed smoothness on the potential outcome, we now assume it for the potential treatment. Also, we need to assume monotonicity, just like in IV. In case you don't remember, it states that \\(T_{i1}>T_{i0} \ \forall i\\). This means that crossing the threshold from the left to the right only increases your chance of getting a diploma (or that there are no defiers). With these 2 assumptions, we have a Wald Estimator for LATE.
$$
\dfrac{\lim_{r \to c^+} E[Y_i|R_i=r] - \lim_{r \to c^-} E[Y_i|R_i=r]}{\lim_{r \to c^+} E[T_i|R_i=r] - \lim_{r \to c^-} E[T_i|R_i=r]} = E[Y_{1i} - Y_{0i} | T_{1i} > T_{0i}, R_i=c]
$$
Notice how this is a local estimate in two senses. First, it is local because it only gives the treatment effect at the threshold \\(c\\). This is the RD locality. Second, it is local because it only estimates the treatment effect for the compliers. This is the IV locality.
To estimate this, we will use 2 linear regression. The numerator can be estimated just like we've done before. To get the denominator, we simply replace the outcome with the treatment. But first, let's talk about a sanity check we need to run to make sure we can trust our RDD estimates.
### The McCrary Test
One thing that could break our RDD argument is if people can manipulate where they stand at the threshold. In the sheepskin example this could happen if students just below the threshold found a way around the system to increase their test score by just a bit. Another example is when you need to be below a certain income level to get a government benefit. Some families might lower their income on purpose, just to be just eligible for the program.
In these sorts of situations, we tend to see a phenomenon called bunching on the density of the running variable. This means that we will have a lot of entities just above or just below the threshold. To check for that, we can plot the density function of the running variable and see if there are any spikes around the threshold. For our case, the density is given by the `n` column in our data.
```
plt.figure(figsize=(8,8))
ax = plt.subplot(2,1,1)
sheepskin.plot.bar(x="minscore", y="n", ax=ax)
plt.title("McCrary Test")
plt.ylabel("Smoothness at the Threshold")
ax = plt.subplot(2,1,2, sharex=ax)
sheepskin.replace({1877:1977, 1874:2277}).plot.bar(x="minscore", y="n", ax=ax)
plt.xlabel("Test Scores Relative to Cut off")
plt.ylabel("Spike at the Threshold");
```
The first plot shows how our data density looks like. As we can see, there are no spikes around the threshold, meaning there is no bunching. Students are not manipulating where they fall on the threshold. Just for illustrative purposes, the second plot shows what bunching would look like if students could manipulate where they fall on the threshold. We would see a spike in the density for the cells just above the threshold, since many students would be on that cell, barely passing the exam.
Getting this out of the way, we can go back to estimate the sheepskin effect. As I've said before, the numerator of the Wald estimator can be estimated just like we did in the Sharp RD. Here, we will use as weight the kernel with a bandwidth of 15. Since we also have the cell size, we will multiply the kernel by the sample size to get a final weight for the cell.
```
sheepsking_rdd = sheepskin.assign(threshold=(sheepskin["minscore"]>0).astype(int))
model = smf.wls("avgearnings~minscore*threshold",
sheepsking_rdd,
weights=kernel(sheepsking_rdd["minscore"], c=0, h=15)*sheepsking_rdd["n"]).fit()
model.summary().tables[1]
```
This is telling us that the effect of a diploma is -97.7571, but this is not statistically significant (P-value of 0.5). If we plot these results, we get a very continuous line at the threshold. More educated people indeed make more money, but there isn't a jump at the point where they receive the 12th grade diploma. This is an argument in favor of the view that says that education increases earnings by making people more productive, rather than being just a signal to the marker. In other words, there is no sheepskin effect.
```
ax = sheepskin.plot.scatter(x="minscore", y="avgearnings", color="C0")
sheepskin.assign(predictions=model.fittedvalues).plot(x="minscore", y="predictions", ax=ax, color="C1", figsize=(8,5))
plt.xlabel("Test Scores Relative to Cutoff")
plt.ylabel("Average Earnings")
plt.title("Last-chance Exams");
```
However, as we know from the way non compliance bias works, this result is biased towards zero. To correct for that, we need to scale it by the first stage and get the Wald estimator. Unfortunately, there isn't a good Python implementation for this, so we will have to do it manually and use bootstrap to get the standard errors.
The code below runs the numerator of the Wald estimator just like we did before and also constructs the denominator by replacing the target variable with the treatment variable `receivehsd`. The final step just divides the numerator by the denominator.
```
def wald_rdd(data):
weights=kernel(data["minscore"], c=0, h=15)*data["n"]
denominator = smf.wls("receivehsd~minscore*threshold", data, weights=weights).fit()
numerator = smf.wls("avgearnings~minscore*threshold", data, weights=weights).fit()
return numerator.params["threshold"]/denominator.params["threshold"]
from joblib import Parallel, delayed
np.random.seed(45)
bootstrap_sample = 1000
ates = Parallel(n_jobs=4)(delayed(wald_rdd)(sheepsking_rdd.sample(frac=1, replace=True))
for _ in range(bootstrap_sample))
ates = np.array(ates)
```
With the bootstrap samples, we can plot the distribution of ATEs and see where the 95% confidence interval is.
```
sns.distplot(ates, kde=False)
plt.vlines(np.percentile(ates, 2.5), 0, 100, linestyles="dotted")
plt.vlines(np.percentile(ates, 97.5), 0, 100, linestyles="dotted", label="95% CI")
plt.title("ATE Bootstrap Distribution")
plt.xlim([-10000, 10000])
plt.legend();
```
As you can see, even when we scale the effect by the first stage, it is still not statistically different from zero. This means that education doesn't increase earnings by a simple sheepskin effect, but rather by increasing one's productivity.
## Key Ideas
We learned how to take advantage of artificial discontinuities to estimate causal effects. The idea is that we will have some artificial threshold that makes the probability of treatment jump. One example that we saw was how age makes the probability of drinking jump at 21 years. We could use that to estimate the impact of drinking on mortality rate. We use the fact that very close to the threshold, we have something close to a randomized trial. Entities very close to the threshold could have gone either way and what determines where they've landed is essentially random. With this, we can compare those just above and just below to get the treatment effect. We saw how we could do that with weighted linear regression using a kernel and how this even gave us, for free, standard errors for our ATE.
Then, we look at what would happen in the fuzzy RD design, where we have non compliance. We saw how we could approach the situation much like we did with IV.
## References
I like to think of this entire book as a tribute to Joshua Angrist, Alberto Abadie and Christopher Walters for their amazing Econometrics class. Most of the ideas here are taken from their classes at the American Economic Association. Watching them is what is keeping me sane during this tough year of 2020.
* [Cross-Section Econometrics](https://www.aeaweb.org/conference/cont-ed/2017-webcasts)
* [Mastering Mostly Harmless Econometrics](https://www.aeaweb.org/conference/cont-ed/2020-webcasts)
I'll also like to reference the amazing books from Angrist. They have shown me that Econometrics, or 'Metrics as they call it, is not only extremely useful but also profoundly fun.
* [Mostly Harmless Econometrics](https://www.mostlyharmlesseconometrics.com/)
* [Mastering 'Metrics](https://www.masteringmetrics.com/)
Other important reference is Miguel Hernan and Jamie Robins' book. It has been my trustworthy companion in the most thorny causal questions I had to answer.
* [Causal Inference Book](https://www.hsph.harvard.edu/miguel-hernan/causal-inference-book/)

## Contribute
Causal Inference for the Brave and True is an open-source material on causal inference, the statistics of science. It uses only free software, based in Python. Its goal is to be accessible monetarily and intellectually.
If you found this book valuable and you want to support it, please go to [Patreon](https://www.patreon.com/causal_inference_for_the_brave_and_true). If you are not ready to contribute financially, you can also help by fixing typos, suggesting edits or giving feedback on passages you didn't understand. Just go to the book's repository and [open an issue](https://github.com/matheusfacure/python-causality-handbook/issues). Finally, if you liked this content, please share it with others who might find it useful and give it a [star on GitHub](https://github.com/matheusfacure/python-causality-handbook/stargazers).
| github_jupyter |
**Chapter 19 – Training and Deploying TensorFlow Models at Scale**
_This notebook contains all the sample code and solutions to the exercises in chapter 19._
<table align="left">
<td>
<a href="https://colab.research.google.com/github/ageron/handson-ml3/blob/main/19_training_and_deploying_at_scale.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
</td>
<td>
<a target="_blank" href="https://kaggle.com/kernels/welcome?src=https://github.com/ageron/handson-ml3/blob/main/19_training_and_deploying_at_scale.ipynb"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" /></a>
</td>
</table>
# WORK IN PROGRESS
<img src="https://freesvg.org/img/Lavori-in-corso.png" width="200" />
**I'm still working on updating this chapter to the 3rd edition. Please come back in a few weeks.**
# Setup
This project requires Python 3.7 or above:
```
import sys
assert sys.version_info >= (3, 7)
```
It also requires Scikit-Learn ≥ 1.0.1:
```
import sklearn
assert sklearn.__version__ >= "1.0.1"
```
And TensorFlow ≥ 2.8:
```
import tensorflow as tf
assert tf.__version__ >= "2.8.0"
```
As we did in earlier chapters, let's define the default font sizes to make the figures prettier:
```
import matplotlib.pyplot as plt
plt.rc('font', size=14)
plt.rc('axes', labelsize=14, titlesize=14)
plt.rc('legend', fontsize=14)
plt.rc('xtick', labelsize=10)
plt.rc('ytick', labelsize=10)
```
And let's create the `images/deploy` folder (if it doesn't already exist), and define the `save_fig()` function which is used through this notebook to save the figures in high-res for the book:
```
from pathlib import Path
IMAGES_PATH = Path() / "images" / "deploy"
IMAGES_PATH.mkdir(parents=True, exist_ok=True)
def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
path = IMAGES_PATH / f"{fig_id}.{fig_extension}"
if tight_layout:
plt.tight_layout()
plt.savefig(path, format=fig_extension, dpi=resolution)
```
This chapter can be very slow without a GPU, so let's make sure there's one, or else issue a warning:
```
if not tf.config.list_physical_devices('GPU'):
print("No GPU was detected. Neural nets can be very slow without a GPU.")
if "google.colab" in sys.modules:
print("Go to Runtime > Change runtime and select a GPU hardware "
"accelerator.")
if "kaggle_secrets" in sys.modules:
print("Go to Settings > Accelerator and select GPU.")
```
If you are running this notebook in Colab or Kaggle, let's install TensorFlow Server:
```
if "google.colab" in sys.modules or "kaggle_secrets" in sys.modules:
!echo "deb http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal" > /etc/apt/sources.list.d/tensorflow-serving.list
!curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | apt-key add -
!apt update && apt-get install -y tensorflow-model-server
%pip install -q -U tensorflow-serving-api
```
# Deploying TensorFlow models to TensorFlow Serving (TFS)
We will use the REST API or the gRPC API.
## Save/Load a `SavedModel`
```
(X_train_full, y_train_full), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
X_train_full = X_train_full[..., np.newaxis].astype(np.float32) / 255.
X_test = X_test[..., np.newaxis].astype(np.float32) / 255.
X_valid, X_train = X_train_full[:5000], X_train_full[5000:]
y_valid, y_train = y_train_full[:5000], y_train_full[5000:]
X_new = X_test[:3]
np.random.seed(42)
tf.random.set_seed(42)
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=[28, 28, 1]),
tf.keras.layers.Dense(100, activation="relu"),
tf.keras.layers.Dense(10, activation="softmax")
])
model.compile(loss="sparse_categorical_crossentropy",
optimizer=tf.keras.optimizers.SGD(learning_rate=1e-2),
metrics=["accuracy"])
model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))
model.predict(X_new).round(2)
model_version = "0001"
model_name = "my_mnist_model"
model_path = Path() / model_name / model_version
model_path
!rm -rf {model_name}
tf.saved_model.save(model, str(model_path))
```
Let's define a `tree()` function to view the structure of the `my_mnist_model` directory:
```
def tree(path, level=0, indent=4):
if level == 0:
print(f"{path}/")
level += 1
sub_paths = sorted(path.iterdir())
sub_dirs = [sub_path for sub_path in sub_paths if sub_path.is_dir()]
filepaths = [sub_path for sub_path in sub_paths if not sub_path in sub_dirs]
indent_str = " " * indent * level
for sub_dir in sub_dirs:
print(f"{indent_str}{sub_dir.name}/")
tree(sub_dir, level + 1, indent)
for filepath in filepaths:
print(f"{indent_str}{filepath.name}")
tree(model_path.parent)
!saved_model_cli show --dir {model_path}
!saved_model_cli show --dir {model_path} --tag_set serve
!saved_model_cli show --dir {model_path} --tag_set serve \
--signature_def serving_default
!saved_model_cli show --dir {model_path} --all
```
Let's write the new instances to a `npy` file so we can pass them easily to our model:
```
np.save("my_mnist_tests.npy", X_new)
input_name = model.input_names[0]
input_name
```
And now let's use `saved_model_cli` to make predictions for the instances we just saved:
```
!saved_model_cli run --dir {model_path} --tag_set serve \
--signature_def serving_default \
--inputs {input_name}=my_mnist_tests.npy
np.round(
[[1.14172166e-04, 1.51857336e-07, 9.79080913e-04, 2.77538411e-03,
3.75553282e-06, 7.66718149e-05, 3.91490929e-08, 9.95566308e-01,
5.34432293e-05, 4.30987304e-04],
[8.14584550e-04, 3.54881959e-05, 9.88290966e-01, 7.04165967e-03,
1.27466748e-07, 2.31963830e-04, 2.55776616e-03, 9.73469416e-10,
1.02734682e-03, 8.74494361e-08],
[4.42889832e-05, 9.70350444e-01, 9.02883708e-03, 2.26117787e-03,
4.85437602e-04, 2.87237833e-03, 2.26676138e-03, 8.35481752e-03,
4.03870409e-03, 2.97143910e-04]], 2)
```
## TensorFlow Serving
Install [Docker](https://docs.docker.com/install/) if you don't have it already. Then run:
```bash
docker pull tensorflow/serving
export ML_PATH=$HOME/ml # or wherever this project is
docker run -it --rm -p 8500:8500 -p 8501:8501 \
-v "$ML_PATH/my_mnist_model:/models/my_mnist_model" \
-e MODEL_NAME=my_mnist_model \
tensorflow/serving
```
Once you are finished using it, press Ctrl-C to shut down the server.
Alternatively, if `tensorflow_model_server` is installed (e.g., if you are running this notebook in Colab), then the following 3 cells will start the server:
```
os.environ["MODEL_DIR"] = str(model_path.absolute().parent)
%%bash --bg
nohup tensorflow_model_server \
--rest_api_port=8501 \
--model_name=my_mnist_model \
--model_base_path="${MODEL_DIR}" >server.log 2>&1
!tail server.log
import json
input_data_json = json.dumps({
"signature_name": "serving_default",
"instances": X_new.tolist(),
})
repr(input_data_json)[:1500] + "..."
```
Now let's use TensorFlow Serving's REST API to make predictions:
```
import requests
SERVER_URL = 'http://localhost:8501/v1/models/my_mnist_model:predict'
response = requests.post(SERVER_URL, data=input_data_json)
response.raise_for_status() # raise an exception in case of error
response = response.json()
response.keys()
y_proba = np.array(response["predictions"])
y_proba.round(2)
```
### Using the gRPC API
```
from tensorflow_serving.apis.predict_pb2 import PredictRequest
request = PredictRequest()
request.model_spec.name = model_name
request.model_spec.signature_name = "serving_default"
input_name = model.input_names[0]
request.inputs[input_name].CopyFrom(tf.make_tensor_proto(X_new))
import grpc
from tensorflow_serving.apis import prediction_service_pb2_grpc
channel = grpc.insecure_channel('localhost:8500')
predict_service = prediction_service_pb2_grpc.PredictionServiceStub(channel)
response = predict_service.Predict(request, timeout=10.0)
response
```
Convert the response to a tensor:
```
output_name = model.output_names[0]
outputs_proto = response.outputs[output_name]
y_proba = tf.make_ndarray(outputs_proto)
y_proba.round(2)
```
Or to a NumPy array if your client does not include the TensorFlow library:
```
output_name = model.output_names[0]
outputs_proto = response.outputs[output_name]
shape = [dim.size for dim in outputs_proto.tensor_shape.dim]
y_proba = np.array(outputs_proto.float_val).reshape(shape)
y_proba.round(2)
```
## Deploying a new model version
```
np.random.seed(42)
tf.random.set_seed(42)
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=[28, 28, 1]),
tf.keras.layers.Dense(50, activation="relu"),
tf.keras.layers.Dense(50, activation="relu"),
tf.keras.layers.Dense(10, activation="softmax")
])
model.compile(loss="sparse_categorical_crossentropy",
optimizer=tf.keras.optimizers.SGD(learning_rate=1e-2),
metrics=["accuracy"])
history = model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))
model_version = "0002"
model_name = "my_mnist_model"
model_path = Path() / model_name / model_version
model_path
tf.saved_model.save(model, str(model_path))
tree(model_path.parent)
```
**Warning**: You may need to wait a minute before the new model is loaded by TensorFlow Serving.
```
import requests
SERVER_URL = 'http://localhost:8501/v1/models/my_mnist_model:predict'
response = requests.post(SERVER_URL, data=input_data_json)
response.raise_for_status()
response = response.json()
response.keys()
y_proba = np.array(response["predictions"])
y_proba.round(2)
```
# Deploy the model to Google Cloud AI Platform
Follow the instructions in the book to deploy the model to Google Cloud AI Platform, download the service account's private key and save it to the `my_service_account_private_key.json` in the project directory. Also, update the `project_id`:
```
project_id = "onyx-smoke-242003"
import googleapiclient.discovery
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "my_service_account_private_key.json"
model_id = "my_mnist_model"
model_path = "projects/{}/models/{}".format(project_id, model_id)
model_path += "/versions/v0001/" # if you want to run a specific version
ml_resource = googleapiclient.discovery.build("ml", "v1").projects()
def predict(X):
input_data_json = {"signature_name": "serving_default",
"instances": X.tolist()}
request = ml_resource.predict(name=model_path, body=input_data_json)
response = request.execute()
if "error" in response:
raise RuntimeError(response["error"])
return np.array([pred[output_name] for pred in response["predictions"]])
Y_probas = predict(X_new)
Y_probas.round(2)
```
# Using GPUs
**Note**: `tf.test.is_gpu_available()` is deprecated. Instead, please use `tf.config.list_physical_devices('GPU')`.
```
#tf.test.is_gpu_available() # deprecated
tf.config.list_physical_devices('GPU')
tf.test.gpu_device_name()
tf.test.is_built_with_cuda()
from tensorflow.python.client.device_lib import list_local_devices
devices = list_local_devices()
devices
```
# Distributed Training
```
tf.keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
def create_model():
return tf.keras.Sequential([
tf.keras.layers.Conv2D(filters=64, kernel_size=7, activation="relu",
padding="same", input_shape=[28, 28, 1]),
tf.keras.layers.MaxPooling2D(pool_size=2),
tf.keras.layers.Conv2D(filters=128, kernel_size=3, activation="relu",
padding="same"),
tf.keras.layers.Conv2D(filters=128, kernel_size=3, activation="relu",
padding="same"),
tf.keras.layers.MaxPooling2D(pool_size=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(units=64, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(units=10, activation='softmax'),
])
batch_size = 100
model = create_model()
model.compile(loss="sparse_categorical_crossentropy",
optimizer=tf.keras.optimizers.SGD(learning_rate=1e-2),
metrics=["accuracy"])
model.fit(X_train, y_train, epochs=10,
validation_data=(X_valid, y_valid), batch_size=batch_size)
tf.keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
distribution = tf.distribute.MirroredStrategy()
# Change the default all-reduce algorithm:
#distribution = tf.distribute.MirroredStrategy(
# cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
# Specify the list of GPUs to use:
#distribution = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
# Use the central storage strategy instead:
#distribution = tf.distribute.experimental.CentralStorageStrategy()
#if IS_COLAB and "COLAB_TPU_ADDR" in os.environ:
# tpu_address = "grpc://" + os.environ["COLAB_TPU_ADDR"]
#else:
# tpu_address = ""
#resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu_address)
#tf.config.experimental_connect_to_cluster(resolver)
#tf.tpu.experimental.initialize_tpu_system(resolver)
#distribution = tf.distribute.experimental.TPUStrategy(resolver)
with distribution.scope():
model = create_model()
model.compile(loss="sparse_categorical_crossentropy",
optimizer=tf.keras.optimizers.SGD(learning_rate=1e-2),
metrics=["accuracy"])
batch_size = 100 # must be divisible by the number of workers
model.fit(X_train, y_train, epochs=10,
validation_data=(X_valid, y_valid), batch_size=batch_size)
model.predict(X_new)
```
Custom training loop:
```
tf.keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
K = tf.keras.backend
distribution = tf.distribute.MirroredStrategy()
with distribution.scope():
model = create_model()
optimizer = tf.keras.optimizers.SGD()
with distribution.scope():
dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).repeat().batch(batch_size)
input_iterator = distribution.make_dataset_iterator(dataset)
@tf.function
def train_step():
def step_fn(inputs):
X, y = inputs
with tf.GradientTape() as tape:
Y_proba = model(X)
loss = K.sum(tf.keras.losses.sparse_categorical_crossentropy(y, Y_proba)) / batch_size
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
return loss
per_replica_losses = distribution.experimental_run(step_fn, input_iterator)
mean_loss = distribution.reduce(tf.distribute.ReduceOp.SUM,
per_replica_losses, axis=None)
return mean_loss
n_epochs = 10
with distribution.scope():
input_iterator.initialize()
for epoch in range(n_epochs):
print("Epoch {}/{}".format(epoch + 1, n_epochs))
for iteration in range(len(X_train) // batch_size):
print("\rLoss: {:.3f}".format(train_step().numpy()), end="")
print()
```
## Training across multiple servers
A TensorFlow cluster is a group of TensorFlow processes running in parallel, usually on different machines, and talking to each other to complete some work, for example training or executing a neural network. Each TF process in the cluster is called a "task" (or a "TF server"). It has an IP address, a port, and a type (also called its role or its job). The type can be `"worker"`, `"chief"`, `"ps"` (parameter server) or `"evaluator"`:
* Each **worker** performs computations, usually on a machine with one or more GPUs.
* The **chief** performs computations as well, but it also handles extra work such as writing TensorBoard logs or saving checkpoints. There is a single chief in a cluster, typically the first worker (i.e., worker #0).
* A **parameter server** (ps) only keeps track of variable values, it is usually on a CPU-only machine.
* The **evaluator** obviously takes care of evaluation. There is usually a single evaluator in a cluster.
The set of tasks that share the same type is often called a "job". For example, the "worker" job is the set of all workers.
To start a TensorFlow cluster, you must first define it. This means specifying all the tasks (IP address, TCP port, and type). For example, the following cluster specification defines a cluster with 3 tasks (2 workers and 1 parameter server). It's a dictionary with one key per job, and the values are lists of task addresses:
```
cluster_spec = {
"worker": [
"machine-a.example.com:2222", # /job:worker/task:0
"machine-b.example.com:2222" # /job:worker/task:1
],
"ps": ["machine-c.example.com:2222"] # /job:ps/task:0
}
```
Every task in the cluster may communicate with every other task in the server, so make sure to configure your firewall to authorize all communications between these machines on these ports (it's usually simpler if you use the same port on every machine).
When a task is started, it needs to be told which one it is: its type and index (the task index is also called the task id). A common way to specify everything at once (both the cluster spec and the current task's type and id) is to set the `TF_CONFIG` environment variable before starting the program. It must be a JSON-encoded dictionary containing a cluster specification (under the `"cluster"` key), and the type and index of the task to start (under the `"task"` key). For example, the following `TF_CONFIG` environment variable defines the same cluster as above, with 2 workers and 1 parameter server, and specifies that the task to start is worker #1:
```
import json
os.environ["TF_CONFIG"] = json.dumps({
"cluster": cluster_spec,
"task": {"type": "worker", "index": 1}
})
os.environ["TF_CONFIG"]
```
Some platforms (e.g., Google Cloud ML Engine) automatically set this environment variable for you.
TensorFlow's `TFConfigClusterResolver` class reads the cluster configuration from this environment variable:
```
import tensorflow as tf
resolver = tf.distribute.cluster_resolver.TFConfigClusterResolver()
resolver.cluster_spec()
resolver.task_type
resolver.task_id
```
Now let's run a simpler cluster with just two worker tasks, both running on the local machine. We will use the `MultiWorkerMirroredStrategy` to train a model across these two tasks.
The first step is to write the training code. As this code will be used to run both workers, each in its own process, we write this code to a separate Python file, `my_mnist_multiworker_task.py`. The code is relatively straightforward, but there are a couple important things to note:
* We create the `MultiWorkerMirroredStrategy` before doing anything else with TensorFlow.
* Only one of the workers will take care of logging to TensorBoard and saving checkpoints. As mentioned earlier, this worker is called the *chief*, and by convention it is usually worker #0.
```
%%writefile my_mnist_multiworker_task.py
import numpy as np
import tensorflow as tf
import time
# At the beginning of the program
distribution = tf.distribute.MultiWorkerMirroredStrategy()
resolver = tf.distribute.cluster_resolver.TFConfigClusterResolver()
print("Starting task {}{}".format(resolver.task_type, resolver.task_id))
# Only worker #0 will write checkpoints and log to TensorBoard
if resolver.task_id == 0:
root_logdir = Path() / "my_mnist_multiworker_logs"
run_id = time.strftime("run_%Y_%m_%d-%H_%M_%S")
run_dir = root_logdir / run_id
callbacks = [
tf.keras.callbacks.TensorBoard(run_dir),
tf.keras.callbacks.ModelCheckpoint("my_mnist_multiworker_model.h5",
save_best_only=True),
]
else:
callbacks = []
# Load and prepare the MNIST dataset
(X_train_full, y_train_full), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
X_train_full = X_train_full[..., np.newaxis] / 255.
X_valid, X_train = X_train_full[:5000], X_train_full[5000:]
y_valid, y_train = y_train_full[:5000], y_train_full[5000:]
with distribution.scope():
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(filters=64, kernel_size=7, activation="relu",
padding="same", input_shape=[28, 28, 1]),
tf.keras.layers.MaxPooling2D(pool_size=2),
tf.keras.layers.Conv2D(filters=128, kernel_size=3, activation="relu",
padding="same"),
tf.keras.layers.Conv2D(filters=128, kernel_size=3, activation="relu",
padding="same"),
tf.keras.layers.MaxPooling2D(pool_size=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(units=64, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(units=10, activation='softmax'),
])
model.compile(loss="sparse_categorical_crossentropy",
optimizer=tf.keras.optimizers.SGD(learning_rate=1e-2),
metrics=["accuracy"])
model.fit(X_train, y_train, validation_data=(X_valid, y_valid),
epochs=10, callbacks=callbacks)
```
In a real world application, there would typically be a single worker per machine, but in this example we're running both workers on the same machine, so they will both try to use all the available GPU RAM (if this machine has a GPU), and this will likely lead to an Out-Of-Memory (OOM) error. To avoid this, we could use the `CUDA_VISIBLE_DEVICES` environment variable to assign a different GPU to each worker. Alternatively, we can simply disable GPU support, like this:
```
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
```
We are now ready to start both workers, each in its own process, using Python's `subprocess` module. Before we start each process, we need to set the `TF_CONFIG` environment variable appropriately, changing only the task index:
```
import subprocess
cluster_spec = {"worker": ["127.0.0.1:9901", "127.0.0.1:9902"]}
for index, worker_address in enumerate(cluster_spec["worker"]):
os.environ["TF_CONFIG"] = json.dumps({
"cluster": cluster_spec,
"task": {"type": "worker", "index": index}
})
subprocess.Popen("python my_mnist_multiworker_task.py", shell=True)
```
That's it! Our TensorFlow cluster is now running, but we can't see it in this notebook because it's running in separate processes (but if you are running this notebook in Jupyter, you can see the worker logs in Jupyter's server logs).
Since the chief (worker #0) is writing to TensorBoard, we use TensorBoard to view the training progress. Run the following cell, then click on the settings button (i.e., the gear icon) in the TensorBoard interface and check the "Reload data" box to make TensorBoard automatically refresh every 30s. Once the first epoch of training is finished (which may take a few minutes), and once TensorBoard refreshes, the SCALARS tab will appear. Click on this tab to view the progress of the model's training and validation accuracy.
```
%load_ext tensorboard
%tensorboard --logdir=./my_mnist_multiworker_logs --port=6006
```
That's it! Once training is over, the best checkpoint of the model will be available in the `my_mnist_multiworker_model.h5` file. You can load it using `tf.keras.models.load_model()` and use it for predictions, as usual:
```
model = tf.keras.models.load_model("my_mnist_multiworker_model.h5")
Y_pred = model.predict(X_new)
Y_pred.argmax(axis=-1)
```
And that's all for today! Hope you found this useful. 😊
# Exercise Solutions
## 1. to 8.
1. A SavedModel contains a TensorFlow model, including its architecture (a computation graph) and its weights. It is stored as a directory containing a _saved_model.pb_ file, which defines the computation graph (represented as a serialized protocol buffer), and a _variables_ subdirectory containing the variable values. For models containing a large number of weights, these variable values may be split across multiple files. A SavedModel also includes an _assets_ subdirectory that may contain additional data, such as vocabulary files, class names, or some example instances for this model. To be more accurate, a SavedModel can contain one or more _metagraphs_. A metagraph is a computation graph plus some function signature definitions (including their input and output names, types, and shapes). Each metagraph is identified by a set of tags. To inspect a SavedModel, you can use the command-line tool `saved_model_cli` or just load it using `tf.saved_model.load()` and inspect it in Python.
2. TF Serving allows you to deploy multiple TensorFlow models (or multiple versions of the same model) and make them accessible to all your applications easily via a REST API or a gRPC API. Using your models directly in your applications would make it harder to deploy a new version of a model across all applications. Implementing your own microservice to wrap a TF model would require extra work, and it would be hard to match TF Serving's features. TF Serving has many features: it can monitor a directory and autodeploy the models that are placed there, and you won't have to change or even restart any of your applications to benefit from the new model versions; it's fast, well tested, and scales very well; and it supports A/B testing of experimental models and deploying a new model version to just a subset of your users (in this case the model is called a _canary_). TF Serving is also capable of grouping individual requests into batches to run them jointly on the GPU. To deploy TF Serving, you can install it from source, but it is much simpler to install it using a Docker image. To deploy a cluster of TF Serving Docker images, you can use an orchestration tool such as Kubernetes, or use a fully hosted solution such as Google Cloud AI Platform.
3. To deploy a model across multiple TF Serving instances, all you need to do is configure these TF Serving instances to monitor the same _models_ directory, and then export your new model as a SavedModel into a subdirectory.
4. The gRPC API is more efficient than the REST API. However, its client libraries are not as widely available, and if you activate compression when using the REST API, you can get almost the same performance. So, the gRPC API is most useful when you need the highest possible performance and the clients are not limited to the REST API.
5. To reduce a model's size so it can run on a mobile or embedded device, TFLite uses several techniques:
* It provides a converter which can optimize a SavedModel: it shrinks the model and reduces its latency. To do this, it prunes all the operations that are not needed to make predictions (such as training operations), and it optimizes and fuses operations whenever possible.
* The converter can also perform post-training quantization: this technique dramatically reduces the model’s size, so it’s much faster to download and store.
* It saves the optimized model using the FlatBuffer format, which can be loaded to RAM directly, without parsing. This reduces the loading time and memory footprint.
6. Quantization-aware training consists in adding fake quantization operations to the model during training. This allows the model to learn to ignore the quantization noise; the final weights will be more robust to quantization.
7. Model parallelism means chopping your model into multiple parts and running them in parallel across multiple devices, hopefully speeding up the model during training or inference. Data parallelism means creating multiple exact replicas of your model and deploying them across multiple devices. At each iteration during training, each replica is given a different batch of data, and it computes the gradients of the loss with regard to the model parameters. In synchronous data parallelism, the gradients from all replicas are then aggregated and the optimizer performs a Gradient Descent step. The parameters may be centralized (e.g., on parameter servers) or replicated across all replicas and kept in sync using AllReduce. In asynchronous data parallelism, the parameters are centralized and the replicas run independently from each other, each updating the central parameters directly at the end of each training iteration, without having to wait for the other replicas. To speed up training, data parallelism turns out to work better than model parallelism, in general. This is mostly because it requires less communication across devices. Moreover, it is much easier to implement, and it works the same way for any model, whereas model parallelism requires analyzing the model to determine the best way to chop it into pieces.
8. When training a model across multiple servers, you can use the following distribution strategies:
* The `MultiWorkerMirroredStrategy` performs mirrored data parallelism. The model is replicated across all available servers and devices, and each replica gets a different batch of data at each training iteration and computes its own gradients. The mean of the gradients is computed and shared across all replicas using a distributed AllReduce implementation (NCCL by default), and all replicas perform the same Gradient Descent step. This strategy is the simplest to use since all servers and devices are treated in exactly the same way, and it performs fairly well. In general, you should use this strategy. Its main limitation is that it requires the model to fit in RAM on every replica.
* The `ParameterServerStrategy` performs asynchronous data parallelism. The model is replicated across all devices on all workers, and the parameters are sharded across all parameter servers. Each worker has its own training loop, running asynchronously with the other workers; at each training iteration, each worker gets its own batch of data and fetches the latest version of the model parameters from the parameter servers, then it computes the gradients of the loss with regard to these parameters, and it sends them to the parameter servers. Lastly, the parameter servers perform a Gradient Descent step using these gradients. This strategy is generally slower than the previous strategy, and a bit harder to deploy, since it requires managing parameter servers. However, it can be useful in some situations, especially when you can take advantage of the asynchronous updates, for example to reduce I/O bottlenecks. This depends on many factors, including hardware, network topology, number of servers, model size, and more, so your mileage may vary.
## 9.
_Exercise: Train a model (any model you like) and deploy it to TF Serving or Google Cloud AI Platform. Write the client code to query it using the REST API or the gRPC API. Update the model and deploy the new version. Your client code will now query the new version. Roll back to the first version._
Please follow the steps in the <a href="#Deploying-TensorFlow-models-to-TensorFlow-Serving-(TFS)">Deploying TensorFlow models to TensorFlow Serving</a> section above.
# 10.
_Exercise: Train any model across multiple GPUs on the same machine using the `MirroredStrategy` (if you do not have access to GPUs, you can use Colaboratory with a GPU Runtime and create two virtual GPUs). Train the model again using the `CentralStorageStrategy `and compare the training time._
Please follow the steps in the [Distributed Training](#Distributed-Training) section above.
# 11.
_Exercise: Train a small model on Google Cloud AI Platform, using black box hyperparameter tuning._
Please follow the instructions on pages 716-717 of the book. You can also read [this documentation page](https://cloud.google.com/ai-platform/training/docs/hyperparameter-tuning-overview) and go through the example in this nice [blog post](https://towardsdatascience.com/how-to-do-bayesian-hyper-parameter-tuning-on-a-blackbox-model-882009552c6d) by Lak Lakshmanan.
| github_jupyter |
# Amazon Comprehend - Sentiment Example
### Assess sentiment of customer review
Objective: Use Comprehend Service to detect sentiment
Input: Customer Review headline and body
Output: Overall sentiment and scores for Positive, Negative, Neutral, Mixed
https://docs.aws.amazon.com/comprehend/latest/dg/how-sentiment.html
Dataset and Problem Description:
https://s3.amazonaws.com/amazon-reviews-pds/readme.html
https://s3.console.aws.amazon.com/s3/buckets/amazon-reviews-pds/?region=us-east-2
File: s3://amazon-reviews-pds/tsv/amazon_reviews_us_Major_Appliances_v1_00.tsv.gz
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re
# Connect to Comprehend to get Sentiment
import boto3
```
### Download Customer Reviews from Amazon Public Dataset
```
!aws s3 cp s3://amazon-reviews-pds/tsv/amazon_reviews_us_Major_Appliances_v1_00.tsv.gz .
```
### Prepare Training and Test data
```
df = pd.read_csv('amazon_reviews_us_Major_Appliances_v1_00.tsv.gz',
sep='\t',error_bad_lines=False,warn_bad_lines=True)#,nrows=1000)
print('Rows: {0}, Columns: {1}'.format(df.shape[0],df.shape[1]))
df.index.max()
df.columns
df.isna().any(axis=0)
# Look for any rows that have NA
rows_missing_values = df.isna().any(axis=1)
df[rows_missing_values]
df['review_headline'] = df['review_headline'].fillna(' ')
df['review_body'] = df['review_body'].fillna(' ')
# Replace embedded new lines, tabs and carriage return
pattern = r'[\n\t\r]+'
# Use Regex module sub method to identify patterns of interest and replace the matching text.
text = 'ab,cd\n\tef'
print('original text:', text)
print('after substituition:', re.sub(pattern,' ', text))
df['product_title'] = df['product_title'].map(lambda x: re.sub(pattern,' ',x))
df['review_headline'] = df['review_headline'].map(lambda x: re.sub(pattern,' ',x))
df['review_body'] = df['review_body'].map(lambda x: re.sub(pattern,' ',x))
df.head()
df['review_body'].head()
# Some examples of review title and body
for i in range(10):
print(df.iloc[i]['review_headline'] + ' - ' + df.iloc[i]['review_body'])
print()
```
### Get Sentiment of Reviews using Comprehend AI Service
```
session = boto3.Session(region_name='us-east-1')
client = session.client('comprehend')
# Try some examples
sentiment = client.detect_sentiment(
Text="It's insulting that @awscloud marked an EBS volume limit increase support request as low severity but I can't do anything while I wait.",
LanguageCode='en'
)
sentiment['Sentiment'],sentiment['SentimentScore']
%%time
# Sentiment of reviews -
# One roundtrip to comprehend service for each review
for i in range(15):
review = df.iloc[i]['review_headline'] + ' - ' + df.iloc[i]['review_body']
print(review)
sentiment = client.detect_sentiment(Text=review,LanguageCode='en')
print(sentiment['Sentiment'])
print()
%%time
# Batch Processing - Upto 25 reviews in one roundtrip
results = []
# Let's get sentiment for first 15 reviews
review = list((df.iloc[0:15]['review_headline'] + ' - ' + df.iloc[0:15]['review_body'].str.slice(0,4000)).values)
#print(review)
# initialize place holder for return values
temp_results = ['']*len(review)
sentiment = client.batch_detect_sentiment(TextList=review,LanguageCode='en')
# Get the sentiment
for s in sentiment['ResultList']:
#print(s['Index']+i,s['Sentiment'])
temp_results[s['Index']] = s['Sentiment']
# Check for errors
for s in sentiment['ErrorList']:
#print(s['Index']+i,s['ErrorCode'])
temp_results[s['Index']] = s['ErrorCode']
results.extend(temp_results)
for idx, r in enumerate(review):
print(r)
print(results[idx])
```
### Get Sentiment for All Reviews
### Warning: Below code accumulated USD 65 in charges for around 100,000 reviews.
### Do not run this code as you will incur the charges.
### I have commented the below cell
### Use the file with sentiments that I generated : customer_reviews_with_sentiment_compressed.txt.gz
### Copy the file to your bucket
#### NOTE: Change the bucket name 'aws-glue-cl' to point to your bucket
```
!aws s3 cp customer_reviews_with_sentiment_compressed.txt.gz s3://aws-glue-cl/customer_review/customer_reviews_with_sentiment_compressed.txt.gz
```
| github_jupyter |
## This notebook is used to generate the finalized version of the classifier, to simply feature transformation into the final form, and to test that the results are the same
Most of the code comes from operational_classifier.
```
import pandas as pd
import numpy as np
import pickle
import sys
#reload(sys)
#sys.setdefaultencoding("utf-8")
#Loading raw data
df = pickle.load(open("../Data/multiclass_tweets_indexed.p",'rb'))
tweets = df.text
```
## Feature generation
```
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk
from nltk.stem.porter import *
import string
import re
stopwords=stopwords = nltk.corpus.stopwords.words("english")
other_exclusions = ["#ff", "ff", "rt"]
stopwords.extend(other_exclusions)
stemmer = PorterStemmer()
def preprocess(text_string):
"""
Accepts a text string and replaces:
1) urls with URLHERE
2) lots of whitespace with one instance
3) mentions with MENTIONHERE
This allows us to get standardized counts of urls and mentions
Without caring about specific people mentioned
"""
space_pattern = '\s+'
giant_url_regex = ('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|'
'[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
mention_regex = '@[\w\-]+'
parsed_text = re.sub(space_pattern, ' ', text_string)
parsed_text = re.sub(giant_url_regex, '', parsed_text)
parsed_text = re.sub(mention_regex, '', parsed_text)
#parsed_text = parsed_text.code("utf-8", errors='ignore')
return parsed_text
def tokenize(tweet):
"""Removes punctuation & excess whitespace, sets to lowercase,
and stems tweets. Returns a list of stemmed tokens."""
tweet = " ".join(re.split("[^a-zA-Z]*", tweet.lower())).strip()
#tokens = re.split("[^a-zA-Z]*", tweet.lower())
tokens = [stemmer.stem(t) for t in tweet.split()]
return tokens
def basic_tokenize(tweet):
"""Same as tokenize but without the stemming"""
tweet = " ".join(re.split("[^a-zA-Z.,!?]*", tweet.lower())).strip()
return tweet.split()
vectorizer = TfidfVectorizer(
#vectorizer = sklearn.feature_extraction.text.CountVectorizer(
tokenizer=tokenize,
preprocessor=preprocess,
ngram_range=(1, 3),
stop_words=stopwords, #We do better when we keep stopwords
use_idf=True,
smooth_idf=False,
norm=None, #Applies l2 norm smoothing
decode_error='replace',
max_features=10000,
min_df=5,
max_df=0.501
)
#Construct tfidf matrix and get relevant scores
tfidf = vectorizer.fit_transform(tweets).toarray()
vocab = {v:i for i, v in enumerate(vectorizer.get_feature_names())}
idf_vals = vectorizer.idf_
idf_dict = {i:idf_vals[i] for i in vocab.values()} #keys are indices; values are IDF scores
#Get POS tags for tweets and save as a string
tweet_tags = []
for t in tweets:
tokens = basic_tokenize(preprocess(t))
tags = nltk.pos_tag(tokens)
tag_list = [x[1] for x in tags]
#for i in range(0, len(tokens)):
tag_str = " ".join(tag_list)
tweet_tags.append(tag_str)
#print(tokens[i],tag_list[i])
#We can use the TFIDF vectorizer to get a token matrix for the POS tags
pos_vectorizer = TfidfVectorizer(
#vectorizer = sklearn.feature_extraction.text.CountVectorizer(
tokenizer=None,
lowercase=False,
preprocessor=None,
ngram_range=(1, 3),
stop_words=None, #We do better when we keep stopwords
use_idf=False,
smooth_idf=False,
norm=None, #Applies l2 norm smoothing
decode_error='replace',
max_features=5000,
min_df=5,
max_df=0.501,
)
#Construct POS TF matrix and get vocab dict
pos = pos_vectorizer.fit_transform(pd.Series(tweet_tags)).toarray()
pos_vocab = {v:i for i, v in enumerate(pos_vectorizer.get_feature_names())}
#Now get other features
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer as VS
from textstat.textstat import *
sentiment_analyzer = VS()
def count_twitter_objs(text_string):
"""
Accepts a text string and replaces:
1) urls with URLHERE
2) lots of whitespace with one instance
3) mentions with MENTIONHERE
4) hashtags with HASHTAGHERE
This allows us to get standardized counts of urls and mentions
Without caring about specific people mentioned.
Returns counts of urls, mentions, and hashtags.
"""
space_pattern = '\s+'
giant_url_regex = ('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|'
'[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
mention_regex = '@[\w\-]+'
hashtag_regex = '#[\w\-]+'
parsed_text = re.sub(space_pattern, ' ', text_string)
parsed_text = re.sub(giant_url_regex, 'URLHERE', parsed_text)
parsed_text = re.sub(mention_regex, 'MENTIONHERE', parsed_text)
parsed_text = re.sub(hashtag_regex, 'HASHTAGHERE', parsed_text)
return(parsed_text.count('URLHERE'),parsed_text.count('MENTIONHERE'),parsed_text.count('HASHTAGHERE'))
def other_features(tweet):
"""This function takes a string and returns a list of features.
These include Sentiment scores, Text and Readability scores,
as well as Twitter specific features"""
##SENTIMENT
sentiment = sentiment_analyzer.polarity_scores(tweet)
words = preprocess(tweet) #Get text only
syllables = textstat.syllable_count(words) #count syllables in words
num_chars = sum(len(w) for w in words) #num chars in words
num_chars_total = len(tweet)
num_terms = len(tweet.split())
num_words = len(words.split())
avg_syl = round(float((syllables+0.001))/float(num_words+0.001),4)
num_unique_terms = len(set(words.split()))
###Modified FK grade, where avg words per sentence is just num words/1
FKRA = round(float(0.39 * float(num_words)/1.0) + float(11.8 * avg_syl) - 15.59,1)
##Modified FRE score, where sentence fixed to 1
FRE = round(206.835 - 1.015*(float(num_words)/1.0) - (84.6*float(avg_syl)),2)
twitter_objs = count_twitter_objs(tweet) #Count #, @, and http://
retweet = 0
if "rt" in words:
retweet = 1
features = [FKRA, FRE,syllables, avg_syl, num_chars, num_chars_total, num_terms, num_words,
num_unique_terms, sentiment['neg'], sentiment['pos'], sentiment['neu'], sentiment['compound'],
twitter_objs[2], twitter_objs[1],
twitter_objs[0], retweet]
#features = pandas.DataFrame(features)
return features
def get_feature_array(tweets):
feats=[]
for t in tweets:
feats.append(other_features(t))
return np.array(feats)
other_features_names = ["FKRA", "FRE","num_syllables", "avg_syl_per_word", "num_chars", "num_chars_total", \
"num_terms", "num_words", "num_unique_words", "vader neg","vader pos","vader neu", "vader compound", \
"num_hashtags", "num_mentions", "num_urls", "is_retweet"]
feats = get_feature_array(tweets)
#Now join them all up
M = np.concatenate([tfidf,pos,feats],axis=1)
M.shape
#Finally get a list of variable names
variables = ['']*len(vocab)
for k,v in vocab.iteritems():
variables[v] = k
pos_variables = ['']*len(pos_vocab)
for k,v in pos_vocab.iteritems():
pos_variables[v] = k
feature_names = variables+pos_variables+other_features_names
```
# Running the model
This model was found using a GridSearch with 5-fold cross validation. Details are in the notebook operational_classifier.
```
X = pd.DataFrame(M)
y = df['class'].astype(int)
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import classification_report
from sklearn.svm import LinearSVC
select = SelectFromModel(LogisticRegression(class_weight='balanced',penalty="l1",C=0.01))
X_ = select.fit_transform(X,y)
model = LinearSVC(class_weight='balanced',C=0.01, penalty='l2', loss='squared_hinge',multi_class='ovr').fit(X_, y)
y_preds = model.predict(X_)
report = classification_report( y, y_preds )
print(report)
```
# Using information from the model to obtain the matrix X_ generically
This is the most difficult task: We have to take the inputs tweets and transform them into a format that can be used in the model without going through all the same pre-processing steps as above. This can be done as follows.
## Obtaining information about the model
```
final_features = select.get_support(indices=True) #get indices of features
final_feature_list = [unicode(feature_names[i]) for i in final_features] #Get list of names corresponding to indices
print final_feature_list
#Getting names for each class of features
ngram_features = final_feature_list[:final_feature_list.index('yr')+1]
pos_features = final_feature_list[final_feature_list.index('yr')+1:final_feature_list.index('VBD')+1]
oth_features = final_feature_list[final_feature_list.index('VBD')+1:]
```
## Generating ngram features
```
new_vocab = {v:i for i, v in enumerate(ngram_features)}
new_vocab_to_index = {}
for k in ngram_features:
new_vocab_to_index[k] = vocab[k]
#Get indices of text features
ngram_indices = final_features[:len(ngram_features)]
#TODO: Pickle new vectorizer
new_vectorizer = TfidfVectorizer(
#vectorizer = sklearn.feature_extraction.text.CountVectorizer(
tokenizer=tokenize,
preprocessor=preprocess,
ngram_range=(1, 3),
stop_words=stopwords, #We do better when we keep stopwords
use_idf=False,
smooth_idf=False,
norm=None, #Applies l2 norm smoothing
decode_error='replace',
min_df=1,
max_df=1.0,
vocabulary=new_vocab
)
from sklearn.externals import joblib
joblib.dump(new_vectorizer, 'final_tfidf.pkl')
tfidf_ = new_vectorizer.fit_transform(tweets).toarray()
#Verifying that results are the same
tfidf_[1,:]
tfidf_[1,:].sum()
X_[1,:tfidf_.shape[1]]
X_[1,:tfidf_.shape[1]].sum()
```
Results are the same if use IDF but the problem is that IDF will be different if we use different data. Instead we have to use the original IDF scores and multiply them by the new matrix.
```
idf_vals_ = idf_vals[ngram_indices]
idf_vals_.shape
#TODO: Pickle idf_vals
joblib.dump(idf_vals_, 'final_idf.pkl')
(tfidf_[1,:]*idf_vals_) == X_[1,:153] #Got same value as final process array!
tfidf_*idf_vals_ == X_[:,:153]
tfidffinal = tfidf_*idf_vals_
```
## Generating POS features
This is simpler as we do not need to worry about IDF but it will be slower as we have to compute the POS tags for the new data. Here we can simply use the old POS tags.
```
new_pos = {v:i for i, v in enumerate(pos_features)}
#TODO: Pickle pos vectorizer
#We can use the TFIDF vectorizer to get a token matrix for the POS tags
new_pos_vectorizer = TfidfVectorizer(
#vectorizer = sklearn.feature_extraction.text.CountVectorizer(
tokenizer=None,
lowercase=False,
preprocessor=None,
ngram_range=(1, 3),
stop_words=None, #We do better when we keep stopwords
use_idf=False,
smooth_idf=False,
norm=None, #Applies l2 norm smoothing
decode_error='replace',
min_df=1,
max_df=1.0,
vocabulary=new_pos
)
joblib.dump(new_pos_vectorizer, 'final_pos.pkl')
pos_ = new_pos_vectorizer.fit_transform(tweet_tags).toarray()
pos_[1,:]
X_[1,153:159]
pos_[:,:] == X_[:,153:159]
pos_[:,:].sum()
X_[:,153:159].sum()
```
## Finally, we can look at the other features
```
print other_features_names
print oth_features
```
The functions can be modified to only calculate and return necessary fields.
```
def other_features_(tweet):
"""This function takes a string and returns a list of features.
These include Sentiment scores, Text and Readability scores,
as well as Twitter specific features"""
##SENTIMENT
sentiment = sentiment_analyzer.polarity_scores(tweet)
words = preprocess(tweet) #Get text only
syllables = textstat.syllable_count(words) #count syllables in words
num_chars = sum(len(w) for w in words) #num chars in words
num_chars_total = len(tweet)
num_terms = len(tweet.split())
num_words = len(words.split())
avg_syl = round(float((syllables+0.001))/float(num_words+0.001),4)
num_unique_terms = len(set(words.split()))
###Modified FK grade, where avg words per sentence is just num words/1
FKRA = round(float(0.39 * float(num_words)/1.0) + float(11.8 * avg_syl) - 15.59,1)
##Modified FRE score, where sentence fixed to 1
FRE = round(206.835 - 1.015*(float(num_words)/1.0) - (84.6*float(avg_syl)),2)
twitter_objs = count_twitter_objs(tweet) #Count #, @, and http://
features = [FKRA, FRE, syllables, num_chars, num_chars_total, num_terms, num_words,
num_unique_terms, sentiment['compound'],
twitter_objs[2], twitter_objs[1],]
#features = pandas.DataFrame(features)
return features
def get_feature_array_(tweets):
feats=[]
for t in tweets:
feats.append(other_features_(t))
return np.array(feats)
feats_ = get_feature_array_(tweets)
feats_[0,:]
X_[0,159:]
feats_[:,:] == X_[:,159:]
```
## Now that we have put it all together using a simplified process we can assess if these new data return the same answers.
```
M_ = np.concatenate([tfidffinal, pos_, feats_],axis=1)
M_.shape
X__ = pd.DataFrame(M_)
y_preds_ = model.predict(X__)
report = classification_report( y, y_preds_ )
print(report)
```
OK. So now that we have verified that the results are the same with X_ and X__ we can implement a script that can transform new data in this manner.
| github_jupyter |
<a href="https://colab.research.google.com/github/google/applied-machine-learning-intensive/blob/master/content/02_data/02_intermediate_pandas/colab.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
####Copyright 2020 Google LLC.
```
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Intermediate Pandas
[Pandas](https://pandas.pydata.org/) is a powerful Python library for working with data. For this lab, you should already know what a [DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) and [Series](https://pandas.pydata.org/pandas-docs/stable/reference/series.html) are and how to do some simple analysis of the data contained in those structures.
In this lab we'll look at some more advanced capabilities of Pandas, such as filtering, grouping, merging, and sorting.
## DataFrame Information
`DataFrame` objects are rich containers that allow us to explore and modify data. In this lab we will learn powerful techniques for working with the data contained in `DataFrame` objects.
To begin, let's create a `DataFrame` containing information about populations and airports in a few select cities.
```
import pandas as pd
airport_df = pd.DataFrame.from_records((
('Atlanta', 498044, 2),
('Austin', 964254, 2),
('Kansas City', 491918, 8),
('New York City', 8398748, 3),
('Portland', 653115, 1),
('San Francisco', 883305, 3),
('Seattle', 744955, 2),
), columns=("City Name", "Population", "Airports"))
airport_df
```
If you aren't familiar with the `from_records()` method, it is a way to create a `DataFrame` from data formatted in a tabular manner. In this case we have a tuple-of-tuples where each inner-tuple is a row of data for a city.
### Shape
One interesting fact about a `DataFrame` is its shape. What is shape?
Shape is the number of rows and columns contained in the dataframe.
Let's find the shape of the `airport_df`:
```
airport_df.shape
```
The `DataFrame` has a shape of `(7, 3)`.
This means that the `DataFrame` has seven rows and three columns.
If you are familiar with [NumPy](http://numpy.org), you probably are also familiar with `shape`. `NumPy` arrays can have n-dimensional shapes while `DataFrame` objects tend to stick to two dimensions: rows and columns.
#### Exercise 1: Finding Shape
Download the California housing data referenced below into a `DataFrame`, and print out the shape of the data.
**Student Solution**
```
url = "https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv"
# Download the housing data
# Print the shape of the data
```
---
### Columns
Speaking of columns, it's possible to ask a `DataFrame` what columns it contains using the `columns` attribute:
```
airport_df.columns
```
Notice that the columns are contained in an `Index` object. An `Index` wraps the list of columns. For basic usage, like loops, you can just use the `Index` directly:
```
for c in airport_df.columns:
print(c)
```
If you do need the columns in a lower level format, you can use `.values` to get a `NumPy` array:
```
type(airport_df.columns.values)
```
If you need a basic Python list, you can then call `.tolist()` to get the core Python list of column names:
```
type(airport_df.columns.values.tolist())
```
#### Exercise 2: Pretty Print Columns
The columns in the California housing dataset are not necessarily easy on the eyes. Columns like `housing_median_age` would be easier to read if they were presented as `Housing Median Age`.
In the code block below, download the California housing dataset. Then find the names of the columns in the dataset and convert them from "snake case" to regular English. For instance `housing_median_age` becomes `Housing Median Age` and `total_rooms` becomes `Total Rooms`. Print the human-readable names one per line. You can find Python string methods that might be helpful [here](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str).
Write your code in a manner that it could handle any column name in "snake case": Underscores should be replaced by spaces. The first letter of each word should be capitalized.
Be sure to get the column names from the `DataFrame`.
**Student Solution**
```
import pandas as pd
url = "https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv"
df = pd.read_csv(url)
# Your Code Goes Here
```
---
### Missing Values
It is common to find datasets with missing data. When this happens it's good to know that the data is missing so you can determine how to handle the situation.
Let's recreate our city data but set some values to `None`:
```
import pandas as pd
airport_df = pd.DataFrame.from_records((
('Atlanta', 498044, 2),
(None, 964254, 2),
('Kansas City', 491918, 8),
('New York City', None, 3),
('Portland', 653115, 1),
('San Francisco', 883305, None),
('Seattle', 744955, 2),
), columns=("City Name", "Population", "Airports"))
airport_df
```
You can see that the population of New York and the number of airports in San Francisco are now represented by `NaN` values. This stands for 'Not a Number', which means that the value is an unknown numeric value. You'll also see that where 'Austin' once was, we now have a `None` value. This means that we are missing a non-numeric value.
If we want to ask the `DataFrame` what values are present or missing, we can use the `isna()` method:
```
airport_df.isna()
```
Here we get `True` values where a data point is missing and `False` values where we have data.
Using this, we can do powerful things like select all columns with populations or airports that have missing data:
```
airport_df[airport_df['Population'].isna() | airport_df['Airports'].isna()]
```
Now that we know that we are missing the population of New York and the number of airports in San Francisco, we can look up that data and manually fix it.
Sometimes the fixes aren't so easy. The data might be impossible to find, or there might be so many missing values that you can't individually fix them all.
In these cases you have two options: completely remove the offending rows or columns or patch the data in some way. Throughout this course we will work with many datasets that have missing or obviously invalid values, and we will discuss mitigation strategies.
## Filtering
Filtering is an important concept in data analysis and processing. When you think of filtering in the real world, you likely think of an object that blocks undesired things while allowing desired things to pass through.
Imagine a coffee filter. It stops the coffee grounds from getting into the coffee pot, but it allows the water bound to coffee's chemical compounds to pass through into your perfect brew.
Filtering a `DataFrame` is similar. A `DataFrame` contains rows of data. Some of these rows might be important to you, and some you might want to discard. Filtering allows you select only the data that you care about and put that data in a new `DataFrame`.
In the example below, we filter our `airport_df` to select only cities that have more than two airports. In return we get a `DataFrame` that contains only information about cities that have more than two airports.
```
airport_df[airport_df['Airports'] > 2]
```
Let's deconstruct this statement. At its core we have:
```python
airport_df['Airports'] > 2
```
This expression compares every 'Airports' value in the `airport_df` `DataFrame` and returns `True` if there are more than two airports, `False` otherwise.
```
airport_df['Airports'] > 2
```
This data is returned as a Pandas `Series`. The series is then used as a boolean index for the `airport_df` the `DataFrame`.
**Boolean index** is just a term used to refer to a `Series` (or other list-like structure) of boolean values used in the index operator, `[]`, for the `DataFrame`. Ideally the boolean index length should be equal to the number of rows in the `DataFrame` being indexed. `DataFrame` rows that map to `True` values in the index are retained, while rows that map to `False` values are filtered out.
```
has_many_airports = airport_df['Airports'] > 2
airport_df[has_many_airports]
```
If you are familiar with Boolean logic and Python, you probably know that you can create compound expressions using the `or` and `and` keywords. You can also use the keyword `not` to reverse an expression.
```
print(True and False)
print(True or False)
print(not True)
```
You can do similar things in Pandas with boolean indices. However, `and`, `or`, and `not` don't work as expected. Instead you need to use the `&`, `|`, and `!` operators.
- `and` changes to `&`
- `or` changes to `|`
- `not` changes to `!`
For normal numbers in Python, these are actually the 'bitwise logical operators'. When working on Pandas objects, these operators don't perform bitwise calculations but instead perform Boolean logic.
Let's see this in action with an example. Imagine we want to find all cities with more than two airports and less than a million inhabitants. First, let's find the rows with more than two airports:
```
has_many_airports = airport_df['Airports'] > 2
has_many_airports
```
Now we can find the rows that represent a city with less than a million residents:
```
small_cities = airport_df['Population'] < 1000000
small_cities
```
We can then combine `has_many_airports` with `small_cities` to find small cities with a large number of airports.
To do this we first need to use the `&` operator to combine the two Boolean tables:
```
small_but_flighty = has_many_airports & small_cities
small_but_flighty
```
We can use this boolean index to select the rows from the original `DataFrame` that contain data about cities with fewer than one million residents and more than two airports.
```
airport_df[small_but_flighty]
```
In this example we broke the filter down into many steps. It could actually be performed in one expression as shown below.
```
airport_df[(airport_df['Airports'] > 2) & (airport_df['Population'] < 1000000)]
```
Notice the need for parenthesis around each Boolean expression. This is because `&` has a higher precedence than `>` and `<`.
The term 'filtering' is typically used when talking about rows of data. However, it is possible to filter out columns of a dataset. To filter columns simply list the columns that you do want to keep in a `list` and pass it to the `DataFrame` selector:
```
population_df = airport_df[['City Name', 'Population']]
population_df
```
If a dataset has many columns, it might be easier to exclude a column using a list expansion instead of explicitly listing many columns:
```
population_df = airport_df[
[col for col in airport_df.columns if col is not 'Airports']]
population_df
```
This works for multiple columns also:
```
population_df = airport_df[
[col for col in airport_df.columns if col not in {'Airports', 'Population'}]]
population_df
```
### Exercise 3: SoCal
Using the California housing `DataFrame` from the previous unit, make a new `DataFrame` that only contains data from the southern part of California. What is 'southern'? For the purpose of this exercise, let's say that southern California includes everything below 36 degrees latitude.
Create a new `DataFrame` called `socal_df` containing only data points below the 36 latitude. Then print out the shape of that `DataFrame`.
**Student Solution**
```
url = "https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv"
cali_df = pd.read_csv(url)
# Your Code Goes here
```
---
##Grouping Data
We can also aggregate `DataFrame` objects by grouping rows of data together.
For our examples we will create a `DataFrame` containing the ages, heights, and weights of a sample of children:
```
import pandas as pd
body_measurement_df = pd.DataFrame.from_records((
(2, 83.82, 8.4),
(4, 99.31, 16.97),
(3, 96.52, 14.41),
(6, 114.3, 20.14),
(4, 101.6, 16.91),
(2, 86.36, 12.64),
(3, 92.71, 14.23),
(2, 85.09, 11.11),
(2, 85.85, 14.18),
(5, 106.68, 20.01),
(4, 99.06, 13.17),
(5, 109.22, 15.36),
(4, 100.84, 14.78),
(6, 115.06, 20.06),
(2, 84.07, 10.02),
(7, 121.67, 28.4),
(3, 94.49, 14.05),
(6, 116.59, 17.55),
(7, 121.92, 22.96),
), columns=("Age (yrs)", "Height (cm)", "Weight (kg)"))
body_measurement_df
```
As you can see, we have a fairly low-level dump of data. It is unsorted and is generally difficult to gain any insight from. We could group the data by age and find metrics such as the count, max, min, mean, median, and more. This information might be more easy to analyze.
In order to do this grouping, we use the `groupby` method on the `DataFrame`.
For instance, if we wanted to know the mean values for the columns for each year of age, we could run the following code:
```
body_measurement_df.groupby('Age (yrs)').mean()
```
We get a `DataFrame` sorted by the column that we chose to group by. The 'Height (cm)' and 'Weight (kg)' columns now represent the mean height and weight for each age represented in our dataset.
Looking at this data, you can now see a steady increase in height and weight as age increases, which is what you are likely to expect.
You might notice here that the 'Age (yrs)' column looks a little different. It is now not a regular column, but is instead an index column.
Let's see what this means by saving the grouped data into a new `DataFrame`:
```
mean_body_measurement_df = body_measurement_df.groupby('Age (yrs)').mean()
mean_body_measurement_df.columns
```
You'll notice that 'Age (yrs)' is no longer listed as a column. In order to access the age you instead have to use the `.index` property of the `DataFrame`.
Note that we get an `Int64Index` object back and not a `Series` as we would if we referenced a single column.
```
mean_body_measurement_df.index
```
We aren't restricted to just using `mean()`. There are many other aggregate functions that we could use, including `max()`, which gives us the largest sample in each grouping:
```
body_measurement_df.groupby('Age (yrs)').max()
```
And `min()` which gives the smallest value in each grouping:
```
body_measurement_df.groupby('Age (yrs)').min()
```
There are many other aggregate functions. You can see the entire list in the [`GroupBy` documentation](https://pandas.pydata.org/pandas-docs/stable/reference/groupby.html).
Sometimes performing a single aggregation across all columns is limiting. What if you want the mean of one column and the max of another? What if you want to perform multiple aggregations on one column?
You can perform different and multiple aggregations using the `agg()` function:
```
body_measurement_df.groupby('Age (yrs)').agg({
'Height (cm)': 'mean',
'Weight (kg)': ['max', 'min'],
})
```
As you can see, `agg()` accepts a dictionary. The keys are the columns that you want to aggregate. The values are either a single aggregation function name or lists of aggregation function names.
### Exercise 4: Grouping
Given the body measurement dataset in a `DataFrame`, group the data by 'Age (yrs)' and find the following aggregations using the `agg()` function:
* 'Age (yrs)' count
* 'Height (cm)' min
* 'Height (cm)' max
* 'Height (cm)' mean
* 'Height (cm)' standard deviation
* 'Weight (kg)' min
* 'Weight (kg)' max
* 'Weight (kg)' mean
* 'Weight (kg)' standard deviation
**Student Solution**
```
import pandas as pd
body_measurement_df = pd.DataFrame.from_records((
(2, 83.82, 8.4),
(4, 99.31, 16.97),
(3, 96.52, 14.41),
(6, 114.3, 20.14),
(4, 101.6, 16.91),
(2, 86.36, 12.64),
(3, 92.71, 14.23),
(2, 85.09, 11.11),
(2, 85.85, 14.18),
(5, 106.68, 20.01),
(4, 99.06, 13.17),
(5, 109.22, 15.36),
(4, 100.84, 14.78),
(6, 115.06, 20.06),
(2, 84.07, 10.02),
(7, 121.67, 28.4),
(3, 94.49, 14.05),
(6, 116.59, 17.55),
(7, 121.92, 22.96),
), columns=("Age (yrs)", "Height (cm)", "Weight (kg)"))
body_measurement_df
# Your Solution Goes Here
```
---
##Merging Data
It is common for related data to be stored in different locations. When this happens you sometimes need to merge the data into a single `DataFrame` in order to work with all of the data in an easy manner.
Let's take a look at some data about popular desserts. First, we have nutritional information:
```
import pandas as pd
nutrition_information_df = pd.DataFrame.from_records((
('Cupcake', 178, 5.26, 32.54, 1.37),
('Donut', 190, 10.51, 21.62, 2.62),
('Eclair', 267, 16.01, 24.68, 6.53),
('Froyo', 214, 2.94, 39.24, 9.4),
('Gingerbread', 130, 5, 19, 2),
('Honeycomb', 190, 13, 23, 2),
('Ice Cream Sandwich', 143, 5.6, 21.75, 2.61),
('Jelly Bean', 100, 0, 25, 0),
('KitKat', 210, 11, 27, 3),
('Lollipop', 110, 0, 28, 0),
('Marshmallow', 100, 0, 24, 1),
('Nougat', 56, 0.23, 12.93, 0.47),
('Oreo', 160, 7, 25, 1),
('Pie', 356, 16.5, 51, 2.85),
), columns=('Name', 'Calories', 'Fat (g)', 'Carbs (g)', 'Protein (g)'))
nutrition_information_df
```
We also have data about the manufacturing costs and the retail price of each of the desserts:
```
import pandas as pd
costs_df = pd.DataFrame.from_records((
('Cupcake', 1.24, 4.50),
('Donut', 0.17, 0.99),
('Eclair', 0.54, 2.50),
('Froyo', 0.78, 3.50),
('Gingerbread', 0.45, 0.99),
('Honeycomb', 1.25, 3.00),
('Ice Cream Sandwich', 1.21, 2.99),
('Jelly Bean', 0.04, 0.99),
('KitKat', 0.33, 1.50),
('Lollipop', 0.11, 1.10),
('Marshmallow', 0.03, 0.50),
('Nougat', 0.75, 1.50),
('Oreo', 0.78, 2.00),
('Pie', 0.66, 2.25),
), columns=('Name', 'Manufacturing (USD)', 'Retail (USD)'))
costs_df
```
If we want to combine the data into a single `DataFrame`, we can merge the data:
```
pd.merge(nutrition_information_df, costs_df)
```
[Pandas](https://pandas.pydata.org) searches for columns with the same name and uses those columns to match rows of data. The result is a single `DataFrame` with columns from the merged `DataFrame` objects.
What if we have yet another `DataFrame` that contains the inventory of desserts that we have in stock:
```
import pandas as pd
inventory_df = pd.DataFrame.from_records((
('Marshmallow', 1004),
('Nougat', 563),
('Oreo', 789),
('Pie', 33),
), columns=('Name', '# In Stock'))
inventory_df
```
If we want to join our inventory with our cost data to see how much earning potential we have in stock, we can join the `costs_df` with the `inventory_df`:
```
pd.merge(costs_df, inventory_df)
```
If we wanted we could then sum up our retail prices multiplied by inventory to see how much gross revenue potential we currently have.
Notice that we only have four desserts. What happened?
By default when merging `DataFrame` objects only rows that match across `DataFrame` objects are returned. Non-matching rows are filtered out.
We can change this by telling `merge` to do an *outer* join. This will keep all of the data in the first `DataFrame` passed to `merge()` and fill in any missing data with null values.
```
pd.merge(costs_df, inventory_df, how='outer')
```
There are many options for merging data. You have options available to keep rows in specific `DataFrames`, to use different columns to join on, and much more. Check out the [`merge` documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html) to learn more.
### Exercise 5: Merging `DataFrame` Objects
In this exercise we will answer a few questions about our dessert-making operation. In order to answer these questions, you are provided with the `costs_df` `DataFrame`, which contains names of treats and costs related to them.
The columns are:
* **Name**: The name of the treat.
* **Manufacturing (USD)**: The cost in United States dollars to create one saleable unit of the treat.
* **Retail (USD)**: The price that one serving of the treat is sold for.
```
import pandas as pd
costs_df = pd.DataFrame.from_records((
('Cupcake', 1.24, 4.50),
('Donut', 0.17, 0.99),
('Eclair', 0.54, 2.50),
('Froyo', 0.78, 3.50),
('Gingerbread', 0.45, 0.99),
('Honeycomb', 1.25, 3.00),
('Ice Cream Sandwich', 1.21, 2.99),
('Jelly Bean', 0.04, 0.99),
('KitKat', 0.33, 1.50),
('Lollipop', 0.11, 1.10),
('Marshmallow', 0.03, 0.50),
('Nougat', 0.75, 1.50),
('Oreo', 0.78, 2.00),
('Pie', 0.66, 2.25),
), columns=('Name', 'Manufacturing (USD)', 'Retail (USD)'))
costs_df
```
The other `DataFrame` that we have at our disposal is the `inventory_df`. This `DataFrame` contains information about how many of each type of treat we have in stock and ready to sell.
The columns are:
* **Name**: The name of the treat.
* **# In Stock**: The number of saleable units of the treat that we have.
Any treats not in inventory are assumed to be out of stock.
```
inventory_df = pd.DataFrame.from_records((
('Marshmallow', 1004),
('Nougat', 563),
('Oreo', 789),
('Pie', 33),
), columns=('Name', '# In Stock'))
inventory_df
```
#### Question 1: Potential Profit
For this question we want to determine the potential profit that we can make with the items that we have in stock.
> $profit = \Sigma^{t}_{i=1} n * (r - m)$
Where:
* `t` is every type of treat in stock
* `n` is the number of units of that treat
* `r` is the retail price of the treat
* `m` are the manufacturing costs for the treat
Merge `inventory_df` and `costs_df` to calculate the `potential_profit`. Print out the potential profit.
**Student Solution**
```
# Merge the DataFrame objects
dessert_df = None
# Calculate potential profit
potential_profit = None
# Print the potential profit
```
---
#### Question 2: Restocking Cost
There are only four different treats available for sale. We need to get some more inventory in this shop!
In this portion of the exercise we will calculate the total cost to get 100 units of each of the missing treats onto the shelves and ready to sale.
The cost is calculated with:
> $cost = \Sigma^{t}_{i=1} 100 * m$
Where:
* `t` is every type of treat **NOT** in stock
* `100` is the number of units of that treat that we'd like to make
* `m` are the manufacturing costs for the treat
Merge `inventory_df` and `costs_df` to calculate the `cost_to_make`. Print out the cost.
**Student Solution**
```
# Merge the DataFrame objects
dessert_df = None
# Identify the missing desserts
missing_dessert_df = None
# Calculate the cost to make 100 of each of the missing treats
cost_to_make = None
# Print the cost
```
---
##Sorting
It is often important to sort data in order to visually examine the data for patterns and anomalies. Luckily this is easy to do in Pandas.
To start off, let's build a `DataFrame` to sort. For this example we will use a `DataFrame` containing information about cities, their populations, and the number of airports in-and-around the cities.
```
import pandas as pd
airport_df = pd.DataFrame.from_records((
('Atlanta', 498044, 2),
('Austin', 964254, 2),
('Kansas City', 491918, 8),
('New York City', 8398748, 3),
('Portland', 653115, 1),
('San Francisco', 883305, 3),
('Seattle', 744955, 2),
), columns=("City Name", "Population", "Airports"))
airport_df
```
The data seems to be sorted by `City Name`. If we want to sort the data by `Population` we can use the `sort_values()` method:
```
airport_df.sort_values('Population')
```
We can see that Kansas City is the smallest city in our dataset, and New York City is the largest.
If you were thinking, *Why does Kansas City have so many airports?*, good for you!
This is one of the benefits we can get from viewing our data in different sorting orders. We can see that the smallest city by population has the largest number of airports. This doesn't seem right.
If we were going to be using this dataset for an actual data science project, we would want to investigate this further. We could:
* Verify that Kansas City actually does have 8 airports
* Verify that a few of the other cities, especially the larger ones, have so few airports
* Look into how the data was collected to see if the count for Kansas City was collected differently:
* Does it contain regional airports while others do not?
* What counts as an airport for the city? Farm landing strips? Military bases?
* How close to a city does an airport need to be to be considered an airport for that city?
You can probably think of many more questions to ask about the data and how it was collected.
When you see something that looks odd in your data, ask questions!
For now, let's get back to sorting. What if we wanted to sort by more than one column?
For instance, we can sort by the number of airports in a city and then by population:
```
airport_df.sort_values(['Airports', 'Population'])
```
Using this we can now answer questions such as *What is the smallest city with two airports?*
Notice that although we sorted the `DataFrame`, we didn't actually change the `DataFrame` itself:
```
airport_df
```
If we do want to save the sort order we can assign the return value of `sort_values()` to another variable:
```
sorted_airport_df = airport_df.sort_values(['Airports', 'Population'])
sorted_airport_df
```
But this doesn't modify the original `DataFrame`. To do that, use the `inplace` argument:
```
airport_df.sort_values(['Airports', 'Population'], inplace=True)
airport_df
```
## References and Copies
Both [Python](https://python.org) and [Pandas](https://pandas.pydata.org) strive to hide lower-level programming details from you whenever they can. However, there are some cases where you do have to be aware of how your data is being managed.
One place where this often happens is when Pandas is working indirectly with with a `DataFrame`.
We'll walk through some examples using the airport data we have seen many times in this lab.
```
import pandas as pd
airport_df = pd.DataFrame.from_records((
('Atlanta', 498044, 2),
('Austin', 964254, 2),
('Kansas City', 491918, 8),
('New York City', 8398748, 3),
('Portland', 653115, 1),
('San Francisco', 883305, 3),
('Seattle', 744955, 2),
), columns=("City Name", "Population", "Airports"))
airport_df
```
We'll start simple and assign the `airport_df` to another variable, `airport_df2`. We then try to double the number of airports in `airport_df2`.
What happens to `airport_df` and `airport_df2`?
```
airport_df2 = airport_df
airport_df2.loc[:, 'Airports'] *= 2
airport_df
```
Yikes! When we modified `airport_df2` we also modified `airport_df`.
This actually has nothing to do with Pandas, but instead is a case where Python creates a **reference** to our original `DataFrame` instead of a copy.
When we assign `airport_df` to `airport_df2` Python just makes `airport_df2` refer to the object that is in `airport_df`. Both refer to the same copy of the data.
This is desirable in many cases. Your data might be big. Having many copies can consume a lot of memory and take a lot of time.
But sometimes you need to actually copy data. Let's reset our airport `DataFrame` and do just that.
```
import pandas as pd
airport_df = pd.DataFrame.from_records((
('Atlanta', 498044, 2),
('Austin', 964254, 2),
('Kansas City', 491918, 8),
('New York City', 8398748, 3),
('Portland', 653115, 1),
('San Francisco', 883305, 3),
('Seattle', 744955, 2),
), columns=("City Name", "Population", "Airports"))
airport_df
```
To make a copy of a `DataFrame` use the `copy()` method.
```
airport_df2 = airport_df.copy()
airport_df2.loc[:, 'Airports'] *= 2
airport_df
```
As you can see, `airport_df` did not change.
But you can see below that `airport_df2` did:
```
airport_df2
```
Pandas adds an additional level of abstraction called **views**. Views are a way to look at the same data from a different perspective.
Let's work through an example using our airport dataset.
Say we wanted to filter to only rows with more than two airports:
```
many_airports_df = airport_df[airport_df['Airports'] > 2]
many_airports_df
```
What is `many_airports_df`? Is it a new `DataFrame`? Does it only contain three rows of data? Are the rows separate or the same as the rows in `airport_df`? If we modify `many_airports_df` will `airports_df` be modified?
Let's try and see:
```
many_airports_df = airport_df[airport_df['Airports'] > 2]
many_airports_df['City Name'] = \
many_airports_df['City Name'].apply(lambda s: s.upper())
airport_df
```
We didn't modify `airport_df`, so we must be working with a copy.
We did get a warning though:
> ```
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
```
In this case Pandas created a copy of the data, but it was uncertain if we wanted to modify the copy or the original `DataFrame`.
Warnings are typically a bad sign. We can get rid of the warning by being explicit about what we want to do.
If we want to copy the data into a new `DataFrame`, we can use `.copy()`:
```
many_airports_df = airport_df[airport_df['Airports'] > 2].copy()
many_airports_df['City Name'] = \
many_airports_df['City Name'].apply(lambda s: s.upper())
airport_df
```
And if we want to not copy the data and to modify the original we need to index into `airport_df` for the modification:
```
has_many_airports = airport_df['Airports'] > 2
airport_df.loc[has_many_airports, 'City Name'] = \
airport_df.loc[has_many_airports, 'City Name'].apply(lambda s: s.upper())
airport_df
```
### Exercise 6: Updating Calories
We just learned that the calorie count for our candy shop's jelly beans and lollipops is 10% too low. We need to update the calorie count for these two treats.
Below you'll find the `nutrition_information_df` which contains nutritional information about our treats. Write some code to increase the calories for 'Jelly Bean' and 'Lollipop' by 10%. Be sure that the data stored in `nutrition_information_df` is updated.
Be sure that no warnings are issued!
**Student Solution**
```
import pandas as pd
nutrition_information_df = pd.DataFrame.from_records((
('Cupcake', 178, 5.26, 32.54, 1.37),
('Donut', 190, 10.51, 21.62, 2.62),
('Eclair', 267, 16.01, 24.68, 6.53),
('Froyo', 214, 2.94, 39.24, 9.4),
('Gingerbread', 130, 5, 19, 2),
('Honeycomb', 190, 13, 23, 2),
('Ice Cream Sandwich', 143, 5.6, 21.75, 2.61),
('Jelly Bean', 100, 0, 25, 0),
('KitKat', 210, 11, 27, 3),
('Lollipop', 110, 0, 28, 0),
('Marshmallow', 100, 0, 24, 1),
('Nougat', 56, 0.23, 12.93, 0.47),
('Oreo', 160, 7, 25, 1),
('Pie', 356, 16.5, 51, 2.85),
), columns=('Name', 'Calories', 'Fat (g)', 'Carbs (g)', 'Protein (g)'))
# Update 'Lollipop' and 'Jelly Bean' calories by 10%
```
---
## Additional Exercises
### Exercise 7: Retail Data
You have been hired to organize a small-town retail chain's data and report to them which of their stores have the most effective marketing, measured by how many dollars of merchandise are sold per visitor.
To accomplish this you are given access to two tables of data.
The first table keeps track of the average daily traffic to each store. We store it in `traffic_df`:
```
import pandas as pd
traffic_df = pd.DataFrame.from_records((
('43 Crescent Way', 2036),
('1001 Main St.', 1399),
('235 Pear Lane', 1386),
('199 Forest Way', 1295),
('703 Grove St.', 1154),
('55 Orchard Blvd.', 1022),
('202 Pine Drive', 968),
('98 Mountain Circle', 730),
('2136 A St.', 729),
('3430 17th St.', 504),
('7766 Ocean Ave.', 452),
('1797 Albatross Ct.', 316),
), columns=('Location', 'Traffic'))
traffic_df
```
The second table contains the average revenue from each store. We store in it `locations_df`:
```
locations_df = pd.DataFrame.from_records((
('43 Crescent Way', 6832),
('55 Orchard Blvd.', 13985),
('98 Mountain Circle', 3956),
('199 Forest Way', 572),
('202 Pine Drive', 3963),
('235 Pear Lane', 25653),
('703 Grove St.', 496),
('1001 Main St.', 38532),
('1797 Albatross Ct.', 26445),
('2136 A St.', 34560),
('3430 17th St.', 1826),
('7766 Ocean Ave.', 5124),
), columns=('Location', 'Revenue'))
locations_df
```
Given the two `DataFrame` objects mentioned above, perform the following tasks:
1. Merge the two dataframes to create a single dataframe with store names: average daily traffic and average daily revenue. Call this new `DataFrame` `performance_df`.
2. Make a new column in `performance_df`, showing the average daily revenue *per customer*. Call the new column 'Revenue per Customer'. Revenue per customer is defined as `rpc = revenue / traffic`.
3. Print the 'Location' of the store that has the highest 'Revenue per Customer'.
```
# Part 1: Perform merge
performance_df = None # ...
# Part 2: Create column
# ...
# Part 3: Print location of store with the most revenue per customer
# ...
```
---
| github_jupyter |
# Disciplina - DQF10648 Eletromagnetismo I
## Aula em 17/06/2021 - Semestre 2021/1 EARTE
### [DQF - CCENS](http://alegre.ufes.br/ccens/departamento-de-quimica-e-fisica) - [UFES/Alegre](http://alegre.ufes.br/)
# Coordenadas Curvilíneas
Sobre coordenadas cartesianas, polares, cilíndricas e esféricas, vide :
- [referências](https://github.com/rcolistete/Eletromagnetismo_I_UFES_Alegre/blob/master/Bibliografia.md) [Griffiths], [Barcarena3] e [Marques];
- [aulas dessa disciplina em 2014/1](https://github.com/rcolistete/Eletromagnetismo_I_UFES_Alegre/tree/master/Aulas/Aula_20210617/2014), dos dias 24/04/2014, 25/04/2014, 30/04/2014 e 08/05/2014;
- demonstrações gráficas gratuitas no site [Wolfram Demonstrations](https://demonstrations.wolfram.com/);
## 2D - em duas dimensões
- coordenadas cartesianas bidimensionais : $(x, y)$
- coordenadas polares : $(\rho, \theta)$
- outras
## 3D - em três dimensões
- coordenadas cartesianas tridimensionais : $(x, y, z)$
- coordenadas cilíndricas : $(\rho, \theta, z)$
- coordenadas esféricas : $(r, \theta, \phi)$
- outras
# Operadores Diferenciais Vetoriais
Sobre coordenadas cartesianas, polares, cilíndricas e esféricas, vide :
- [referências](https://github.com/rcolistete/Eletromagnetismo_I_UFES_Alegre/blob/master/Bibliografia.md) [Griffiths], [Barcarena2] e [Barcarena3];
- demonstrações gráficas gratuitas no site [Wolfram Demonstrations](https://demonstrations.wolfram.com/);
## Gradiente : $\vec{\nabla} f$
Vide também [aula dessa disciplina em 2014/1](https://github.com/rcolistete/Eletromagnetismo_I_UFES_Alegre/tree/master/Aulas/Aula_20210617/2014) do dia 24/04/2014.
### Teoria
Gradiente é um operador diferencial vetorial que atua sobre função escalar e gera função vetorial.
Operador diferencial vetorial gradiente (grad) em coordenadas cartesianas 2D $(x, y)$ :
$$\vec{\nabla} = \left\langle \frac{\partial}{\partial x}, \frac{\partial}{\partial y}\right\rangle = \frac{\partial}{\partial x}\hat{i} + \frac{\partial}{\partial y}\hat{j} $$
em coordenadas polares $(\rho, \theta)$ :
$$\vec{\nabla} = \left\langle \frac{\partial }{\partial \rho},\frac{1}{\rho}\frac{\partial }{\partial \theta }\right\rangle = \frac{\partial }{\partial \rho}\hat{\rho} + \frac{1}{\rho}\frac{\partial }{\partial \theta }\hat{\theta}$$
em coordenadas cartesianas 3D $(x, y, z)$ :
$$\vec{\nabla}=\left\langle \frac{\partial }{\partial x}, \frac{\partial }{\partial y}, \frac{\partial }{\partial z}\right\rangle = \frac{\partial}{\partial x}\hat{i} + \frac{\partial}{\partial y}\hat{j} + \frac{\partial}{\partial z}\hat{k}$$
Em coordenadas cilíndricas $(\rho, \theta, z)$ :
$$\vec{\nabla}=\left\langle \frac{\partial }{\partial \rho},\frac{1}{\rho}\frac{\partial }{\partial \theta},\frac{\partial }{\partial z}\right\rangle = \frac{\partial }{\partial \rho}\hat{\rho} + \frac{1}{\rho}\frac{\partial }{\partial \theta }\hat{\theta} + \frac{\partial }{\partial z}\hat{k} $$
Em coordenadas esféricas $(r, \theta, \phi)$ :
$$\vec{\nabla}=\left\langle \frac{\partial }{\partial r},\frac{1}{r}\frac{\partial }{\partial \theta},\frac{1}{r sen \theta}\frac{\partial }{\partial \phi}\right\rangle = \frac{\partial }{\partial r}\hat{r} + \frac{1}{r}\frac{\partial }{\partial \theta}\hat{\theta} + \frac{1}{r sen \theta}\frac{\partial }{\partial \phi}\hat{\phi}$$
## Divergente : $\vec{\nabla} \cdot \vec{F}$
Vide também [aulas dessa disciplina em 2014/1](https://github.com/rcolistete/Eletromagnetismo_I_UFES_Alegre/tree/master/Aulas/Aula_20210617/2014) dos dias 08/05/2014 e 09/05/2014.
### Teoria
Divergente é um operador diferencial vetorial que atua sobre função vetorial e gera função escalar.
Em coordenadas cartesianas 3D $(x, y, z)$ :
$$\vec{\nabla} \cdot \vec{F} = \frac{\partial F_x}{\partial x} + \frac{\partial F_y}{\partial y} + \frac{\partial F_z}{\partial z} $$
em coordenadas cilíndricas $(\rho, \theta, z)$ :
$$\vec{\nabla} \cdot \vec{F} = \frac{1}{\rho}\frac{\partial\,(\rho F_{\rho})}{\partial \rho} + \frac{1}{\rho}\frac{\partial F_{\theta}}{\partial \theta} + \frac{\partial F_z}{\partial z} $$
em coordenadas esféricas $(r, \theta, \phi)$ :
$$\vec{\nabla} \cdot \vec{F} = \frac{1}{r^2} \frac{\partial\,(r^2 F_r)}{\partial r} + \frac{1}{r sen \theta}\frac{\partial\,(sen \theta F_{\theta})}{\partial \theta} + \frac{1}{r sen \theta}\frac{\partial F_\phi}{\partial \phi} $$
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Better performance with the tf.data API
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/data_performance"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/data_performance.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/guide/data_performance.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/data_performance.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
## Overview
GPUs and TPUs can radically reduce the time required to execute a single training step.
Achieving peak performance requires an efficient input pipeline that delivers data for the next step before the current step has finished.
The `tf.data` API helps to build flexible and efficient input pipelines.
This document demonstrates how to use the `tf.data` API to build highly performant TensorFlow input pipelines.
Before you continue, read the "[Build TensorFlow input pipelines](./data.ipynb)" guide, to learn how to use the `tf.data` API.
## Resources
* [Build TensorFlow input pipelines](./data.ipynb)
* `tf.data.Dataset` API
## Setup
```
from __future__ import absolute_import, division, print_function, unicode_literals
try:
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
import time
```
Throughout this guide, you will iterate across a dataset and measure the performance.
Making reproducible performance benchmarks can be difficult, different factors impacting it:
- the current CPU load,
- the network traffic,
- complex mechanisms like cache, etc.
Hence, to provide a reproducible benchmark, build an artificial example.
### The dataset
Define a class inheriting from `tf.data.Dataset` called `ArtificialDataset`.
This dataset:
- generates `num_samples` samples (default is 3)
- sleeps for some time before the first item to simulate opening a file
- sleeps for some time before producing each item to simulate reading data from a file
```
class ArtificialDataset(tf.data.Dataset):
def _generator(num_samples):
# Opening the file
time.sleep(0.03)
for sample_idx in range(num_samples):
# Reading data (line, record) from the file
time.sleep(0.015)
yield (sample_idx,)
def __new__(cls, num_samples=3):
return tf.data.Dataset.from_generator(
cls._generator,
output_types=tf.dtypes.int64,
output_shapes=(1,),
args=(num_samples,)
)
```
This dataset is similar to the `tf.data.Dataset.range` one, adding a fixed delay at the beginning and between each sample.
### The training loop
Write a dummy training loop that measures how long it takes to iterate over a dataset.
Training time is simulated.
```
def benchmark(dataset, num_epochs=2):
start_time = time.perf_counter()
for epoch_num in range(num_epochs):
for sample in dataset:
# Performing a training step
time.sleep(0.01)
tf.print("Execution time:", time.perf_counter() - start_time)
```
## Optimize performance
To exhibit how performance can be optimized, you will improve the performance of the `ArtificialDataset`.
### The naive approach
Start with a naive pipeline using no tricks, iterating over the dataset as-is.
```
benchmark(ArtificialDataset())
```
Under the hood, this is how your execution time was spent:

You can see that performing a training step involves:
- opening a file if it hasn't been opened yet,
- fetching a data entry from the file,
- using the data for training.
However, in a naive synchronous implementation like here, while your pipeline is fetching the data, your model is sitting idle.
Conversely, while your model is training, the input pipeline is sitting idle.
The training step time is thus the sum of all, opening, reading and training time.
The next sections build on this input pipeline, illustrating best practices for designing performant TensorFlow input pipelines.
### Prefetching
Prefetching overlaps the preprocessing and model execution of a training step.
While the model is executing training step `s`, the input pipeline is reading the data for step `s+1`.
Doing so reduces the step time to the maximum (as opposed to the sum) of the training and the time it takes to extract the data.
The `tf.data` API provides the `tf.data.Dataset.prefetch` transformation.
It can be used to decouple the time when data is produced from the time when data is consumed.
In particular, the transformation uses a background thread and an internal buffer to prefetch elements from the input dataset ahead of the time they are requested.
The number of elements to prefetch should be equal to (or possibly greater than) the number of batches consumed by a single training step.
You could either manually tune this value, or set it to `tf.data.experimental.AUTOTUNE` which will prompt the
`tf.data` runtime to tune the value dynamically at runtime.
Note that the prefetch transformation provides benefits any time there is an opportunity to overlap the work of a "producer" with the work of a "consumer."
```
benchmark(
ArtificialDataset()
.prefetch(tf.data.experimental.AUTOTUNE)
)
```

This time you can see that while the training step is running for sample 0, the input pipeline is reading the data for the sample 1, and so on.
### Parallelizing data extraction
In a real-world setting, the input data may be stored remotely (for example, GCS or HDFS).
A dataset pipeline that works well when reading data locally might become bottlenecked on I/O when reading data remotely because of the following differences between local and remote storage:
* **Time-to-first-byte:** Reading the first byte of a file from remote storage can take orders of magnitude longer than from local storage.
* **Read throughput:** While remote storage typically offers large aggregate bandwidth, reading a single file might only be able to utilize a small fraction of this bandwidth.
In addition, once the raw bytes are loaded into memory, it may also be necessary to deserialize and/or decrypt the data (e.g. [protobuf](https://developers.google.com/protocol-buffers/)), which requires additional computation.
This overhead is present irrespective of whether the data is stored locally or remotely, but can be worse in the remote case if data is not prefetched effectively.
To mitigate the impact of the various data extraction overheads, the `tf.data.Dataset.interleave` transformation can be used to parallelize the data loading step, interleaving the contents of other datasets (such as data file
readers).
The number of datasets to overlap can be specified by the `cycle_length` argument, while the level of parallelism can be specified by the `num_parallel_calls` argument. Similar to the `prefetch` transformation, the `interleave` transformation supports `tf.data.experimental.AUTOTUNE` which will delegate the decision about what level of parallelism to use to the `tf.data` runtime.
#### Sequential interleave
The default arguments of the `tf.data.Dataset.interleave` transformation make it interleave single samples from two datasets sequentially.
```
benchmark(
tf.data.Dataset.range(2)
.interleave(ArtificialDataset)
)
```

This plot allows to exhibit the behavior of the `interleave` transformation, fetching samples alternatively from the two datasets available.
However, no performance improvement is involved here.
#### Parallel interleave
Now use the `num_parallel_calls` argument of the `interleave` transformation.
This loads multiple datasets in parallel, reducing the time waiting for the files to be opened.
```
benchmark(
tf.data.Dataset.range(2)
.interleave(
ArtificialDataset,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
)
```

This time, the reading of the two datasets is parallelized, reducing the global data processing time.
### Parallelizing data transformation
When preparing data, input elements may need to be pre-processed.
To this end, the `tf.data` API offers the `tf.data.Dataset.map` transformation, which applies a user-defined function to each element of the input dataset.
Because input elements are independent of one another, the pre-processing can be parallelized across multiple CPU cores.
To make this possible, similarly to the `prefetch` and `interleave` transformations, the `map` transformation provides the `num_parallel_calls` argument to specify the level of parallelism.
Choosing the best value for the `num_parallel_calls` argument depends on your hardware, characteristics of your training data (such as its size and shape), the cost of your map function, and what other processing is happening on the CPU at the same time.
A simple heuristic is to use the number of available CPU cores.
However, as for the `prefetch` and `interleave` transformation, the `map` transformation supports `tf.data.experimental.AUTOTUNE` which will delegate the decision about what level of parallelism to use to the `tf.data` runtime.
```
def mapped_function(s):
# Do some hard pre-processing
tf.py_function(lambda: time.sleep(0.03), [], ())
return s
```
#### Sequential mapping
Start by using the `map` transformation without parallelism as a baseline example.
```
benchmark(
ArtificialDataset()
.map(mapped_function)
)
```

As for the [naive approach](#The-naive-approach), here the times spent for opening, reading, pre-processing (mapping) and training steps sum together for a single iteration.
#### Parallel mapping
Now, use the same pre-processing function but apply it in parallel on multiple samples.
```
benchmark(
ArtificialDataset()
.map(
mapped_function,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
)
```

Now, you can see on the plot that the pre-processing steps overlap, reducing the overall time for a single iteration.
### Caching
The `tf.data.Dataset.cache` transformation can cache a dataset, either in memory or on local storage.
This will save some operations (like file opening and data reading) from being executed during each epoch.
```
benchmark(
ArtificialDataset()
.map( # Apply time consuming operations before cache
mapped_function
).cache(
),
5
)
```

When you cache a dataset, the transformations before the `cache` one (like the file opening and data reading) are executed only during the first epoch.
The next epochs will reuse the data cached by the`cache` transformation.
If the user-defined function passed into the `map` transformation is expensive, apply the `cache` transformation after the `map` transformation as long as the resulting dataset can still fit into memory or local storage.
If the user-defined function increases the space required to store the dataset beyond the cache capacity, either apply it after the `cache` transformation or consider pre-processing your data before your training job to reduce resource usage.
### Vectorizing mapping
Invoking a user-defined function passed into the `map` transformation has overhead related to scheduling and executing the user-defined function.
We recommend vectorizing the user-defined function (that is, have it operate over a batch of inputs at once) and apply the `batch` transformation _before_ the `map` transformation.
To illustrate this good practice, your artificial dataset is not suitable.
The scheduling delay is around 10 microseconds (10e-6 seconds), far less than the tens of milliseconds used in the `ArtificialDataset`, and thus its impact is hard to see.
For this example, use the base `tf.data.Dataset.range` function and simplify the training loop to its simplest form.
```
fast_dataset = tf.data.Dataset.range(10000)
def fast_benchmark(dataset, num_epochs=2):
start_time = time.perf_counter()
for _ in tf.data.Dataset.range(num_epochs):
for _ in dataset:
pass
tf.print("Execution time:", time.perf_counter() - start_time)
def increment(x):
return x+1
```
#### Scalar mapping
```
fast_benchmark(
fast_dataset
# Apply function one item at a time
.map(increment)
# Batch
.batch(256)
)
```

The plot above illustrate what is going on (with less samples).
You can see that the mapped function is applied for each sample.
While this function is very fast, it has some overhead that impact the time performance.
#### Vectorized mapping
```
fast_benchmark(
fast_dataset
.batch(256)
# Apply function on a batch of items
# The tf.Tensor.__add__ method already handle batches
.map(increment)
)
```

This time, the mapped function is called once and applies to a batch of sample.
While the function could takes more time to execute, the overhead appear only once, improving the overall time performance.
### Reducing memory footprint
A number of transformations, including `interleave`, `prefetch`, and `shuffle`,
maintain an internal buffer of elements. If the user-defined function passed
into the `map` transformation changes the size of the elements, then the
ordering of the map transformation and the transformations that buffer elements
affects the memory usage. In general, we recommend choosing the order that
results in lower memory footprint, unless different ordering is desirable for
performance.
#### Caching partial computations
It is recommended to cache the dataset after the `map` transformation except if this transformation makes the data too big to fit in memory.
A trade-off can be achieved if your mapped function can be split in two parts: a time consuming one and a memory consuming part.
In this case, you can chain your transformations like below:
```python
dataset.map(time_consuming_mapping).cache().map(memory_consuming_mapping)
```
This way, the time consuming part is only executed during the first epoch, and you avoid using too much cache space.
## Best practice summary
Here is a summary of the best practices for designing performant TensorFlow
input pipelines:
* [Use the `prefetch` transformation](#Pipelining) to overlap the work of a producer and consumer.
* [Parallelize the data reading transformation](#Parallelizing-data-extraction) using the `interleave` transformation.
* [Parallelize the `map` transformation](#Parallelizing-data-transformation) by setting the `num_parallel_calls` argument.
* [Use the `cache` transformation](#Caching) to cache data in memory during the first epoch
* [Vectorize user-defined functions](#Map-and-batch) passed in to the `map` transformation
* [Reduce memory usage](#Reducing-memory-footprint) when applying the `interleave`, `prefetch`, and `shuffle` transformations.
## Reproducing the figures
Note: The rest of this notebook is about how to reproduce the above figures, feel free to play around with this code, but understanding it is not an essential part of this tutorial.
To go deeper in the `tf.data.Dataset` API understanding, you can play with your own pipelines.
Below is the code used to plot the images from this guide.
It can be a good starting point, showing some workarounds for common difficulties such as:
- Execution time reproducibility;
- Mapped functions eager execution;
- `interleave` transformation callable.
```
import itertools
from collections import defaultdict
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
```
### The dataset
Similar to the `ArtificialDataset` you can build a dataset returning the time spent in each step.
```
class TimeMeasuredDataset(tf.data.Dataset):
# OUTPUT: (steps, timings, counters)
OUTPUT_TYPES = (tf.dtypes.string, tf.dtypes.float32, tf.dtypes.int32)
OUTPUT_SHAPES = ((2, 1), (2, 2), (2, 3))
_INSTANCES_COUNTER = itertools.count() # Number of datasets generated
_EPOCHS_COUNTER = defaultdict(itertools.count) # Number of epochs done for each dataset
def _generator(instance_idx, num_samples):
epoch_idx = next(TimeMeasuredDataset._EPOCHS_COUNTER[instance_idx])
# Opening the file
open_enter = time.perf_counter()
time.sleep(0.03)
open_elapsed = time.perf_counter() - open_enter
for sample_idx in range(num_samples):
# Reading data (line, record) from the file
read_enter = time.perf_counter()
time.sleep(0.015)
read_elapsed = time.perf_counter() - read_enter
yield (
[("Open",), ("Read",)],
[(open_enter, open_elapsed), (read_enter, read_elapsed)],
[(instance_idx, epoch_idx, -1), (instance_idx, epoch_idx, sample_idx)]
)
open_enter, open_elapsed = -1., -1. # Negative values will be filtered
def __new__(cls, num_samples=3):
return tf.data.Dataset.from_generator(
cls._generator,
output_types=cls.OUTPUT_TYPES,
output_shapes=cls.OUTPUT_SHAPES,
args=(next(cls._INSTANCES_COUNTER), num_samples)
)
```
This dataset provides samples of shape `[[2, 1], [2, 2], [2, 3]]` and of type `[tf.dtypes.string, tf.dtypes.float32, tf.dtypes.int32]`.
Each sample is:
```
(
[("Open"), ("Read")],
[(t0, d), (t0, d)],
[(i, e, -1), (i, e, s)]
)
```
Where:
- `Open` and `Read` are steps identifiers
- `t0` is the timestamp when the corresponding step started
- `d` is the time spent in the corresponding step
- `i` is the instance index
- `e` is the epoch index (number of times the dataset has been iterated)
- `s` is the sample index
### The iteration loop
Make the iteration loop a little bit more complicated to aggregate all timings.
This will only work with datasets generating samples as detailed above.
```
def timelined_benchmark(dataset, num_epochs=2):
# Initialize accumulators
steps_acc = tf.zeros([0, 1], dtype=tf.dtypes.string)
times_acc = tf.zeros([0, 2], dtype=tf.dtypes.float32)
values_acc = tf.zeros([0, 3], dtype=tf.dtypes.int32)
start_time = time.perf_counter()
for epoch_num in range(num_epochs):
epoch_enter = time.perf_counter()
for (steps, times, values) in dataset:
# Record dataset preparation informations
steps_acc = tf.concat((steps_acc, steps), axis=0)
times_acc = tf.concat((times_acc, times), axis=0)
values_acc = tf.concat((values_acc, values), axis=0)
# Simulate training time
train_enter = time.perf_counter()
time.sleep(0.01)
train_elapsed = time.perf_counter() - train_enter
# Record training informations
steps_acc = tf.concat((steps_acc, [["Train"]]), axis=0)
times_acc = tf.concat((times_acc, [(train_enter, train_elapsed)]), axis=0)
values_acc = tf.concat((values_acc, [values[-1]]), axis=0)
epoch_elapsed = time.perf_counter() - epoch_enter
# Record epoch informations
steps_acc = tf.concat((steps_acc, [["Epoch"]]), axis=0)
times_acc = tf.concat((times_acc, [(epoch_enter, epoch_elapsed)]), axis=0)
values_acc = tf.concat((values_acc, [[-1, epoch_num, -1]]), axis=0)
time.sleep(0.001)
tf.print("Execution time:", time.perf_counter() - start_time)
return {"steps": steps_acc, "times": times_acc, "values": values_acc}
```
### The plotting method
Finally, define a function able to plot a timeline given the values returned by the `timelined_benchmark` function.
```
def draw_timeline(timeline, title, width=0.5, annotate=False, save=False):
# Remove invalid entries (negative times, or empty steps) from the timelines
invalid_mask = np.logical_and(timeline['times'] > 0, timeline['steps'] != b'')[:,0]
steps = timeline['steps'][invalid_mask].numpy()
times = timeline['times'][invalid_mask].numpy()
values = timeline['values'][invalid_mask].numpy()
# Get a set of different steps, ordered by the first time they are encountered
step_ids, indices = np.stack(np.unique(steps, return_index=True))
step_ids = step_ids[np.argsort(indices)]
# Shift the starting time to 0 and compute the maximal time value
min_time = times[:,0].min()
times[:,0] = (times[:,0] - min_time)
end = max(width, (times[:,0]+times[:,1]).max() + 0.01)
cmap = mpl.cm.get_cmap("plasma")
plt.close()
fig, axs = plt.subplots(len(step_ids), sharex=True, gridspec_kw={'hspace': 0})
fig.suptitle(title)
fig.set_size_inches(17.0, len(step_ids))
plt.xlim(-0.01, end)
for i, step in enumerate(step_ids):
step_name = step.decode()
ax = axs[i]
ax.set_ylabel(step_name)
ax.set_ylim(0, 1)
ax.set_yticks([])
ax.set_xlabel("time (s)")
ax.set_xticklabels([])
ax.grid(which="both", axis="x", color="k", linestyle=":")
# Get timings and annotation for the given step
entries_mask = np.squeeze(steps==step)
serie = np.unique(times[entries_mask], axis=0)
annotations = values[entries_mask]
ax.broken_barh(serie, (0, 1), color=cmap(i / len(step_ids)), linewidth=1, alpha=0.66)
if annotate:
for j, (start, width) in enumerate(serie):
annotation = "\n".join([f"{l}: {v}" for l,v in zip(("i", "e", "s"), annotations[j])])
ax.text(start + 0.001 + (0.001 * (j % 2)), 0.55 - (0.1 * (j % 2)), annotation,
horizontalalignment='left', verticalalignment='center')
if save:
plt.savefig(title.lower().translate(str.maketrans(" ", "_")) + ".svg")
```
### Use wrappers for mapped function
To run mapped function in an eager context, you have to wrap them inside a `tf.py_function` call.
```
def map_decorator(func):
def wrapper(steps, times, values):
# Use a tf.py_function to prevent auto-graph from compiling the method
return tf.py_function(
func,
inp=(steps, times, values),
Tout=(steps.dtype, times.dtype, values.dtype)
)
return wrapper
```
### Pipelines comparison
```
_batch_map_num_items = 50
def dataset_generator_fun(*args):
return TimeMeasuredDataset(num_samples=_batch_map_num_items)
```
#### Naive
```
@map_decorator
def naive_map(steps, times, values):
map_enter = time.perf_counter()
time.sleep(0.001) # Time contumming step
time.sleep(0.0001) # Memory consumming step
map_elapsed = time.perf_counter() - map_enter
return (
tf.concat((steps, [["Map"]]), axis=0),
tf.concat((times, [[map_enter, map_elapsed]]), axis=0),
tf.concat((values, [values[-1]]), axis=0)
)
naive_timeline = timelined_benchmark(
tf.data.Dataset.range(2)
.flat_map(dataset_generator_fun)
.map(naive_map)
.batch(_batch_map_num_items, drop_remainder=True)
.unbatch(),
5
)
```
### Optimized
```
@map_decorator
def time_consumming_map(steps, times, values):
map_enter = time.perf_counter()
time.sleep(0.001 * values.shape[0]) # Time contumming step
map_elapsed = time.perf_counter() - map_enter
return (
tf.concat((steps, tf.tile([[["1st map"]]], [steps.shape[0], 1, 1])), axis=1),
tf.concat((times, tf.tile([[[map_enter, map_elapsed]]], [times.shape[0], 1, 1])), axis=1),
tf.concat((values, tf.tile([[values[:][-1][0]]], [values.shape[0], 1, 1])), axis=1)
)
@map_decorator
def memory_consumming_map(steps, times, values):
map_enter = time.perf_counter()
time.sleep(0.0001 * values.shape[0]) # Memory consumming step
map_elapsed = time.perf_counter() - map_enter
# Use tf.tile to handle batch dimension
return (
tf.concat((steps, tf.tile([[["2nd map"]]], [steps.shape[0], 1, 1])), axis=1),
tf.concat((times, tf.tile([[[map_enter, map_elapsed]]], [times.shape[0], 1, 1])), axis=1),
tf.concat((values, tf.tile([[values[:][-1][0]]], [values.shape[0], 1, 1])), axis=1)
)
optimized_timeline = timelined_benchmark(
tf.data.Dataset.range(2)
.interleave( # Parallelize data reading
dataset_generator_fun,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
.batch( # Vectorize your mapped function
_batch_map_num_items,
drop_remainder=True)
.map( # Parallelize map transformation
time_consumming_map,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
.cache() # Cache data
.map( # Reduce memory usage
memory_consumming_map,
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
.prefetch( # Overlap producer and consumer works
tf.data.experimental.AUTOTUNE
)
.unbatch(),
5
)
draw_timeline(naive_timeline, "Naive", 15)
draw_timeline(optimized_timeline, "Optimized", 15)
```
| github_jupyter |

# Qiskit Runtime on IBM Cloud
Qiskit Runtime is now part of the IBM Quantum Services on IBM Cloud. To use this service, you'll need to create an IBM Cloud account and a quantum service instance. [This guide](https://cloud.ibm.com/docs/quantum-computing?topic=quantum-computing-gettingstarted) contains step-by-step instructions on setting this up, including directions to find your IBM Cloud API key and Cloud Resource Name (CRN), which you will need later in this tutorial.
This tutorial assumes that you know how to use Qiskit, including using it to create circuits. If you are not familiar with Qiskit, the [Qiskit Textbook](https://qiskit.org/textbook/preface.html) is a great resource to learn about both Qiskit and quantum computation in general.
# qiskit-ibm-runtime
Once you have an IBM Cloud account and service instance set up, you can use `qiskit-ibm-runtime` to access Qiskit Runtime on IBM Cloud. `qiskit-ibm-runtime` provides the interface to interact with Qiskit Runtime. You can, for example, use it to query and execute runtime programs.
## Installation
You can install the `qiskit-ibm-runtime` package using pip:
```
pip install qiskit-ibm-runtime
```
## Account initialization
Before you can start using Qiskit Runtime, you need to initialize your account by calling `QiskitRuntimeService` with your IBM Cloud API key and the CRN or service name of your service instance.
You can also choose to save your credentials on disk (in the `$HOME/.qiskit/qiskit-ibm.json` file). By doing so, you only need to use `QiskitRuntimeService()` in the future to initialize your account.
For more information about account management, such as how to delete or view an account, see [04_account_management.ipynb](04_account_management.ipynb).
<div class="alert alert-block alert-info">
<b>Note:</b> Account credentials are saved in plain text, so only do so if you are using a trusted device.
</div>
```
from qiskit_ibm_runtime import QiskitRuntimeService
# Save account on disk.
# QiskitRuntimeService.save_account(channel="ibm_cloud", token=<IBM Cloud API key>, instance=<IBM Cloud CRN> or <IBM Cloud service name>)
service = QiskitRuntimeService()
```
The `<IBM Cloud API key>` in the example above is your IBM Cloud API key and looks something like
```
kYgdggnD-qx5k2u0AAFUKv3ZPW_avg0eQ9sK75CCW7hw
```
The `<IBM Cloud CRN>` is the Cloud Resource Name and looks something like
```
crn:v1:bluemix:public:quantum-computing:us-east:a/b947c1c5a9378d64aed96696e4d76e8e:a3a7f181-35aa-42c8-94d6-7c8ed6e1a94b::
```
The `<IBM Cloud service name>` is user-provided and defaults to something like
```
Quantum Services-9p
```
If you choose to set `instance` to the service name, the initialization time of the `QiskitRuntimeService` is slightly higher because the required `CRN` value is internally resolved via IBM Cloud APIs.
## Listing programs <a name='listing_program'>
There are three methods that can be used to find metadata of available programs:
- `pprint_programs()`: pretty prints summary metadata of available programs
- `programs()`: returns a list of `RuntimeProgram` instances
- `program()`: returns a single `RuntimeProgram` instance
The metadata of a runtime program includes its ID, name, description, maximum execution time, backend requirements, input parameters, and return values. Maximum execution time is the maximum amount of time, in seconds, a program can run before being forcibly terminated.
To print the summary metadata of the programs (by default first 20 programs are displayed):
```
service.pprint_programs(limit=None)
```
You can use the `limit` and `skip` parameters in `pprint_programs()` and `programs()` to page through all programs.
You can pass `detailed=True` parameter to `pprint_programs()` to view all the metadata for the programs.
The program metadata, once fetched, is cached for performance reasons. But you can pass the `refresh=True` parameter to get the latest data from the server.
To print the metadata of the program `sampler`:
```
program = service.program("sampler")
print(program)
```
As you can see from above, the primitive `sampler` calculates the distributions generated by given circuits executed on the target backend. It takes a number of parameters, but `circuits` and `circuit_indices` are the only required parameters. When the program finishes, it returns the quasi-probabilities for each circuit.
## Invoking a runtime program <a name='invoking_program'>
You can use the [QiskitRuntimeService.run()](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.QiskitRuntimeService.html#qiskit_ibm_runtime.QiskitRuntimeService.run) method to invoke a runtime program. This method takes the following parameters:
- `program_id`: ID of the program to run.
- `inputs`: Program input parameters. These input values are passed to the runtime program.
- `options`: Runtime options. These options control the execution environment. Currently the only available option is `backend_name`, which is optional for cloud runtime.
- `result_decoder`: Optional class used to decode the job result.
Below is an example of invoking the `sampler` program.
First we need to construct a circuit as the input to `sampler` using Qiskit.
```
from qiskit import QuantumCircuit
N = 6
qc = QuantumCircuit(N)
qc.x(range(0, N))
qc.h(range(0, N))
for kk in range(N // 2, 0, -1):
qc.ch(kk, kk - 1)
for kk in range(N // 2, N - 1):
qc.ch(kk, kk + 1)
qc.measure_all()
qc.draw("mpl", fold=-1)
```
We now use this circuit as the input to `sampler`:
```
# Specify the program inputs here.
program_inputs = {
"circuits": qc,
"circuit_indices": [0],
}
job = service.run(
program_id="sampler",
inputs=program_inputs,
)
# Printing the job ID in case we need to retrieve it later.
print(f"Job ID: {job.job_id}")
# Get the job result - this is blocking and control may not return immediately.
result = job.result()
print(result)
# see which backend the job was executed on
print(job.backend)
```
### Runtime job
The `run()` method returns a [RuntimeJob](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.RuntimeJob.html#qiskit_ibm_runtime.RuntimeJob) instance, which represents the asynchronous execution instance of the program.
Some of the `RuntimeJob` methods:
- `status()`: Return job status.
- `result()`: Wait for the job to finish and return the final result.
- `cancel()`: Cancel the job.
- `wait_for_final_state()`: Wait for the job to finish.
- `logs()`: Return job logs.
- `error_message()`: Returns the reason if the job failed and `None` otherwise.
Some of the `RuntimeJob` attributes:
- `job_id`: Unique identifier of the job.
- `backend`: The backend where the job is run.
- `program_id`: ID of the program the execution is for.
Refer to the [RuntimeJob API documentation](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.RuntimeJob.html#qiskit_ibm_runtime.RuntimeJob) for a full list of methods and usage.
<div class="alert alert-block alert-info">
<b>Note:</b> To ensure fairness, there is a maximum execution time for each Qiskit Runtime job. Refer to <a href="https://qiskit.org/documentation/partners/qiskit_ibm_runtime/max_time.html#qiskit-runtime-on-ibm-cloud">this documentation</a> on what the time limit is.
</div>
## Selecting a backend
A **backend** is a quantum device or simulator capable of running quantum circuits or pulse schedules.
In the example above, we invoked a runtime program without specifying which backend it should run on. In this case the server automatically picks the one that is the least busy. Alternatively, you can choose a specific backend to run your program.
To list all the backends you have access to:
```
service.backends()
```
The [QiskitRuntimeService.backends()](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.QiskitRuntimeService.html#qiskit_ibm_runtime.QiskitRuntimeService.backends) method also takes filters. For example, to find all real devices that have at least five qubits:
```
service.backends(simulator=False, min_num_qubits=5)
```
[QiskitRuntimeService.backends()](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.QiskitRuntimeService.html#qiskit_ibm_runtime.QiskitRuntimeService.backends) returns a list of [IBMBackend](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.IBMBackend.html#qiskit_ibm_runtime.IBMBackend) instances. Each instance represents a particular backend. Attributes and methods of an `IBMBackend` provide more information about the backend, such as its qubit count, error rate, and status.
For more information about backends, such as commonly used attributes, see [03_backends.ipynb](03_backends.ipynb).
Once you select a backend to use, you can specify the name of the backend in the `options` parameter:
```
# Specify the program inputs here.
program_inputs = {
"circuits": qc,
"circuit_indices": [0],
}
# Specify the backend name.
options = {"backend_name": "ibmq_qasm_simulator"}
job = service.run(
program_id="sampler",
options=options,
inputs=program_inputs,
)
# Printing the job ID in case we need to retrieve it later.
print(f"Job ID: {job.job_id}")
# Get the job result - this is blocking and control may not return immediately.
result = job.result()
print(result)
```
## Retrieving previously run jobs
You can use the [QiskitRuntimeService.job()](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.QiskitRuntimeService.html#qiskit_ibm_runtime.QiskitRuntimeService.job) method to retrieve a previously executed runtime job. Attributes of this [RuntimeJob](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.RuntimeJob.html#qiskit_ibm_runtime.RuntimeJob) instance can tell you about the execution:
```
retrieved_job = service.job(job.job_id)
print(
f"Job {retrieved_job.job_id} is an execution instance of runtime program {retrieved_job.program_id}."
)
print(
f"This job ran on backend {retrieved_job.backend} and had input parameters {retrieved_job.inputs}"
)
```
Similarly, you can use [QiskitRuntimeService.jobs()](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.QiskitRuntimeService.html#qiskit_ibm_runtime.QiskitRuntimeService.jobs) to get a list of jobs. You can specify a limit on how many jobs to return. The default limit is 10:
```
retrieved_jobs = service.jobs(limit=1)
for rjob in retrieved_jobs:
print(rjob.job_id)
```
## Deleting a job
You can use the [QiskitRuntimeService.delete_job()](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/stubs/qiskit_ibm_runtime.QiskitRuntimeService.html#qiskit_ibm_runtime.QiskitRuntimeService.delete_job) method to delete a job. You can only delete your own jobs, and this action cannot be reversed.
```
service.delete_job(job.job_id)
```
# Next steps
There are additional tutorials in this directory:
- [02_introduction_ibm_quantum_runtime.ipynb](02_introduction_ibm_quantum_runtime.ipynb) is the corresponding tutorial on using Qiskit Runtime on IBM Quantum. You can skip this tutorial if you don't plan on using Qiskit Runtime on IBM Quantum.
- [03_backends.ipynb](03_backends.ipynb) describes how to find a target backend for the Qiskit Runtime program you want to invoke.
- [04_account_management.ipynb](04_account_management.ipynb) describes how to save, load, and delete your account credentials on disk.
- [qiskit_runtime_vqe_program.ipynb](sample_vqe_program/qiskit_runtime_vqe_program.ipynb) goes into more details on uploading a real-world program (VQE).
- [qka.ipynb](qka.ipynb), [vqe.ipynb](vqe.ipynb), and [qiskit_runtime_expval_program.ipynb](sample_expval_program/qiskit_runtime_expval_program.ipynb) describe how to use the public programs `qka`, `vqe`, and `sample-expval`, respectively. These programs are currently only available in Qiskit Runtime on IBM Quantum.
```
from qiskit.tools.jupyter import *
%qiskit_copyright
```
| github_jupyter |
```
import os
import fnmatch
import numpy as np
import pandas as pd
import pint
import sympy
import sissotools
from sissotools import io
from sissotools import dimensional_analysis
from sissotools import regression
from sissotools import plotting
try:
from tqdm import tqdm
except ImportError:
# Optional import
class tqdm:
"""Progress bar placeholder"""
def __init__(self, iterable=None, total=0):
self.count = 0
self.total = total
if iterable is not None:
self.iterable = iterable
if hasattr(iterable, "__len__"):
self.total = len(iterable)
else:
self.iterable = []
def __iter__(self):
for obj in self.iterable:
self.count += 1
print(self.count, "/", self.total)
yield obj
def update(self, n=1):
self.count += n
print(self.count, "/", self.total)
%matplotlib inline
```
# I/O Options
```
input_filename = "./data_AD.txt"
working_directory = "./demo"
features_fname = os.path.join(working_directory, "feature_space/Uspace.name")
file_list = os.listdir(os.path.join(working_directory, "models"))
models_fname = fnmatch.filter(file_list, "top*0_001d").pop()
models_fname = os.path.join(working_directory, "models", models_fname)
coeff_fname = fnmatch.filter(file_list, "top*_001d_coeff").pop()
coeff_fname = os.path.join(working_directory, "models", coeff_fname)
file_checks = [os.path.isfile(fname) for fname
in [features_fname, models_fname, coeff_fname]]
if not all(file_checks):
raise RuntimeError("Please ensure demo_inputs.ipynb has completed.")
```
# Read Files
```
# parse tab-separated-value file
df_train = io.read_tsv(input_filename)
# parse SISSO outputs
df_features = io.read_features(features_fname)
df_models = io.read_models(models_fname)
df_coeff = io.read_coefficients(coeff_fname)
df_features.head() # feature_space/Uspace.name
df_models.head() # models/"top*0_001d"
df_coeff.head() # models/"top*0_001d_coeff"
```
# Filtering by units
```
# Define units per feature
unit_ref = {'wlog': 'K',
'w2': 'K',
'lambd': 'dimensionless',
'mus': 'dimensionless'}
# Set desired units
target_units = "[temperature]"
target_degree = 1
filtered_indices = []
for model_row in df_models.itertuples():
# loop over models, sorted by RMSE
idx, rmse, mae, feature_id = model_row
intercept, slope = df_coeff.loc[idx]
feature, correlation = df_features.loc[feature_id]
dims, degree = dimensional_analysis.check_dimensionality(
feature, unit_ref)
if dims == target_units and degree == target_degree:
filtered_indices.append(idx)
print("Filtered by units. Remaining: {} / {}".format(
len(filtered_indices), len(df_models)))
```
# Filtering by other constraints
```
feature_columns = ["wlog", "lambd", "mus"]
lambda_res = 401 # resolution: 0.01
mus_res = 61 # resolution: 0.01
wlog_res = 100 # resolution: 10 K
lambda_range = np.linspace(0, 4, lambda_res)
mus_range = np.linspace(0.1, 0.16, mus_res)
wlog_range = np.linspace(10, 1000, wlog_res)
lambda_range[0] += 1e-9 # evaluate one-sided limit
validation_meshes = np.meshgrid(wlog_range, lambda_range, mus_range)
validation_space = np.vstack([mesh.flatten() for mesh
in validation_meshes]).T
df_val = pd.DataFrame(columns=feature_columns,
data=validation_space)
print("Validation points:", len(validation_space))
transform = "({}) / wlog" # normalize
idx_pass = []
checks_fail = {}
for idx in tqdm(filtered_indices):
feature_id = df_models.loc[idx, "feature id"]
expr = df_features.loc[feature_id, "Feature"]
expr = transform.format(expr)
coeff = tuple(df_coeff.loc[idx][::-1])
values, _ = regression.evaluate_model(expr,
df_val,
feature_columns,
coeff)
lambda_sort = np.argsort(validation_space[:, 1])
unique_lambda, counts = np.unique(validation_space[:, 1],
return_counts=True)
split_indices = np.cumsum(counts)[:-1]
split_values = np.array_split(values[lambda_sort], split_indices)
lower_curve = np.array([np.min(batch) for batch in split_values])
upper_curve = np.array([np.max(batch) for batch in split_values])
lower_gradient = np.gradient(lower_curve)
upper_gradient = np.gradient(upper_curve)
checks = [np.all(np.isfinite(values)), # finite
np.all(values > 0), # strictly positive
np.all(lower_gradient>=0), # monotonic
np.all(upper_gradient>=0), # monotonic
lower_gradient[0] < 1e-3, # lambda limit
upper_gradient[0] < 1e-3, # lambda limit
]
if np.all(checks):
idx_pass.append(idx)
else:
checks_fail[idx] = checks
print("Filtered by physical constraints. Remaining: {} / {}".format(
len(idx_pass), len(filtered_indices)))
```
# Summarizing filtered models
```
rmse_list = df_models.loc[idx_pass, "rmse"]
features_idx = df_models.loc[idx_pass, "feature id"].values
features_list = df_features.loc[features_idx, "Feature"]
slope_list = df_coeff.loc[idx_pass, "slope"]
data = np.vstack([rmse_list, slope_list]).T
df_summary = pd.DataFrame(data=data,
columns=["RMSE", "Coeff."],
index=features_list)
df_summary
```
# Visualizing filtered models
```
lambda_res = 401 # resolution: 0.01
lambda_range = np.linspace(0, 4, lambda_res)
lambda_range[0] = 1e-9
wlog_range = [50]
mus_range = [0.1]
validation_meshes = np.meshgrid(wlog_range, lambda_range, mus_range)
validation_space = np.vstack([mesh.flatten() for mesh
in validation_meshes]).T
df_val = pd.DataFrame(columns=feature_columns,
data=validation_space)
print("Plotting points:", len(validation_space))
import matplotlib.pyplot as plt
plt.figure(figsize=(3.5, 3), dpi=150)
for i, (expr, slope) in enumerate(zip(features_list, slope_list)):
coeff = (slope, 0)
expr = transform.format(expr)
values, _ = regression.evaluate_model(expr,
df_val,
feature_columns,
coeff)
if i == 0:
plt.plot(lambda_range,
values,
linewidth=3,
color='cornflowerblue',
zorder=10)
else:
plt.plot(lambda_range, values, linewidth=1, color='k', alpha=0.5)
plt.plot([], [], linewidth=3, color='cornflowerblue', label="Best Equation")
plt.plot([], [], linewidth=1, color='k', alpha=0.1, label="Eq. 2 ~ {}".format(len(features_list)))
plt.legend(loc='lower right')
plt.xlim(0, 4)
plt.ylim(0, 0.34)
plt.xlabel("$\lambda$")
plt.ylabel("$T_C / \omega_{log}$")
plt.tight_layout()
```
| github_jupyter |
## Saving and loading objects
```
import numpy as np
import json
import sfsimodels as sm
```
## Define a soil
```
# Set the void ratio and specific gravity
sl = sm.Soil()
sl.id = 1 # Must set an id before saving
sl.e_curr = 0.7
assert sl.unit_dry_weight is None
sl.specific_gravity = 2.95
assert np.isclose(sl.unit_dry_weight, 17000, rtol=0.01)
# set modulus parameters
g_mod_set = 40e6
sl.g_mod = g_mod_set
sl.poissons_ratio = 0.4
```
## Save the soil to file then load it
```
# Create an output object
ecp_output = sm.Output()
# Add the soil to the output object
ecp_output.add_to_dict(sl)
# Add further info to the output object
ecp_output.name = "a single soil"
ecp_output.units = "N, kg, m, s"
ecp_output.comments = ""
# Export the output object to a json string, which can be saved to file
p_str = json.dumps(ecp_output.to_dict(), skipkeys=["__repr__"], indent=4)
# load the json string using the sfsimodels.load_json method
objs = sm.loads_json(p_str, verbose=0)
loaded_soil = objs['soils'][1]
assert np.isclose(loaded_soil.g_mod, sl.g_mod)
print(sl.g_mod)
```
## Define a soil profile
```
# Define another soil
sl_2 = sm.Soil()
sl_2.id = 2
sl_2.phi = 33.
sl_2.cohesion = 50000
sl_2.unit_dry_weight = 16000
# Define a soil profile
sp = sm.SoilProfile()
depth_1 = 0.0 # m (set to top of layer from surface)
depth_2 = 4.0 # m
sp.add_layer(depth_1, sl)
sp.add_layer(depth_2, sl_2)
sp.id = 0
sp.height = 12.0 # m (total height of profile)
sp.gwl = 5.0 # m (ground water level from surface)
```
## Save and load a soil profile
```
# re-initiate the output object
ecp_output = sm.Output()
# add the soil profile, it automatically adds the associated soil objects
ecp_output.add_to_dict(sp)
# Add further info to the output object
ecp_output.name = "a soil profile"
ecp_output.units = "N, kg, m, s"
ecp_output.comments = ""
# Export the output object to a json string, which can be saved to file
p_str = json.dumps(ecp_output.to_dict(), skipkeys=["__repr__"], indent=4)
# load the json string using the sfsimodels.load_json method
objs = sm.loads_json(p_str, verbose=0)
loaded_soil_profile = objs['soil_profiles'][0]
assert np.isclose(loaded_soil_profile.height, 12)
assert np.isclose(loaded_soil_profile.layer(1).g_mod, sl.g_mod)
print(loaded_soil_profile.height)
```
## Extend a standard model
This example takes the soil model and adds new parameters and functionality.
### Define the extension
In this example the Soil model is extended, however you can inherit from custom object and overwrite both the 'type' and 'base_type' parameters.
```
class SpecialSoil(sm.Soil):
type = "special_soil" # tag used to save a load
def __init__(self):
super(SpecialSoil, self).__init__() # run the base model initialisation function
self.cotton_content = None
# list the extra save a load parameters that should be saved and loaded
self._extra_class_inputs = ["cotton_content"]
self.inputs = self.inputs + self._extra_class_inputs
def custom_func(self, value): # Add additional functionality
return value + self.cohesion
```
### Save, load and use the extended soil model
```
s_soil = SpecialSoil()
s_soil.id = 1
s_soil.cohesion = 30000.0
print("Assert cotton_content initialises and is set to None: ", s_soil.cotton_content)
s_soil.cotton_content = 34
print("s_soil.cotton_content: ", s_soil.cotton_content)
print("custom_func(4): ", s_soil.custom_func(4))
# create an output object
ecp_output = sm.Output()
ecp_output.add_to_dict(s_soil)
# save to a string, use json.dump to save to file
p_str = json.dumps(ecp_output.to_dict(), skipkeys=["__repr__"])
# load the json string using the sfsimodels.load_json method
# pass a dict of <base_type>-<type>: Object pairs in to load to a custom object
objs = sm.loads_json(p_str, verbose=0, custom={"soil-special_soil": SpecialSoil})
loaded_soil = objs['soils'][1]
assert isinstance(loaded_soil, SpecialSoil)
print("loaded_soil.cotton_content: ", loaded_soil.cotton_content)
print("loaded_soil.custom_func(5): ", s_soil.custom_func(5))
```
### Lazy alternative (just for saving)
If you just want to add some custom attributes to the output.
```
s2 = sm.Soil()
s2.id = 1
s2.special_prop = 3
# custom parameters are not saved by default
ecp_output = sm.Output()
ecp_output.add_to_dict(s2)
p_str = json.dumps(ecp_output.to_dict(), skipkeys=["__repr__"])
objs = sm.loads_json(p_str, verbose=0)
loaded_soil = objs['soils'][1]
assert not hasattr(loaded_soil, "special_prop")
# to add to output without creating a new model
# just add directly to the inputs
s2.inputs += ["special_prop"]
ecp_output = sm.Output()
ecp_output.add_to_dict(s2)
p_str = json.dumps(ecp_output.to_dict(), skipkeys=["__repr__"])
objs = sm.loads_json(p_str, verbose=0)
loaded_soil = objs['soils'][1]
assert hasattr(loaded_soil, "special_prop")
```
| github_jupyter |
# Problem Set 7
```
import matplotlib.colors as mplc
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import pandas as pd
import qeds
```
## Question 1
From [Data Visualization: Rules and Guidelines](../applications/visualization_rules.ipynb)
Create a bar chart of the below data on Canadian GDP growth.
Use a non-red color for the years 2000 to 2008, red for
2009, and the first color again for 2010 to 2018.
```
ca_gdp = pd.Series(
[5.2, 1.8, 3.0, 1.9, 3.1, 3.2, 2.8, 2.2, 1.0, -2.8, 3.2, 3.1, 1.7, 2.5, 2.9, 1.0, 1.4, 3.0],
index=list(range(2000, 2018))
)
fig, ax = plt.subplots()
for side in ["right", "top", "left", "bottom"]:
ax.spines[side].set_visible(False)
```
## Question 2
From [Data Visualization: Rules and Guidelines](../applications/visualization_rules.ipynb)
Draft another way to organize time and education by modifying the code below.
That is, have two subplots (one for each
education level) and four groups of points (one for each year).
Why do you think they chose to organize the information the way they
did rather than this way?
```
# Read in data
df = pd.read_csv("https://datascience.quantecon.org/assets/data/density_wage_data.csv")
df["year"] = df.year.astype(int) # Convert year to int
def single_scatter_plot(df, year, educ, ax, color):
"""
This function creates a single year's and education level's
log density to log wage plot
"""
# Filter data to keep only the data of interest
_df = df.query("(year == @year) & (group == @educ)")
_df.plot(
kind="scatter", x="density_log", y="wages_logs", ax=ax, color=color
)
return ax
# Create initial plot
fig, ax = plt.subplots(1, 4, figsize=(16, 6), sharey=True)
for (i, year) in enumerate(df.year.unique()):
single_scatter_plot(df, year, "college", ax[i], "b")
single_scatter_plot(df, year, "noncollege", ax[i], "r")
ax[i].set_title(str(year))
```
## Questions 3-5
These question uses a dataset from the [Bureau of Transportation
Statistics]([https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236&DB_Short_Name=On-Time](https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236&DB_Short_Name=On-Time))
that describes the cause for all US domestic flight delays
in November 2016. We used the same data in the previous problem set.
```
air_perf = qeds.load("airline_performance_dec16") #[["CRSDepTime", "Carrier", "CarrierDelay", "ArrDelay"]]
air_perf.info()
air_perf.head
```
The following questions are intentionally somewhat open-ended. For
each one, carefully choose the type of visualization you’ll create.
Put some effort into choosing colors, labels, and other
formatting.
### Question 3
Create a visualization of the relationship between airline (carrier)
and delays.
### Question 4
Create a visualization of the relationship between date and delays.
### Question 5
Create a visualization of the relationship between location (origin
and/or destination) and delays.
| github_jupyter |
```
import math
import numpy as np
import matplotlib.pyplot as plt
import skimage as sk
import skimage.transform as sktr
import skimage.io as skio
from skimage import draw
from skimage import transform
import scipy
from tqdm import tqdm
# read & mark corresponding points
img1 = skio.imread('alimg1.jpg')
img1 = sk.img_as_float(img1)
img2 = skio.imread('alimg2.jpg')
img2 = sk.img_as_float(img2)
pts1 = np.load('alimg1_pts.npy',allow_pickle=True)
pd = pts1.item()
p1 = np.array([i for l in pd.values() for i in l])
p1 = np.ndarray.round(p1)
pts2 = np.load('alimg2_pts.npy',allow_pickle=True)
pd = pts2.item()
p2 = np.array([i for l in pd.values() for i in l])
p2 = np.ndarray.round(p2)
fig,ax = plt.subplots(ncols=2,figsize=(14,10))
ax[0].imshow(img1)
ax[0].scatter(p1[:,0],p1[:,1])
ax[1].imshow(img2)
ax[1].scatter(p2[:,0],p2[:,1])
# triangulation with image 1 points
from scipy.spatial import Delaunay
points = (p1+p2)/2
tri = Delaunay(points)
points = (p1 + p2)/2
fig,ax = plt.subplots(ncols=2,figsize=(14,10))
tri = Delaunay(points)
ax[0].imshow(img1)
ax[0].scatter(p1[:,0],p1[:,1])
ax[0].triplot(p1[:,0],p1[:,1],tri.simplices)
ax[0].plot(p1[:,0],p1[:,1],'o')
ax[0].set_title('Tri with avg points')
ax[1].imshow(img2)
ax[1].scatter(p2[:,0],p2[:,1])
ax[1].triplot(p2[:,0], p2[:,1], tri.simplices)
ax[1].plot(p2[:,0], p2[:,1], 'o')
ax[1].set_title('Tri with avg points')
# uses linear algebra to solve the affine transform matrix, note that we uses its inverse
def computeAffine(tri1_pts,tri2_pts):
src,dst = tri1_pts,tri2_pts
x1 = np.pad(src.transpose(1,0),[(0,1),(0,0)],mode='constant',constant_values=1)
x2 = np.pad(dst.transpose(1,0),[(0,1),(0,0)],mode='constant',constant_values=1)
T = x2 @ np.linalg.inv(x1)
return T
def pos_of_interest(tri_target,T):
dst = tri_target
tu1 = draw.polygon(dst[:,0],dst[:,1])
new_src = tuple(np.ndarray.round((np.linalg.inv(T) @ np.pad(np.array(tu1),[(0,1),(0,0)],mode='constant',constant_values=1))[:2]).astype(int))
return tu1[::-1], new_src[::-1]
# use corresponding points to get triangles once and fixed through morphing process
tri = Delaunay((p1+p2)/2)
def morph(im1, im2, im1_pts, im2_pts, tri, warp_frac, dissolve_frac):
img1,img2,p1,p2 = im1,im2,im1_pts,im2_pts
# warped shape according to warp_frac
warped_pts = warp_frac*p1+(1-warp_frac)*p2
# initialize two mid-way images
new_img1 = img1.copy()
new_img2 = img2.copy()
# obtain Mid-way images
for indices in tri.simplices:
# use the corresponding feature triangle to estimate the affine transformation matrix
from_src,to_dst = p2[indices],warped_pts[indices]
T2 = computeAffine(from_src,to_dst)
# new morphing image's dst_position is filled with src_position from the old images (hybrid of src&dst)
to_img_dst, from_img_src = pos_of_interest(to_dst,T2)
# mid-way image part I
new_img2[to_img_dst] = img2[from_img_src]
# from img1 to mid-way
from_src,to_dst = p1[indices],warped_pts[indices]
T1 = computeAffine(from_src,to_dst)
# new morphing image's dst_position is filled with src_position from the old images (hybrid of src&dst)
to_img_dst, from_img_src = pos_of_interest(to_dst,T1)
# mid-way image
new_img1[to_img_dst] = img1[from_img_src]
# cross-dissolve
mid_img = dissolve_frac*new_img1 + (1-dissolve_frac)*new_img2
return mid_img
mids = morph(img1,img2,p1,p2,tri,warp_frac=0.4,dissolve_frac=0.5)
plt.imshow(mids)
# time frame morphing
num_steps = 100
imgs = []
for t in tqdm(np.linspace(0,1,num_steps)):
mid_img = morph(img1,img2,p1,p2,tri,warp_frac=t,dissolve_frac=t)
imgs.append(mid_img)
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.animation as animation
#img = [] # some array of images
frames = [] # for storing the generated images
fig = plt.figure()
for i in range(num_steps):
frames.append([plt.imshow(imgs[i], animated=True)])
ani = animation.ArtistAnimation(fig, frames, interval=50, blit=True,
repeat_delay=1000)
ani.save('movie.mp4')
#plt.show()
```
Population Mean: TBD
| github_jupyter |
#Media Bias on Twitter using Sentiment Analysis [BERT]
The folllowing notebook trains a Sentiment Classifier on the [Tweet Sentiment Extraction](https://www.kaggle.com/c/tweet-sentiment-extraction) dataset available on Kaggle. We'll use the pretrained BERT model for Sentiment analysis from [Hugging face](https://huggingface.co/transformers/model_doc/bert.html) library.
I have scrapped the data from the twitter accounts of four English News Channels of India CNN News18, Republic TV, NDTV, Times Now. We'll predict the sentiment of these tweets and analyse how one channel is biased towards any particular political party or leaders.
##Table of Contents:
>1. [Setup](#setup)
>2. [Data Preparation](#prep)
>3. [Model](#mod)
>4. [Training](#train)
>5. [Evaluation](#eval)
>6. [Sentiment Prediction](#sent)
>7. [Analysis of media-bias](#ana)
#<a id="setup">Setup</a>
```
!pip install transformers
import numpy as np
import pandas as pd
import transformers
from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup
import torch
from torch import nn, optim
from torch.utils.data import Dataset, DataLoader
import seaborn as sns
from matplotlib import pyplot as plt
from pylab import rcParams
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report
from collections import defaultdict
from textwrap import wrap
RANDOM_SEED = 42
torch.manual_seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
if torch.cuda.is_available():
device = torch.device("cuda:0")
print(torch.cuda.get_device_name(0))
else:
device = torch.device("cpu")
print("cpu")
```
#<a id="prep">Data Preparation</a>
```
train = pd.read_csv("train.csv")
train.head()
```
The dataset contains selected_text and sentiment but we will use only sentiment column and text column for training purpose.
```
test = pd.read_csv("test.csv")
test.head()
```
Converting the sentiment values to integers:-
* neutral - 1
* positive - 2
* negative - 0
```
#Removing missing values
train['text'].dropna(axis=0,inplace=True)
train['sentiment'].dropna(axis=0,inplace=True)
#Replacing sentiments with scores
train['sentiment'].replace({'neutral':1,'positive':2,'negative':0},inplace=True)
train.head()
#Removing missing values
test['text'].dropna(axis=0,inplace=True)
test['sentiment'].dropna(axis=0,inplace=True)
#Replacing sentiments with scores
test['sentiment'].replace({'neutral':1,'positive':2,'negative':0},inplace=True)
MAX_LEN=160
classes = ['negative', 'neutral', 'positive']
PRE_TRAINED_MODEL_NAME = 'bert-base-uncased'
tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME)
class TwitterDataset(Dataset):
#Creating a Twitter sentiment dataset
def __init__(self, reviews, targets, tokenizer, max_len):
self.reviews = reviews
self.targets = targets
self.tokenizer = tokenizer
self.max_len = max_len
def __len__(self):
return len(self.reviews)
def __getitem__(self, item):
review = str(self.reviews[item]) #tweet
target = self.targets[item] #sentiment
encoding = self.tokenizer.encode_plus(
review,
add_special_tokens=True, # addding [CLS] and [SEP] tokens
max_length=self.max_len,
return_token_type_ids=False,
truncation=True, #trunction for max length
pad_to_max_length=True,
return_attention_mask=True,
return_tensors='pt', #PyTorch tensors
)
return {
'review_text': review,
'input_ids': encoding['input_ids'].flatten(),
'attention_mask': encoding['attention_mask'].flatten(),
'targets': torch.tensor(target, dtype=torch.long)
}
```
Splitting the training and testing data
```
d_train, d_test = train_test_split(
train,
test_size=0.1,
random_state=RANDOM_SEED
)
d_val, d_test = train_test_split(
test,
test_size=0.5,
random_state=RANDOM_SEED
)
def dataloader(dataframe, tokenizer, max_len, batch_size):
#dataloader for pytorch dataset
dataset = TwitterDataset(
reviews = dataframe.text.to_numpy(), #converting to numpy array
targets = dataframe.sentiment.to_numpy(), #converting to numpy array
max_len=max_len, # setting the maximum length
tokenizer=tokenizer,
)
return DataLoader(
dataset,
num_workers=4,
batch_size=batch_size,
)
BATCH_SIZE = 16
train_dataloader = dataloader(d_train, tokenizer, MAX_LEN, BATCH_SIZE)
val_dataloader = dataloader(d_val, tokenizer, MAX_LEN, BATCH_SIZE)
test_dataloader = dataloader(d_test, tokenizer, MAX_LEN, BATCH_SIZE)
```
#<a id='mod'>Model</a>
```
bert_model = BertModel.from_pretrained('bert-base-uncased')
class Classifier(nn.Module):
def __init__(self, n_classes):
super(Classifier, self).__init__()
self.bert = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME)
self.drop = nn.Dropout(p=0.3)
self.out = nn.Linear(self.bert.config.hidden_size, n_classes)
def forward(self, input_ids, attention_mask):
#using only [CLS] embedding, ignoring sequence output
_, pooled_output = self.bert(
input_ids=input_ids,
attention_mask=attention_mask
)
output = self.drop(pooled_output)
return self.out(output)
data = next(iter(train_dataloader))
data.keys()
model = Classifier(len(classes))
model = model.to(device)
input_ids = data['input_ids'].to(device)
attention_mask = data['attention_mask'].to(device)
```
#<a id="train">Training</a>
```
EPOCHS = 3
optimizer = AdamW(model.parameters(), lr=2e-5, correct_bias=False)
total_steps = len(train_dataloader) * EPOCHS
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=0,
num_training_steps=total_steps
)
loss_fn = nn.CrossEntropyLoss().to(device)
def train_epoch(
model,
data_loader,
loss_fn,
optimizer,
device,
scheduler,
n_examples
):
model = model.train()
losses = []
correct_predictions = 0
for d in data_loader:
input_ids = d["input_ids"].to(device)
attention_mask = d["attention_mask"].to(device)
targets = d["targets"].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask
)
_, preds = torch.max(outputs, dim=1)
loss = loss_fn(outputs, targets)
correct_predictions += torch.sum(preds == targets)
losses.append(loss.item())
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
scheduler.step()
optimizer.zero_grad()
return correct_predictions.double() / n_examples, np.mean(losses)
def eval_model(model, data_loader, loss_fn, device, n_examples):
model = model.eval()
losses = []
correct_predictions = 0
with torch.no_grad():
for d in data_loader:
input_ids = d["input_ids"].to(device)
attention_mask = d["attention_mask"].to(device)
targets = d["targets"].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask
)
_, preds = torch.max(outputs, dim=1)
loss = loss_fn(outputs, targets)
correct_predictions += torch.sum(preds == targets)
losses.append(loss.item())
return correct_predictions.double() / n_examples, np.mean(losses)
%%time
history = defaultdict(list)
best_accuracy = 0
for epoch in range(EPOCHS):
print(f'Epoch {epoch + 1}/{EPOCHS}')
print('-' * 10)
train_acc, train_loss = train_epoch(
model,
train_dataloader,
loss_fn,
optimizer,
device,
scheduler,
len(d_train)
)
print(f'Train loss {train_loss} accuracy {train_acc}')
val_acc, val_loss = eval_model(
model,
val_dataloader,
loss_fn,
device,
len(d_val)
)
print(f'Val loss {val_loss} accuracy {val_acc}')
print()
history['train_acc'].append(train_acc)
history['train_loss'].append(train_loss)
history['val_acc'].append(val_acc)
history['val_loss'].append(val_loss)
if val_acc > best_accuracy:
torch.save(model.state_dict(), 'best_model_state.bin')
best_accuracy = val_acc
def get_predictions(model, data_loader):
model = model.eval()
review_texts = []
predictions = []
prediction_probs = []
real_values = []
with torch.no_grad():
for d in data_loader:
texts = d["review_text"]
input_ids = d["input_ids"].to(device)
attention_mask = d["attention_mask"].to(device)
targets = d["targets"].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask
)
_, preds = torch.max(outputs, dim=1)
review_texts.extend(texts)
predictions.extend(preds)
prediction_probs.extend(outputs)
real_values.extend(targets)
predictions = torch.stack(predictions).cpu()
prediction_probs = torch.stack(prediction_probs).cpu()
real_values = torch.stack(real_values).cpu()
return review_texts, predictions, prediction_probs, real_values
y_review_texts, y_pred, y_pred_probs, y_test = get_predictions(
model,
test_dataloader
)
print(classification_report(y_test, y_pred, target_names=classes))
```
#<a id="sent">Sentiment Prediction<a>
I have used the [Twitter Scrapper](https://dev.to/natterstefan/scrape-tweets-from-twitter-profiles-without-using-twitter-s-api-47n7) for scraping the latest 5000 tweets of every channel.
---
```
df = pd.read_csv("tweets.csv",index_col=[0])
df.head()
```
**Data Description**
>1. channel - Name of the news channel.
>2. tweet - Text of the tweet.
>3.Modi - Tweet contains keyword 'modi' or not
>3.Rahul Gandhi - Tweet contains keyword 'Rahul Gandhi' or not
>3.BJP - Tweet contains keyword 'BJP' or not
>3.Congress - Tweet contains keyword 'Congress' or not
>3.Amit Shah - Tweet contains keyword 'Amit Shah' or not
>3.Arvind Kejriwal - Tweet contains keyword 'Arvind Kejriwal' or not
```
pred = []
for tweet in df['tweet']:
encoded_review = tokenizer.encode_plus(
tweet,
max_length=MAX_LEN,
add_special_tokens=True,
return_token_type_ids=False,
truncation=True,
pad_to_max_length=True,
return_attention_mask=True,
return_tensors='pt',
)
input_ids = encoded_review['input_ids'].to(device)
attention_mask = encoded_review['attention_mask'].to(device)
output = model(input_ids, attention_mask)
_, prediction = torch.max(output, dim=1)
pred.append(classes[prediction])
df['sentiment'] = pred
```
Creating a new column 'relevant', it will be 1 or 0 depending upon whether it contains any keywords or not
```
df['relevant']=df.sum(axis=1)
binary=[]
for t in df['relevant']:
if t>0:
binary.append(1)
else:
binary.append(0)
df['relevant'] =binary
df.head()
```
#<a id="ana">Analysis of Media-Bias<a>
```
num_relevant = df.relevant.sum()
num_total = df.shape[0]
print('Number of relevant tweets: %s' % num_relevant)
print('Total number of tweets: %s' % num_total)
print('Percentage of relevant tweets: %0.2f%%' % (100*num_relevant/num_total))
```
The chosen topics are covered in of the total 20,000 tweets. Let's see to what extent those topics are covered overall by each channel
```
channel_stats = pd.DataFrame({
'relevant': df.groupby('channel').relevant.sum().astype(int),
'total': df.groupby('channel').size()
})
channel_stats['percentage_relevant'] = (100*channel_stats.relevant/channel_stats.total).round(2)
channel_stats.sort_values('percentage_relevant', ascending=False)
```
##Relative topic Coverage
> It shows that how important each topic is to each channel, We will plot the count of tweets about every topic for each channel.
```
modi=df.loc[df['Modi'] == 1]
rahul_gandhi=df.loc[df['Rahul Gandhi'] == 1]
fig, axes = plt.subplots(1, 2,figsize=(15,5))
plt.ylim(0, 400)
sns.countplot(x="channel", data=modi, ax=axes[0]).set_title("Modi")
sns.countplot(x='channel',data=rahul_gandhi, ax=axes[1]).set_title("Rahul Gandhi")
```
It shows that except the Times now news Channel the other three talks more about Narendra Modi than Rahul Gandhi.
```
bjp=df.loc[df['BJP'] == 1]
congress=df.loc[df['Congress'] == 1]
fig, axes = plt.subplots(1, 2,figsize=(15,5))
plt.ylim(0, 400)
sns.countplot(x="channel", data=bjp, ax=axes[0]).set_title("BJP")
sns.countplot(x='channel',data=congress, ax=axes[1]).set_title("Congress")
```
* It can be seen from the above graph that Times Now is having the most tweets about BJP(and Modi) than any other channel and
*For Congress Party the distribution is nearly equal among all channels with CNN having the maximum tweets about Congress Party.
```
amit=df.loc[df['Amit Shah'] == 1]
arvind=df.loc[df['Arvind Kejriwal'] == 1]
fig, axes = plt.subplots(1, 2,figsize=(15,5))
plt.ylim(0, 400)
sns.countplot(x="channel", data=amit, ax=axes[0]).set_title("Amit Shah")
sns.countplot(x='channel',data=arvind, ax=axes[1]).set_title("Arvind Kejriwal")
```
It shows that NDTV talks about BJP's Political Leaders quite often and Arwind Kejriwal is having very few tweets on all the four channels.
##Sentiment towards Topics
We will show the sentiments of News Channels towards our Topics by ploting percentage of their positive tweets and negative tweets out of their total tweets about a topic.
### Percentage Positive Tweets
```
modi.groupby(['channel','sentiment']).sum()
channels=['cnn','ndtv','republic','times']
```
**Modi vs Rahul Gandhi**
```
groups = modi.groupby(['channel','sentiment'])
group = modi.groupby('channel')
a=[]
a.append(100*len(groups.get_group(('cnn','positive')))/len(group.get_group('cnn')))
a.append(100*len(groups.get_group(('ndtv','positive')))/len(group.get_group('ndtv')))
a.append(100*len(groups.get_group(('republic','positive')))/len(group.get_group('republic')))
a.append(100*len(groups.get_group(('times','positive')))/len(group.get_group('times')))
groups = rahul_gandhi.groupby(['channel','sentiment'])
group = rahul_gandhi.groupby('channel')
b=[]
b.append(100*len(groups.get_group(('cnn','positive')))/len(group.get_group('cnn')))
b.append(100*len(groups.get_group(('ndtv','positive')))/len(group.get_group('ndtv')))
b.append(100*len(groups.get_group(('republic','positive')))/len(group.get_group('republic')))
b.append(100*len(groups.get_group(('times','positive')))/len(group.get_group('times')))
fig, axes = plt.subplots(1, 2,figsize=(15,5))
axes[0].set_ylim(0,30)
axes[1].set_ylim(0,30)
d=pd.DataFrame({'channel':channels,'pos_per':a})
e=pd.DataFrame({'channel':channels,'pos_per':b})
sns.barplot(x='channel',y='pos_per',data=d,ax=axes[0], palette=("Greens")).set_title("Modi")
sns.barplot(x='channel',y='pos_per',data=e,ax=axes[1], palette=("Greens")).set_title("Rahul Gandhi")
```
* It shows that all the four News Channel talks more positive about Narendra Modi than Rahul Gandhi
* NDTV is having the maximum positive tweets percent of 28.38%.
* Rahul Gandhi is having very few positive tweets from all the four channels.
* Combined positive percentage of Rahul Gandhi ( 5.43 + 8.8 + 6.25 + 6.66 ) is less than NDTV's ( 28.38 %) for Narendra Modi.
**BJP vs Congress**
```
groups = bjp.groupby(['channel','sentiment'])
group = bjp.groupby('channel')
a=[]
a.append(100*len(groups.get_group(('cnn','positive')))/len(group.get_group('cnn')))
a.append(100*len(groups.get_group(('ndtv','positive')))/len(group.get_group('ndtv')))
a.append(100*len(groups.get_group(('republic','positive')))/len(group.get_group('republic')))
a.append(100*len(groups.get_group(('times','positive')))/len(group.get_group('times')))
groups = congress.groupby(['channel','sentiment'])
group = congress.groupby('channel')
b=[]
b.append(100*len(groups.get_group(('cnn','positive')))/len(group.get_group('cnn')))
b.append(100*len(groups.get_group(('ndtv','positive')))/len(group.get_group('ndtv')))
b.append(100*len(groups.get_group(('republic','positive')))/len(group.get_group('republic')))
b.append(100*len(groups.get_group(('times','positive')))/len(group.get_group('times')))
fig, axes = plt.subplots(1, 2,figsize=(15,5))
axes[0].set_ylim(0,30)
axes[1].set_ylim(0,30)
d=pd.DataFrame({'channel':channels,'pos_per':a})
e=pd.DataFrame({'channel':channels,'pos_per':b})
sns.barplot(x='channel',y='pos_per',data=d,ax=axes[0], palette=("Greens")).set_title("BJP")
sns.barplot(x='channel',y='pos_per',data=e,ax=axes[1], palette=("Greens")).set_title("Congress")
```
* It can be seen that the News Channels are more interested in any particular leader than a party, because for both BJP and Congress the percent of positive tweets is less.
* Republic TV having more positive tweets about BJP party.
###Percentage Negative Tweets
**Modi vs Rahul Gandhi**
```
groups = modi.groupby(['channel','sentiment'])
group = modi.groupby('channel')
a=[]
a.append(100*len(groups.get_group(('cnn','negative')))/len(group.get_group('cnn')))
a.append(100*len(groups.get_group(('ndtv','negative')))/len(group.get_group('ndtv')))
a.append(100*len(groups.get_group(('republic','negative')))/len(group.get_group('republic')))
a.append(100*len(groups.get_group(('times','negative')))/len(group.get_group('times')))
groups = rahul_gandhi.groupby(['channel','sentiment'])
group = rahul_gandhi.groupby('channel')
b=[]
b.append(100*len(groups.get_group(('cnn','negative')))/len(group.get_group('cnn')))
b.append(100*len(groups.get_group(('ndtv','negative')))/len(group.get_group('ndtv')))
b.append(100*len(groups.get_group(('republic','negative')))/len(group.get_group('republic')))
b.append(100*len(groups.get_group(('times','negative')))/len(group.get_group('times')))
fig, axes = plt.subplots(1, 2,figsize=(15,5))
axes[0].set_ylim(0,50)
axes[1].set_ylim(0,50)
d=pd.DataFrame({'channel':channels,'neg_per':a})
e=pd.DataFrame({'channel':channels,'neg_per':b})
sns.barplot(x='channel',y='neg_per',data=d,ax=axes[0], palette=("Reds")).set_title("Modi")
sns.barplot(x='channel',y='neg_per',data=e,ax=axes[1], palette=("Reds")).set_title("Rahul Gandhi")
```
* We can see clearly in the above figure that the all the News channels talks so much negative about Rahul Gandhi.
* But for Narendra Modi that is not the case, only Republic TV is having a significant negative percent and rest all are below 20%.
**BJP vs Congress**
```
groups = bjp.groupby(['channel','sentiment'])
group = bjp.groupby('channel')
a=[]
a.append(100*len(groups.get_group(('cnn','positive')))/len(group.get_group('cnn')))
a.append(100*len(groups.get_group(('ndtv','positive')))/len(group.get_group('ndtv')))
a.append(100*len(groups.get_group(('republic','positive')))/len(group.get_group('republic')))
a.append(100*len(groups.get_group(('times','positive')))/len(group.get_group('times')))
groups = congress.groupby(['channel','sentiment'])
group = congress.groupby('channel')
b=[]
b.append(100*len(groups.get_group(('cnn','negative')))/len(group.get_group('cnn')))
b.append(100*len(groups.get_group(('ndtv','negative')))/len(group.get_group('ndtv')))
b.append(100*len(groups.get_group(('republic','negative')))/len(group.get_group('republic')))
b.append(100*len(groups.get_group(('times','negative')))/len(group.get_group('times')))
fig, axes = plt.subplots(1, 2,figsize=(15,5))
axes[0].set_ylim(0,40)
axes[1].set_ylim(0,40)
d=pd.DataFrame({'channel':channels,'neg_per':a})
e=pd.DataFrame({'channel':channels,'neg_per':b})
sns.barplot(x='channel',y='neg_per',data=d,ax=axes[0], palette=("Reds")).set_title("BJP")
sns.barplot(x='channel',y='neg_per',data=e,ax=axes[1], palette=("Reds")).set_title("Congress")
```
* Here also BJP is having very low percent of negative tweets from all the channels.
* Congress is not so popular among these channels becuse ever channel is having about 25% negative tweets which is very low than that of BJP.
* We can also see that for BJP most of the tweets are neutral (because both the positive and negative count is low).
#<a id="ref"> References</a>
* [BERT Fine-Tuning Tutorial with PyTorch](https://mccormickml.com/2019/07/22/BERT-fine-tuning/)
* [Hugging Face Transformers](https://huggingface.co/transformers/)
* [Text Classification | Sentiment Analysis with BERT using huggingface](https://www.youtube.com/watch?time_continue=2055&v=8N-nM3QW7O0&feature=emb_title)
* [How to Fine-Tune BERT for Text Classification?](https://arxiv.org/pdf/1905.05583.pdf)
| github_jupyter |
# Implementation of Simple ML Model
### Author: Tejaswini Patil
### Reg No: 20MAI0044
```
# Importing necessary libraries
import sklearn.datasets
import numpy as np
import pandas as pd
# Load cancer data set from scikit
cancer_ds = sklearn.datasets.load_breast_cancer()
# Lets organise as X and Y
X = cancer_ds.data
Y = cancer_ds.target
# Lets look at the values of X and Y
print(X)
print(Y)
# Peek inside the actual shape of X and Y
print(X.shape, Y.shape)
# Lets get the dataset inside a dataframe and label columns
data = pd.DataFrame(cancer_ds.data,columns = cancer_ds.feature_names)
data.head()
# rename the Y variable as Target
data['class'] = cancer_ds.target
# Finally lets take a look at the data frame
data.head(10)
# Lets understand our data a little bit better
data.describe()
# How many malignant and benign?
print(data['class'].value_counts())
# Know the target names
print(cancer_ds.target_names)
# Understanding role of groupby and insights it can provide
data.groupby('class').mean()
# Lets get our hands dirty.. by wierd experimenting
data.groupby('mean radius').mean()
```
### Train Test Split
```
from sklearn.model_selection import train_test_split
X = data.drop('class',axis=1)
Y = data['class']
# Code for split up
# Stratify will see to it that the balanced data goes into the train
# and test variables
X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.1,
stratify=Y)
print(Y.shape,Y_train.shape,Y_test.shape)
print(X.shape,X_train.shape,X_test.shape)
#Code for split up
X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.1)
print(Y.shape,Y_train.shape,Y_test.shape)
print(X,X_train,X_test)
#random state freezes the push of test and train data to same samples
X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.1,
stratify=Y, random_state=1)
print(X,X_train,X_test)
# Printing the mean values
print(Y.mean(),Y_train.mean(),Y_test.mean())
print(X.mean(),X_train.mean(),X_test.mean())
# We'll try to change the random state a bit and see if it affects
# the data distribution
X_train, X_test, Y_train, Y_test = train_test_split(X,Y,
test_size=0.1,stratify=Y,
random_state=10)
print(X_train.mean())
```
#### We can observe that no significant effect is observed by changing the random state from 1 to 10 in this case
We will see if making random state to be 100 makes any difference
```
X_train, X_test, Y_train, Y_test = train_test_split(X,Y,
test_size=0.1, stratify=Y,
random_state=50)
print(X_train.mean())
```
#### And no difference again!
But.... Random state is important for the model when going into production environments where we will be testing it with tuning our model and we would like to compare the performance of the model.
If the model is taking different data for training and testing every time then there is no way of knowing how the model is performing.
### Let's now write the split up without stratify argument
```
X_train, X_test, Y_train, Y_test = train_test_split(X,Y,
test_size=0.1,
random_state=1)
print(X_train.mean())
```
#### And again the same story repeats.
Seems our data set is perfect. But as a good ML practitioner we cannot always rely on the dataset and we must take care of our model and it means we must look carefully what data we are feeding to our model.
#### Thus it is good idea to keep the stratify back into the place
```
X_train, X_test, Y_train, Y_test = train_test_split(X,Y,
test_size=0.1, stratify=Y,
random_state=1)
# Binarization of Input
X_binarised_train = X_train.apply(pd.cut,bins=2,labels=[1,0])
X_binarised_test = X_test.apply(pd.cut,bins=2,labels=[1,0])
X_binarised_train.shape
X_binarised_test.shape
type(X_binarised_test) #to know the format
# Convert the data frame into numpy for further training and
# testing of simple ML model
X_binarised_train = X_binarised_train.values
X_binarised_test = X_binarised_test.values
type(X_binarised_train)
b = 10 # What are the possible values b can take
from random import randint
#Different values of b- to be tested stored in i
i = randint(0,X_binarised_train.shape[1])
accurate_rows = 0
if(np.sum(X_binarised_train[i:])>=b):
print('Model prediction is Malignant')
else:
print('Model prediction is Benign')
print(i)
if(Y_train[i]==1):
print('Actual Outcome is Malignant')
else:
print('Actual Outcome is Benign')
for b in range (X_binarised_train.shape[1]+1):
accurate_rows = 0
for x,y in zip(X_binarised_train,Y_train):
y_pred = (np.sum(x)>=b)
accurate_rows += (y==y_pred)
print("For b = ", b, accurate_rows,
accurate_rows/X_binarised_train[0])
## Encountered a silly error here where I put
# X_binarised_train[0] instead of X_binarised_train.shape[0]
print(" b Accurate rows Accuracy")
for b in range (X_binarised_train.shape[1]+1):
accurate_rows = 0
for x,y in zip(X_binarised_train,Y_train):
y_pred = (np.sum(x)>=b)
accurate_rows += (y==y_pred)
print(" ", b," ", accurate_rows," ",
accurate_rows/X_binarised_train.shape[0])
print("Testing:")
b = 28
accurate_rows = 0
for x,y in zip(X_binarised_test,Y_test):
y_pred = (np.sum(x)>=b)
accurate_rows += (y==y_pred)
print("For b = ", b, " No. of accurate rows: ", accurate_rows,
" Accuracy: ", accurate_rows/X_binarised_train.shape[0])
b = 27
accurate_rows = 0
for x,y in zip(X_binarised_test,Y_test):
y_pred = (np.sum(x)>=b)
accurate_rows += (y==y_pred)
print("For b = ", b, " No. of accurate rows: ", accurate_rows,
" Accuracy: ", accurate_rows/X_binarised_test.shape[0])
```
#### We could easily see that b=28 was performing better in training but same is not the case in testing here;
that b value has disappointed us and makes me think
if any other b value which performed comparatively lower
on the accuracy part on training might perform better during testing.
But then again I guess it is due to data dependency of the model..
i.e. values which are favorable for b=28 are more in training than in testing
```
print(" b Accurate rows Accuracy")
for b in range (X_binarised_train.shape[1]+1):
accurate_rows = 0
for x,y in zip(X_binarised_train,Y_train):
y_pred = (np.sum(x)>=b)
accurate_rows += (y==y_pred)
print(" ", b," ", accurate_rows," ",
accurate_rows/X_binarised_train.shape[0])
```
### Let's try to see what are the top b values for accuracy
```
dict_train = {}
for b in range (X_binarised_train.shape[1]+1):
accurate_rows = 0
for x,y in zip(X_binarised_train,Y_train):
y_pred = (np.sum(x)>=b)
accurate_rows += (y==y_pred)
dict_train[b] = accurate_rows
print("Dictionary consisting of b and its accurate values for training")
print(dict_train)
import operator
sorted_x_train = dict( sorted(dict_train.items(),
key=operator.itemgetter(1),reverse=True))
print("Sorted Dictionary consisting of b and its accurate values for training")
print(sorted_x_train)
```
#### We can figure out that for training are b=28,27,26,29,25
#### And.. Now lets see what is the accuracy for the testing for these top training values of b
```
print("b #Acc_train_rows #Acc_train #Acc_test_rows #Acc_test")
for key in sorted_x_train:
b = key
accurate_rows = 0
for x,y in zip(X_binarised_test,Y_test):
y_pred = (np.sum(x)>=b)
accurate_rows += (y==y_pred)
print(b," ",dict_train[key]," ",
round(dict_train[key]/X_binarised_train.shape[0],4),
" ",accurate_rows," ",
round(accurate_rows/X_binarised_test.shape[0],4))
```
#### It can be easily inferred that for b=22 training accuracy
#### is less but on the other hand testing accuracy is more.
#### For b=27 accuracy remains same which is acceptable
| github_jupyter |
# Summary
MESH is a POC (Proof of Concept) of high accurate Iris Recognition algorithm. Tested on CASIA_V1 dataset with manual labeled pupil circular, the 1-on-1 cross matching accuracy is 100%. After rejecting several low quality images, the theoritical ERR (Equal Error Rate) can be as low as 1/1billion.
MESH_Open is part of MESH which was open sourced in this repository. MESH_Open has a cross matching accuracy of 99.9965%, or 10 errors in a total of 285,390 1-on-1 cross matchings.
A main advantage of MESH is that the Same Iris Histogram and the Not Same Iris Histogram are far apart, well separated. Which indicates that Iris Recognition has the potential to achieve very high cross matching accuracy, e.g. 1/1billion.
# WorkFlow
## Iris Location
Manual labeled pupil circular data were used, because MESH focuses on feature matching, and I do not have a good Iris Location/Segmentation algorithm. Notes that the manual labeled pupil circulars are not accurate at all. I labelled it myself, sometimes there are 10 pixels offset from ground truth. With a good Iris Location algorithm MESH can do even better.
The Iris circular is setup as same center of Pupil, radius 100 pixels.
## Normalization
Simply stretch the Iris circular disk to a rectangle.
## Encoding
Gabor Filter was used for Iris Encoding. Source code was borrowed from mvjq's repository
https://github.com/mvjq/IrisRecognition.
## Template Matching
MESH focuses on Iris Template Matching. The main idea is to divides the normalized Iris Rectangles into small blocks, then calculates HD (Hamming Distance) between the small blocks. It is a flexible HD calculating algorithm, which can handle the distortion in Iris streching. As a result, MESH_Open achieves cross matching accuracy 99.9965%. MESH uses advanced algorithm and achieves accuracy 100%.
## 1-On-1 Cross Matching
Each Iris was matched with all other Irises. Histogram of Same Iris and Not Same Iris were plotted together and compared.
Each Iris Matching takes about 0.12 seconds on Intel(R) Core(TM) i7-8565U CPU (single thread). It takes about 10 hours to run a full cross matching. One of the disadvantage of MESH Feature Matching is its speed.
```
import warnings
warnings.filterwarnings("ignore")
%config Completer.use_jedi = False
import cv2
import numpy as np
import glob
import math
import scipy
from time import time
from scipy.spatial import distance
from scipy import signal
from scipy.stats import binom, norm
import matplotlib.pyplot as plt
import pandas as pd
import plotly.express as px
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly import tools
import plotly.graph_objs as go
import plotly.io as pio
init_notebook_mode(connected=True)
```
# Functions and Constants
```
def draw_circle(img, c):
return cv2.circle(cv2.cvtColor(img.copy(), cv2.COLOR_GRAY2RGB), (c[1], c[0]), round(c[2]), (255,255,255), 1)
# iris circular to rect
def norm_iris(img, c, r_iris):
[cy, cx, r_pupil, _] = c
# fix r_iris 100
r_iris = 100
_padding = 0
img_rect = cv2.linearPolar(img, (cx, cy), r_iris + _padding, cv2.WARP_FILL_OUTLIERS)
img_rect = cv2.rotate(img_rect, cv2.ROTATE_90_COUNTERCLOCKWISE)
img_rect = cv2.resize(img_rect, (600, r_iris + _padding), interpolation=cv2.INTER_AREA)
img_rect = img_rect[:(r_iris - r_pupil + _padding * 2), :]
img_rect = cv2.resize(img_rect, (600, 60), interpolation=cv2.INTER_AREA)
img_rect = cv2.equalizeHist(img_rect)
return img_rect
# Gabor encoding, From: https://github.com/mvjq/IrisRecognition
def encode_iris(arr_polar, arr_noise, minw_length, mult, sigma_f):
"""
Generate iris template and noise mask from the normalised iris region.
"""
# convolve with gabor filters
filterb = gaborconvolve_f(arr_polar, minw_length, mult, sigma_f)
l = arr_polar.shape[1]
template = np.zeros([arr_polar.shape[0], 2 * l])
h = np.arange(arr_polar.shape[0])
# making the iris template
mask_noise = np.zeros(template.shape)
filt = filterb[:, :]
# quantization and check to see if the phase data is useful
H1 = np.real(filt) > 0
H2 = np.imag(filt) > 0
H3 = np.abs(filt) < 0.0001
for i in range(l):
ja = 2 * i
# biometric template
template[:, ja] = H1[:, i]
template[:, ja + 1] = H2[:, i]
return template, mask_noise
def gaborconvolve_f(img, minw_length, mult, sigma_f):
"""
Convolve each row of an imgage with 1D log-Gabor filters.
"""
rows, ndata = img.shape
logGabor_f = np.zeros(ndata)
filterb = np.zeros([rows, ndata], dtype=complex)
radius = np.arange(ndata/2 + 1) / (ndata/2) / 2
radius[0] = 1
# filter wavelength
wavelength = minw_length
# radial filter component
fo = 1 / wavelength
logGabor_f[0: int(ndata/2) + 1] = np.exp((-(np.log(radius/fo))**2) /
(2 * np.log(sigma_f)**2))
logGabor_f[0] = 0
# convolution for each row
for r in range(rows):
signal = img[r, 0:ndata]
imagefft = np.fft.fft(signal)
filterb[r, :] = np.fft.ifft(imagefft * logGabor_f)
return filterb
def get_gabor_encoded_img(img, c):
minw_length = 18
mult = 1
sigma_f = 0.5
img_rect = norm_iris(img, c, c[2] + iris_depth)
img_gabor_rect, mask_noise = encode_iris(img_rect, np.zeros(img_rect.shape), minw_length, mult, sigma_f)
img_gabor_rect = (img_gabor_rect * 255).astype(np.uint8)
return img_gabor_rect[:, ::2], img_gabor_rect[:, 1::2]
# get hamming distance of 2 iris rects
def get_hd_of_img_i_j(img0, img1):
key_points_0 = key_points.copy()
key_points_1 = []
hd_map = []
for kp in key_points_0:
feature_0 = img0[kp[0]-hsp:kp[0]+hsp, kp[1]-hsp:kp[1]+hsp]
feature_1 = img1[kp[0]-sp:kp[0]+sp, kp[1]-sp:kp[1]+sp]
# quality check
# feature_0_mean, feature_1_mean = feature_0.mean(), feature_1.mean()
# if((feature_0_mean > 255*0.4 and feature_0_mean < 255*0.6) and (feature_1_mean > 255*0.41 and feature_1_mean < 255*0.59)):
feature_match_map = cv2.filter2D(feature_1, -1, feature_0/feature_0.sum())
feature_match_map_0 = cv2.filter2D((255 - feature_1), -1, (255 - feature_0)/(255 - feature_0).sum())
feature_match_map = (feature_match_map.astype(np.int) + feature_match_map_0.astype(np.int)) / 2
salt = np.random.rand(feature_match_map.shape[0], feature_match_map.shape[1])
feature_match_map = feature_match_map.astype(np.float32) + salt
kp_match_ind = np.unravel_index(feature_match_map.argmax(), feature_match_map.shape)
kp_match_offset = kp_match_ind - np.array([sp, sp])
kp_match = np.array(kp) + kp_match_offset
key_points_1.append(kp_match)
hd_map.append(feature_match_map[kp_match_ind[0]][kp_match_ind[1]])
select_hd = pd.DataFrame(hd_map)[0] > thresh_hd
return key_points_1, np.sum(select_hd), hd_map
N_tested = 756 # number of tested images
iris_depth = 60 # height of normed iris rect
thresh_hd = int(0.7 * 255)
percentile_hd = .75
```
# Load CASIA V1 images and pupil centers
```
files = []
for i in range(1, 109):
files.extend(sorted(glob.glob('CASIA1/' + str(i) + '/*.jpg')))
print("N# of files which we are extracting features", len(files))
# for f in files:
# print(f)
cirpupils = pd.read_csv('casia_v1_circle_pupil.csv')
cirpupils
img_oris = [cv2.imread(_, 0) for _ in files[:N_tested]]
```
# Observe Pupil Circle
```
ti = 333
fig, ax = plt.subplots(figsize=(12, 12))
ax.imshow(draw_circle(img_oris[ti], list(cirpupils.iloc[ti])), interpolation='nearest')
list(cirpupils.iloc[ti])
```
# Observe sample images, rects, templates
```
t0, t1 = 2, 4 # index of sample images
print(files[t0])
print(files[t1])
fig, ax = plt.subplots(figsize=(16, 8))
ax.imshow(np.hstack((img_oris[t0], img_oris[t1])), interpolation='nearest')
fig, ax = plt.subplots(figsize=(20, 16))
ax.imshow(np.vstack((norm_iris(img_oris[t0], cirpupils.iloc[t0], cirpupils.iloc[t0][2] + iris_depth),
norm_iris(img_oris[t1], cirpupils.iloc[t1], cirpupils.iloc[t1][2] + iris_depth))), interpolation='nearest')
img_gabor_rects = []
for i in range(len(img_oris)):
template_ori = get_gabor_encoded_img(img_oris[i], cirpupils.iloc[i])
template_pat = []
template_pat.append(np.hstack((template_ori[0], template_ori[0][:, :30])))
template_pat.append(np.hstack((template_ori[1], template_ori[1][:, :30])))
img_gabor_rects.append(template_pat)
fig, ax = plt.subplots(figsize=(20, 16))
ax.imshow(np.vstack((img_gabor_rects[t0][0], img_gabor_rects[t1][0])), interpolation='nearest')
```
# Define mesh points
```
h_rect, w_rect = img_gabor_rects[0][0].shape
n_h, n_w = 5, 60 # N feature points on H, W
sp = 30 # size of HD area
hsp = int(sp*0.5) # half of sp
step_h = (h_rect - sp) / (n_h - 1)
step_w = (w_rect - sp) / (n_w - 1)
key_points = []
for i in range(n_h):
_k_h = i * step_h + sp
for j in range(n_w):
_k_w = j * step_w + sp
key_points.append([int(_k_h), int(_k_w)])
print(h_rect, w_rect, step_h, step_w)
```
# Sample of mesh Hamming Distance map
```
kp = key_points[20]
feature_0 = img_gabor_rects[t0][0][kp[0]-hsp:kp[0]+hsp, kp[1]-hsp:kp[1]+hsp]
feature_1 = img_gabor_rects[t1][0][kp[0]-sp:kp[0]+sp, kp[1]-sp:kp[1]+sp]
feature_match_map = cv2.filter2D(feature_1, -1, feature_0/feature_0.sum())
kp_match_ind = np.unravel_index(feature_match_map.argmax(), feature_match_map.shape)
kp_match_offset = kp_match_ind - np.array([hsp, hsp])
kp_match = np.array(kp) + kp_match_offset
print(kp_match, feature_match_map[kp_match_ind[0]][kp_match_ind[1]], feature_0.mean(), feature_1.mean())
fig, ax = plt.subplots(figsize=(6, 6))
ax.imshow(feature_0, interpolation='nearest')
fig, ax = plt.subplots(figsize=(6, 6))
ax.imshow(np.hstack((feature_1, feature_match_map)), interpolation='nearest')
key_points_1, n_selected, hd_map = get_hd_of_img_i_j(img_gabor_rects[t0][0], img_gabor_rects[t1][0])
print(n_selected, np.percentile(hd_map, percentile_hd))
```
# Cross Matching
## It takes about 10h to run a full cross matching.
```
np.random.seed(42)
start_time = time()
recs = []
for i in range(N_tested-1):
if(i % 10 == 0):
print(i)
for j in range(i+1, min(N_tested, N_tested)):
if(i != j):
_, n_selected1, hd_map = get_hd_of_img_i_j(img_gabor_rects[i][0], img_gabor_rects[j][0])
_, n_selected2, hd_map_2 = get_hd_of_img_i_j(img_gabor_rects[j][0], img_gabor_rects[i][0])
recs.append([i, j, n_selected, n_selected2, np.percentile(hd_map, percentile_hd), np.percentile(hd_map_2, percentile_hd)])
print('time cost: %d' % int(time() - start_time))
df_hd = pd.DataFrame(data=recs, columns=['i', 'j', 'n_selected1', 'n_selected2', 'hd1', 'hd2'])
df_hd['hd'] = (df_hd['hd1'] + df_hd['hd2']) / 2
df_hd['fi'] = df_hd['i'].apply(lambda x: files[x].split('\\')[1][:3])
df_hd['fj'] = df_hd['j'].apply(lambda x: files[x].split('\\')[1][:3])
df_hd['fi_'] = df_hd['i'].apply(lambda x: files[x].split('\\')[1][:7])
df_hd['fj_'] = df_hd['j'].apply(lambda x: files[x].split('\\')[1][:7])
df_hd['same'] = df_hd['fi'] == df_hd['fj']
```
# Histogram of Hamming Distance, FRR/FAR. ERR: 0.0035%
## Load pre run HD data.
```
df_hd = pd.read_csv('casia_v1_hd.csv', index_col=None)
df_hd.sort_values(by='hd', inplace=True, ascending=True)
df_hd[df_hd['same']].head(10)
df_hd.sort_values(by='hd', inplace=True, ascending=False)
df_hd[~df_hd['same']].head(10)
# hd
N_bins = 200
counts_same, bins_same = np.histogram(df_hd[df_hd['same']]['hd'].values / 255, bins=[_ / N_bins for _ in range(0, N_bins)])
counts_not_same, bins_not_same = np.histogram(df_hd[df_hd['same'] == False]['hd'].values / 255, bins=[_ / N_bins for _ in range(0, N_bins)])
fig = go.Figure(data=[
go.Bar(x=bins_same, y=counts_same, name='same'),
go.Bar(x=bins_not_same, y=counts_not_same * counts_same.sum() / counts_not_same.sum(), name='not same'),
])
fig.show()
fars, frrs, fars_fit = [], [], []
err = 0
for i in range(len(bins_same)):
frrs.append(counts_same[:i].sum() / counts_same.sum())
fars.append(counts_not_same[i:].sum() / counts_not_same.sum())
fig = go.Figure(data=[
go.Scatter(x=bins_not_same, y=frrs, name='frr'),
go.Scatter(x=bins_same, y=fars, name='far'),
])
fig.show()
# for matplotlib
_ = plt.hist([
np.repeat(df_hd[df_hd['same']]['hd'].values, counts_not_same.sum() / counts_same.sum()) / 255,
df_hd[df_hd['same'] == False]['hd'].values / 255],
[_ / N_bins for _ in range(0, N_bins)],
label=['Same', 'Not Same'])
fig = plt.gcf()
fig.set_size_inches(18, 6)
plt.scatter(x=bins_not_same, y=frrs, label='frr')
plt.scatter(x=bins_same, y=fars, label='far')
fig = plt.gcf()
fig.set_size_inches(18, 6)
```
| github_jupyter |
<h1 align="center"> Registration Initialization: We Have to Start Somewhere</h1>
Initialization is a critical aspect of most registration algorithms, given that most algorithms are formulated as an iterative optimization problem.
In many cases we perform initialization in an automatic manner by making assumptions with regard to the contents of the image and the imaging protocol. For instance, if we expect that images were acquired with the patient in a known orientation we can align the geometric centers of the two volumes or the center of mass of the image contents if the anatomy is not centered in the image (this is what we previously did in [this example](60_Registration_Introduction.ipynb)).
When the orientation is not known, or is known but incorrect, this approach will not yield a reasonable initial estimate for the registration.
When working with clinical images, the DICOM tags define the orientation and position of the anatomy in the volume. The tags of interest are:
<ul>
<li> (0020|0032) Image Position (Patient) : coordinates of the the first transmitted voxel. </li>
<li>(0020|0037) Image Orientation (Patient): directions of first row and column in 3D space. </li>
<li>(0018|5100) Patient Position: Patient placement on the table
<ul>
<li> Head First Prone (HFP)</li>
<li> Head First Supine (HFS)</li>
<li> Head First Decubitus Right (HFDR)</li>
<li> Head First Decubitus Left (HFDL)</li>
<li> Feet First Prone (FFP)</li>
<li> Feet First Supine (FFS)</li>
<li> Feet First Decubitus Right (FFDR)</li>
<li> Feet First Decubitus Left (FFDL)</li>
</ul>
</li>
</ul>
The patient position is manually entered by the CT/MR operator and thus can be erroneous (HFP instead of FFP will result in a $180^o$ orientation error).
A heuristic, yet effective, solution is to use a sampling strategy of the parameter space. Note that this strategy is primarily useful in low dimensional parameter spaces (rigid or possibly affine transformations).
In this notebook we illustrate how to sample the parameter space in a fixed pattern. We then initialize the registration with the parameters that correspond to the best similarity metric value obtained by our sampling.
```
import SimpleITK as sitk
# If the environment variable SIMPLE_ITK_MEMORY_CONSTRAINED_ENVIRONMENT is set, this will override the ReadImage
# function so that it also resamples the image to a smaller size (testing environment is memory constrained).
%run setup_for_testing
import os
import numpy as np
from ipywidgets import interact, fixed
%run update_path_to_download_script
from downloaddata import fetch_data as fdata
import registration_callbacks as rc
import registration_utilities as ru
# Always write output to a separate directory, we don't want to pollute the source directory.
OUTPUT_DIR = 'Output'
%matplotlib inline
# This is the registration configuration which we use in all cases. The only parameter that we vary
# is the initial_transform.
def multires_registration(fixed_image, moving_image, initial_transform):
registration_method = sitk.ImageRegistrationMethod()
registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)
registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)
registration_method.SetMetricSamplingPercentage(0.01)
registration_method.SetInterpolator(sitk.sitkLinear)
registration_method.SetOptimizerAsGradientDescent(learningRate=1.0, numberOfIterations=100, estimateLearningRate=registration_method.Once)
registration_method.SetOptimizerScalesFromPhysicalShift()
registration_method.SetInitialTransform(initial_transform)
registration_method.SetShrinkFactorsPerLevel(shrinkFactors = [4,2,1])
registration_method.SetSmoothingSigmasPerLevel(smoothingSigmas = [2,1,0])
registration_method.SmoothingSigmasAreSpecifiedInPhysicalUnitsOn()
registration_method.AddCommand(sitk.sitkStartEvent, rc.metric_start_plot)
registration_method.AddCommand(sitk.sitkEndEvent, rc.metric_end_plot)
registration_method.AddCommand(sitk.sitkMultiResolutionIterationEvent, rc.metric_update_multires_iterations)
registration_method.AddCommand(sitk.sitkIterationEvent, lambda: rc.metric_plot_values(registration_method))
final_transform = registration_method.Execute(fixed_image, moving_image)
print('Final metric value: {0}'.format(registration_method.GetMetricValue()))
print('Optimizer\'s stopping condition, {0}'.format(registration_method.GetOptimizerStopConditionDescription()))
return final_transform
```
## Loading Data
```
data_directory = os.path.dirname(fdata("CIRS057A_MR_CT_DICOM/readme.txt"))
fixed_series_ID = "1.2.840.113619.2.290.3.3233817346.783.1399004564.515"
moving_series_ID = "1.3.12.2.1107.5.2.18.41548.30000014030519285935000000933"
reader = sitk.ImageSeriesReader()
fixed_image = sitk.ReadImage(reader.GetGDCMSeriesFileNames(data_directory, fixed_series_ID), sitk.sitkFloat32)
moving_image = sitk.ReadImage(reader.GetGDCMSeriesFileNames(data_directory, moving_series_ID), sitk.sitkFloat32)
# To provide a reasonable display we need to window/level the images. By default we could have used the intensity
# ranges found in the images [SimpleITK's StatisticsImageFilter], but these are not the best values for viewing.
# Using an external viewer we identified the following settings.
fixed_intensity_range = (-1183,544)
moving_intensity_range = (0,355)
interact(lambda image1_z, image2_z, image1, image2,:ru.display_scalar_images(image1_z, image2_z, image1, image2,
fixed_intensity_range,
moving_intensity_range,
'fixed image',
'moving image'),
image1_z=(0,fixed_image.GetSize()[2]-1),
image2_z=(0,moving_image.GetSize()[2]-1),
image1 = fixed(fixed_image),
image2=fixed(moving_image));
```
Arbitrarily rotate the moving image.
```
rotation_x = 0.0
rotation_z = 0.0
def modify_rotation(rx_in_degrees, rz_in_degrees):
global rotation_x, rotation_z
rotation_x = np.radians(rx_in_degrees)
rotation_z = np.radians(rz_in_degrees)
interact(modify_rotation, rx_in_degrees=(0.0,180.0,5.0), rz_in_degrees=(-90.0,180.0,5.0));
resample = sitk.ResampleImageFilter()
resample.SetReferenceImage(moving_image)
resample.SetInterpolator(sitk.sitkLinear)
# Rotate around the physical center of the image.
rotation_center = moving_image.TransformContinuousIndexToPhysicalPoint([(index-1)/2.0 for index in moving_image.GetSize()])
transform = sitk.Euler3DTransform(rotation_center, rotation_x, 0, rotation_z, (0,0,0))
resample.SetTransform(transform)
modified_moving_image = resample.Execute(moving_image)
interact(lambda image1_z, image2_z, image1, image2,:ru.display_scalar_images(image1_z, image2_z, image1, image2,
moving_intensity_range,
moving_intensity_range, 'original', 'rotated'),
image1_z=(0,moving_image.GetSize()[2]-1),
image2_z=(0,modified_moving_image.GetSize()[2]-1),
image1 = fixed(moving_image),
image2=fixed(modified_moving_image));
```
## Register using standard initialization (assumes orientation is similar)
```
initial_transform = sitk.CenteredTransformInitializer(fixed_image,
modified_moving_image,
sitk.Euler3DTransform(),
sitk.CenteredTransformInitializerFilter.GEOMETRY)
final_transform = multires_registration(fixed_image, modified_moving_image, initial_transform)
```
Visually evaluate our results:
```
moving_resampled = sitk.Resample(modified_moving_image, fixed_image, final_transform, sitk.sitkLinear, 0.0, moving_image.GetPixelID())
interact(ru.display_images_with_alpha, image_z=(0,fixed_image.GetSize()[2]), alpha=(0.0,1.0,0.05),
image1 = fixed(sitk.IntensityWindowing(fixed_image, fixed_intensity_range[0], fixed_intensity_range[1])),
image2=fixed(sitk.IntensityWindowing(moving_resampled, moving_intensity_range[0], moving_intensity_range[1])));
```
## Register using heuristic initialization approach (using multiple orientations)
As we want to account for significant orientation differences due to erroneous patient position (HFS...) we evaluate the similarity measure at locations corresponding to the various orientation differences. This can be done in two ways which will be illustrated below:
<ul>
<li>Use the ImageRegistrationMethod.MetricEvaluate() method.</li>
<li>Use the Exhaustive optimizer.
</ul>
The former approach is more computationally intensive as it constructs and configures a metric object each time it is invoked. It is therefore more appropriate for use if the set of parameter values we want to evaluate are not on a rectilinear grid in the parameter space. The latter approach is appropriate if the set of parameter values are on a rectilinear grid, in which case the approach is more computationally efficient.
In both cases we use the CenteredTransformInitializer to obtain the initial translation.
### MetricEvaluate
To use the MetricEvaluate method we create a ImageRegistrationMethod, set its metric and interpolator. We then iterate over all parameter settings, set the initial transform and evaluate the metric. The minimal similarity measure value corresponds to the best parameter settings.
```
# Dictionary with all the orientations we will try. We omit the identity (x=0, y=0, z=0) as we always use it. This
# set of rotations is arbitrary. For a complete grid coverage we would naively have 64 entries
# (0, pi/2, pi, 1.5pi for each angle), but we know better, there are only 24 unique rotation matrices defined by
# these parameter value combinations.
all_orientations = {'x=0, y=0, z=90': (0.0,0.0,np.pi/2.0),
'x=0, y=0, z=-90': (0.0,0.0,-np.pi),
'x=0, y=0, z=180': (0.0,0.0,np.pi),
'x=180, y=0, z=0': (np.pi,0.0,0.0),
'x=180, y=0, z=90': (np.pi,0.0,np.pi/2.0),
'x=180, y=0, z=-90': (np.pi,0.0,-np.pi/2.0),
'x=180, y=0, z=180': (np.pi,0.0,np.pi)}
# Registration framework setup.
registration_method = sitk.ImageRegistrationMethod()
registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)
registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)
registration_method.SetMetricSamplingPercentage(0.01)
registration_method.SetInterpolator(sitk.sitkLinear)
# Evaluate the similarity metric using the eight possible orientations, translation remains the same for all.
initial_transform = sitk.Euler3DTransform(sitk.CenteredTransformInitializer(fixed_image,
modified_moving_image,
sitk.Euler3DTransform(),
sitk.CenteredTransformInitializerFilter.GEOMETRY))
registration_method.SetInitialTransform(initial_transform, inPlace=False)
best_orientation = (0.0,0.0,0.0)
best_similarity_value = registration_method.MetricEvaluate(fixed_image, modified_moving_image)
# Iterate over all other rotation parameter settings.
for key, orientation in all_orientations.items():
initial_transform.SetRotation(*orientation)
registration_method.SetInitialTransform(initial_transform)
current_similarity_value = registration_method.MetricEvaluate(fixed_image, modified_moving_image)
if current_similarity_value < best_similarity_value:
best_similarity_value = current_similarity_value
best_orientation = orientation
print('best orientation is: ' + str(best_orientation))
```
#### Why loop if you can process in parallel
As the metric evaluations are independent of each other, we can easily replace looping with parallelization.
```
from multiprocessing.pool import ThreadPool
from functools import partial
# This function evaluates the metric value in a thread safe manner
def evaluate_metric(current_rotation, tx, f_image, m_image):
registration_method = sitk.ImageRegistrationMethod()
registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)
registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)
registration_method.SetMetricSamplingPercentage(0.01)
registration_method.SetInterpolator(sitk.sitkLinear)
current_transform = sitk.Euler3DTransform(tx)
current_transform.SetRotation(*current_rotation)
registration_method.SetInitialTransform(current_transform)
res = registration_method.MetricEvaluate(f_image, m_image)
return res
p = ThreadPool(9)
orientations_list = [(0,0,0)] + list(all_orientations.values())
all_metric_values = p.map(partial(evaluate_metric,
tx = initial_transform,
f_image = fixed_image,
m_image = modified_moving_image),
orientations_list)
best_orientation = orientations_list[np.argmin(all_metric_values)]
print('best orientation is: ' + str(best_orientation))
initial_transform.SetRotation(*best_orientation)
final_transform = multires_registration(fixed_image, modified_moving_image, initial_transform)
```
Visually evaluate our results:
```
moving_resampled = sitk.Resample(modified_moving_image, fixed_image, final_transform, sitk.sitkLinear, 0.0, moving_image.GetPixelID())
interact(ru.display_images_with_alpha, image_z=(0,fixed_image.GetSize()[2]), alpha=(0.0,1.0,0.05),
image1 = fixed(sitk.IntensityWindowing(fixed_image, fixed_intensity_range[0], fixed_intensity_range[1])),
image2=fixed(sitk.IntensityWindowing(moving_resampled, moving_intensity_range[0], moving_intensity_range[1])));
```
### Exhaustive optimizer
The exhaustive optimizer evaluates the similarity measure using a grid overlaid on the parameter space.
The grid is centered on the parameter values set by the SetInitialTransform, and the location of its vertices are determined by the <b>numberOfSteps</b>, <b>stepLength</b> and <b>optimizer scales</b>. To quote the documentation of this class: "a side of the region is stepLength*(2*numberOfSteps[d]+1)*scaling[d]."
Using this approach we have superfluous evaluations (15 evaluations corresponding to 3 values for rotations around the x axis and five for rotation around the z axis, as compared to the 8 evaluations using the MetricEvaluate method).
```
initial_transform = sitk.CenteredTransformInitializer(fixed_image,
modified_moving_image,
sitk.Euler3DTransform(),
sitk.CenteredTransformInitializerFilter.GEOMETRY)
registration_method = sitk.ImageRegistrationMethod()
registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)
registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)
registration_method.SetMetricSamplingPercentage(0.01)
registration_method.SetInterpolator(sitk.sitkLinear)
# The order of parameters for the Euler3DTransform is [angle_x, angle_y, angle_z, t_x, t_y, t_z]. The parameter
# sampling grid is centered on the initial_transform parameter values, that are all zero for the rotations. Given
# the number of steps and their length and optimizer scales we have:
# angle_x = -pi, 0, pi
# angle_y = 0
# angle_z = -pi, -pi/2, 0, pi/2, pi
registration_method.SetOptimizerAsExhaustive(numberOfSteps=[1,0,2,0,0,0], stepLength = np.pi)
registration_method.SetOptimizerScales([1,1,0.5,1,1,1])
#Perform the registration in-place so that the initial_transform is modified.
registration_method.SetInitialTransform(initial_transform, inPlace=True)
registration_method.Execute(fixed_image, modified_moving_image)
final_transform = multires_registration(fixed_image, modified_moving_image, initial_transform)
```
Visually evaluate our results:
```
moving_resampled = sitk.Resample(modified_moving_image, fixed_image, final_transform, sitk.sitkLinear, 0.0, moving_image.GetPixelID())
interact(ru.display_images_with_alpha, image_z=(0,fixed_image.GetSize()[2]), alpha=(0.0,1.0,0.05),
image1 = fixed(sitk.IntensityWindowing(fixed_image, fixed_intensity_range[0], fixed_intensity_range[1])),
image2=fixed(sitk.IntensityWindowing(moving_resampled, moving_intensity_range[0], moving_intensity_range[1])));
```
| github_jupyter |
```
import sys, os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.stats import bayes_mvs as bayesest
import time
from PyEcoLib.simulator import Simulator
%matplotlib inline
mean_size = 3 # micron
doubling_time = 18 #min
tmax = 180 #min
sample_time = 2 #min
div_steps = 10
ncells = 5000
gr = np.log(2)/doubling_time
if not os.path.exists('./data'):
os.makedirs('./data') #data path
if not os.path.exists('./figures'):
os.makedirs('./figures') #Figures path
sim = Simulator(ncells=ncells, gr = gr, sb=mean_size, steps = div_steps) #Initializing the simulator
start = time.time()
sim.divstrat(tmax = tmax, sample_time = 0.1*doubling_time, nameDSM = "./data/dataDSM.csv") #Obtaining the simulation of Sd vs Sb
print('It took', np.int(time.time()-start), 'seconds.')
start = time.time()
sim.szdyn(tmax = tmax, sample_time= 0.1*doubling_time, nameCRM = "./data/dataCRM.csv") #Simulating the size for all the cells
print('It took', np.int(time.time()-start), 'seconds.')
start = time.time()
sim.szdynFSP(tmax = tmax, nameFSP = "./data/dataFSP.csv") #Obtaining trends using numerical FSP algorithm
print('It took', np.int(time.time()-start), 'seconds.')
sbar=np.linspace(0.5,1.5,100)*mean_size
cv2sz=[]
deltsz=[]
for i in sbar:
Added,cv2=sim.SdStat(i) #Obtaining trends in sd vs Sb using master equation formulation
cv2sz.append(cv2)
deltsz.append(Added)
data1=pd.read_csv("./data/dataCRM.csv")
timearray=data1.time.unique()
mnszarray=[]
cvszarray=[]
errcv2sz=[]
errmnsz=[]
df=data1
del df['time']
for m in range(len(df)):
szs=df.loc[m, :].values.tolist()
mean_cntr, var_cntr, std_cntr = bayesest(szs,alpha=0.95)
mnszarray.append(np.mean(szs))
errmnsz.append(mean_cntr[1][1]-mean_cntr[0])
cvszarray.append(np.var(szs)/np.mean(szs)**2)
errv=(var_cntr[1][1]-var_cntr[0])/mean_cntr[0]**2+2*(mean_cntr[1][1]-mean_cntr[0])*var_cntr[0]/mean_cntr[0]**3
errcv2sz.append(errv)
fig, ax = plt.subplots(1,2, figsize=(12,4))
data=pd.read_csv("./data/dataCRM.csv")
tt=data.time
del data['time']
for column in data.columns[0:10]:
ax[0].plot(tt/doubling_time,data[column],c="#B9B9B9",label='_nolegend_')
ax[0].plot(np.array(timearray)/doubling_time,mnszarray)
ax[0].fill_between(np.array(timearray)/doubling_time,np.array(mnszarray)-np.array(errmnsz),np.array(mnszarray)+np.array(errmnsz),
alpha=1, edgecolor='#4db8ff', facecolor='#4db8ff',linewidth=0,label="SSA")
ax[1].plot(np.array(timearray)/doubling_time,cvszarray)
ax[1].fill_between(np.array(timearray)/doubling_time,np.array(cvszarray)-np.array(errcv2sz),np.array(cvszarray)+np.array(errcv2sz),
alpha=1, edgecolor='#4db8ff', facecolor='#4db8ff',linewidth=0)
data=pd.read_csv("./data/dataFSP.csv")
ax[0].plot(data.time/doubling_time,data.Meansize,ls='--',c='g',label="Numeric",lw=2)
ax[1].plot(data.time/doubling_time,data.VarSize/data.Meansize**2,ls='--',c='g',lw=2)
ax[0].set_ylabel("$s$ $(\mu m)$",size=20)
ax[1].set_ylabel("$C_V^2(s)$",size=20)
ax[0].set_xlabel(r"$t/\tau$",size=20)
ax[1].set_xlabel(r"$t/\tau$",size=20)
#ax[0].set_ylim([1,1.7])
#ax[1].set_ylim([0,0.15])
for l in [0,1]:
ax[l].set_xlim([0,7])
taqui=np.arange(0,8,step=1)
ax[l].set_xticks(np.array(taqui))
ax[l].grid()
ax[l].tick_params(axis='x', labelsize=15)
ax[l].tick_params(axis='y', labelsize=15)
for axis in ['bottom','left']:
ax[l].spines[axis].set_linewidth(2)
ax[l].tick_params(axis='both', width=2,length=6)
for axis in ['top','right']:
ax[l].spines[axis].set_linewidth(0)
ax[l].tick_params(axis='both', width=0,length=6)
plt.subplots_adjust(hspace=0.3,wspace=0.3)
taqui=np.arange(0,0.15,step=0.02)
ax[1].set_yticks(np.array(taqui))
ax[0].legend(fontsize=15)
plt.savefig('./figures/size_statistics.svg',bbox_inches='tight')
plt.savefig('./figures/size_statistics.png',bbox_inches='tight')
data2=pd.read_csv("./data/dataDSM.csv")
data2=data2[data2.time>3*doubling_time]
fig, ax = plt.subplots(1,2, figsize=(12,4))
ax[0].scatter(data2.S_b/np.mean(data2.S_b),(data2.S_d-data2.S_b)/np.mean(data2.S_b),s=2)
quantnumber=5
pvadd2=data2
CV2d=[]
delt=[]
sb=[]
errcv2d=[]
errdelt=[]
errsb=[]
for i in range(quantnumber):
lperv0=np.percentile(pvadd2.S_b,i*100/quantnumber)
hperv0=np.percentile(pvadd2.S_b,(i+1)*100/quantnumber)
quanta1=pvadd2[pvadd2.S_b>lperv0]
quanta2=quanta1[quanta1.S_b<hperv0]
mean_cntr, var_cntr, std_cntr = bayesest((quanta2.S_d-quanta2.S_b)/np.mean(pvadd2.S_d-pvadd2.S_b),alpha=0.95)
meanv0_cntr, varv0_cntr, stdv0_cntr = bayesest(quanta2.S_b/np.mean(pvadd2.S_b),alpha=0.95)
CV2d.append(var_cntr[0]/mean_cntr[0]**2)
delt.append(mean_cntr[0])
sb.append(meanv0_cntr[0])
errv=(var_cntr[1][1]-var_cntr[0])/mean_cntr[0]**2+2*(mean_cntr[1][1]-mean_cntr[0])*var_cntr[0]/mean_cntr[0]**3
errcv2d.append(errv)
errdelt.append(mean_cntr[1][1]-mean_cntr[0])
errsb.append(meanv0_cntr[1][1]-meanv0_cntr[0])
ax[0].errorbar(np.array(sb),np.array(delt),xerr=errsb,yerr=errdelt, fmt='o',mec='k',capsize=5,markersize='8',elinewidth=3,c='#0075BD',label="SSA")
ax[1].errorbar(np.array(sb),CV2d,xerr=errsb,yerr=errcv2d, fmt='o',mec='k',capsize=5,markersize='8',elinewidth=3,c='#0075BD',label="SSA")
ax[1].set_ylim([0,0.3])
ax[0].set_xlabel("$s_b/\overline{s_b}$",size=20)
ax[1].set_xlabel("$s_b/\overline{s_b}$",size=20)
ax[0].set_ylabel("$\Delta/\overline{s_b}$",size=15)
ax[1].set_ylabel("$C_V^2(\Delta)$",size=15)
for l in [0,1]:
ax[l].set_xlim([0.2,2])
ax[l].grid()
ax[l].tick_params(axis='x', labelsize=15)
ax[l].tick_params(axis='y', labelsize=15)
for axis in ['bottom','left']:
ax[l].spines[axis].set_linewidth(2)
ax[l].tick_params(axis='both', width=2,length=6)
for axis in ['top','right']:
ax[l].spines[axis].set_linewidth(0)
ax[l].tick_params(axis='both', width=0,length=6)
ax[0].plot(np.array(sbar)/mean_size, np.array(deltsz)/mean_size, lw=2,c='k',label="Numeric")
ax[1].plot(np.array(sbar)/mean_size, cv2sz, lw=2,c='k',label="Numeric")
ax[1].legend(fontsize=15)
plt.savefig('./figures/div_strategy.eps',bbox_inches='tight')
plt.savefig('./figures/div_strategy.svg',bbox_inches='tight')
plt.savefig('./figures/div_strategy.png',bbox_inches='tight')
data2
```
| github_jupyter |
# Two-body problems, from the Gravitational Force to Two-body Scattering
## Introduction and Definitions
Central forces are forces which are directed towards or away from a
reference point. A familiar force is the gravitional
force with the motion of our Earth around the Sun as a classic. The Sun, being
approximately sixth order of magnitude heavier than the Earth serves
as our origin. A force like the gravitational force is a function of the
relative distance $\boldsymbol{r}=\boldsymbol{r}_1-\boldsymbol{r}_2$ only, where
$\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ are the positions relative to a defined
origin for object one and object two, respectively.
These forces depend on the spatial degrees of freedom only (the
positions of the interacting objects/particles). As discussed earlier, from such forces we can infer
that the total internal energy, the total linear momentum and total angular momentum are so-called constants of the motion, that is they stay constant over time. We say that energy, linear and anuglar momentum are conserved.
With a scalar potential $V(\boldsymbol{r})$ we define the force as the gradient of the potential
$$
\boldsymbol{F}(\boldsymbol{r})=-\boldsymbol{\nabla}V(\boldsymbol{r}).
$$
In general these potentials depend only on the magnitude of the
relative position and we will write the potential as $V(r)$ where $r$
is defined as,
$$
r = |\boldsymbol{r}_1-\boldsymbol{r}_2|.
$$
In three dimensions our vectors are defined as (for a given object/particle $i$)
$$
\boldsymbol{r}_i = x_i\boldsymbol{e}_1+y_i\boldsymbol{e}_2+z_i\boldsymbol{e}_3,
$$
while in two dimensions we have
$$
\boldsymbol{r}_i = x_i\boldsymbol{e}_1+y_i\boldsymbol{e}_2.
$$
In two dimensions the radius $r$ is defined as
$$
r = |\boldsymbol{r}_1-\boldsymbol{r}_2|=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}.
$$
If we consider the gravitational potential involving two masses $1$ and $2$, we have
$$
V_{12}(r)=V(r)=-\frac{Gm_1m_2}{|\boldsymbol{r}_1-\boldsymbol{r}_2|}=-\frac{Gm_1m_2}{r}.
$$
Calculating the gradient of this potential we obtain the force
$$
\boldsymbol{F}(\boldsymbol{r})=-\frac{Gm_1m_2}{|\boldsymbol{r}_1-\boldsymbol{r}_1|^2}\hat{\boldsymbol{r}}_{12}=-\frac{Gm_am_b}{r^2}\hat{\boldsymbol{r}},
$$
where we have the unit vector
$$
\hat{\boldsymbol{r}}=\hat{\boldsymbol{r}}_{12}=\frac{\boldsymbol{r}_2-\boldsymbol{r}_1}{|\boldsymbol{r}_1-\boldsymbol{r}_2|}.
$$
Here $G=6.67\times 10^{-11}$ Nm$^2$/kg$^2$, and $\boldsymbol{F}$ is the force
on $2$ due to $1$. By inspection, one can see that the force on $2$
due to $1$ and the force on $1$ due to $2$ are equal and opposite. The
net potential energy for a large number of masses would be
$$
V=\sum_{i<j}V_{ij}=\frac{1}{2}\sum_{i\ne j}V_{ij}.
$$
In general, the central forces that we will study can be written mathematically as
$$
\boldsymbol{F}(\boldsymbol{r})=f(r)\hat{r},
$$
where $f(r)$ is a scalar function. For the above gravitational force this scalar term is
$-Gm_1m_2/r^2$.
In general we will simply write this scalar function $f(r)=\alpha/r^2$ where $\alpha$ is a constant that can be either negative or positive. We will also see examples of other types of potentials in the examples below.
Besides general expressions for the potentials/forces, we will discuss
in detail different types of motion that arise, from circular to
elliptical or hyperbolic or parabolic. By transforming to either polar
coordinates or spherical coordinates, we will be able to obtain
analytical solutions for the equations of motion and thereby obtain
new insights about the properties of a system. Where possible, we will
compare our analytical equations with numerical studies.
However, before we arrive at these lovely insights, we need to
introduce some mathematical manipulations and definitions. We conclude
this chapter with a discussion of two-body scattering.
## Center of Mass and Relative Coordinates
Thus far, we have considered the trajectory as if the force is
centered around a fixed point. For two bodies interacting only with
one another, both masses circulate around the center of mass. One
might think that solutions would become more complex when both
particles move, but we will see here that the problem can be reduced
to one with a single body moving according to a fixed force by
expressing the trajectories for $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ into the
center-of-mass coordinate $\boldsymbol{R}$ and the relative
coordinate $\boldsymbol{r}$. We define the center-of-mass (CoM) coordinate as
$$
\boldsymbol{R}\equiv\frac{m_1\boldsymbol{r}_1+m_2\boldsymbol{r}_2}{m_1+m_2},
$$
and the relative coordinate as
$$
\boldsymbol{r}\equiv\boldsymbol{r}_1-\boldsymbol{r_2}.
$$
We can then rewrite $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative and CoM coordinates as
$$
\boldsymbol{r}_1=\boldsymbol{R}+\frac{m_2}{M}\boldsymbol{r},
$$
and
$$
\boldsymbol{r}_2=\boldsymbol{R}-\frac{m_1}{M}\boldsymbol{r}.
$$
### Conservation of total Linear Momentum
In our discussions on conservative forces we defined
the total linear momentum as
$$
\boldsymbol{P}=\sum_{i=1}^Nm_i\frac{d\boldsymbol{r}_i}{dt},
$$
where $N=2$ in our case. With the above definition of the center of mass position, we see that we can rewrite the total linear momentum as (multiplying the CoM coordinate with $M$)
$$
\boldsymbol{P}=M\frac{d\boldsymbol{R}}{dt}=M\dot{\boldsymbol{R}}.
$$
The net force acting on the system is given by the time derivative of the linear momentum (assuming mass is time independent)
and we have
$$
\boldsymbol{F}^{\mathrm{net}}=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}.
$$
The net force acting on the system is given by the sum of the forces acting on the two bodies, that is we have
$$
\boldsymbol{F}^{\mathrm{net}}=\boldsymbol{F}_1+\boldsymbol{F}_2=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}.
$$
In our case the forces are given by the internal forces only. The force acting on object $1$ is thus $\boldsymbol{F}_{12}$ and the one acting on object $2$ is $\boldsymbol{F}_{12}$. We have also defined that $\boldsymbol{F}_{12}=-\boldsymbol{F}_{21}$. This means thar we have
$$
\boldsymbol{F}_1+\boldsymbol{F}_2=\boldsymbol{F}_{12}+\boldsymbol{F}_{21}=0=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}.
$$
We could alternatively had write this
$$
\ddot{\boldsymbol{R}}_{\rm cm}=\frac{1}{m_1+m_2}\left\{m_1\ddot{\boldsymbol{r}}_1+m_2\ddot{\boldsymbol{r}}_2\right\}=\frac{1}{m_1+m_2}\left\{\boldsymbol{F}_{12}+\boldsymbol{F}_{21}\right\}=0.
$$
This has the important consequence that the CoM velocity is a constant
of the motion. And since the total linear momentum is given by the
time-derivative of the CoM coordinate times the total mass
$M=m_1+m_2$, it means that linear momentum is also conserved.
Stated differently, the center-of-mass coordinate
$\boldsymbol{R}$ moves at a fixed velocity.
This has also another important consequence for our forces. If we
assume that our force depends only on the relative coordinate, it
means that the gradient of the potential with respect to the center of
mass position is zero, that is
$$
M\ddot{d\boldsymbol{R}}=-\boldsymbol{\nabla}_{\boldsymbol{R}}V =0!
$$
If we now switch to the equation of motion for the relative coordinate, we have
$$
\ddot{\boldsymbol{r}}=\ddot{\boldsymbol{r}}_1-\ddot{\boldsymbol{r}}_2=\left(\frac{\boldsymbol{F}_{12}}{m_1}-\frac{\boldsymbol{F}_{21}}{m_2}\right)=\left(\frac{1}{m_1}+\frac{1}{m_2}\right)\boldsymbol{F}_{12},
$$
which we can rewrite in terms of the reduced mass
$$
\mu=\frac{m_1m_2}{m_1+m_2},
$$
as
$$
\mu \ddot{\boldsymbol{r}}=\boldsymbol{F}_{12}.
$$
This has a very important consequence for our coming analysis of the equations of motion for the two-body problem.
Since the acceleration for the CoM coordinate is zero, we can now
treat the trajectory as a one-body problem where the mass is given by
the reduced mass $\mu$ plus a second trivial problem for the center of
mass. The reduced mass is especially convenient when one is
considering forces that depend only on the relative coordinate (like the Gravitational force or the electrostatic force between two charges) because then for say the gravitational force we have
$$
\mu \ddot{\boldsymbol{r}}=-\frac{Gm_1m_2}{r^2}\hat{\boldsymbol{r}}=-\frac{GM\mu}{r^2}\hat{\boldsymbol{r}},
$$
where we have defined $M= m_1+m_2$. It means that the acceleration of the relative coordinate is
$$
\ddot{\boldsymbol{r}}=-\frac{GM}{r^2}\hat{\boldsymbol{r}},
$$
and we have that for the gravitational problem, the reduced mass then falls out and the
trajectory depends only on the total mass $M$.
The standard strategy is to transform into the center of mass frame,
then treat the problem as one of a single particle of mass $\mu$
undergoing a force $\boldsymbol{F}_{12}$. Scattering angles, see our discussion of scattering problems below, can also be
expressed in this frame. Before we proceed to our definition of the CoM frame we need to set up the expression for the energy in terms of the relative and CoM coordinates.
### Kinetic and total Energy
The kinetic energy and momenta also have analogues in center-of-mass
coordinates.
We have defined the total linear momentum as
$$
\boldsymbol{P}=\sum_{i=1}^Nm_i\frac{d\boldsymbol{r}_i}{dt}=M\dot{\boldsymbol{R}}.
$$
For the relative momentum $\boldsymbol{q}$, we have that the time derivative of $\boldsymbol{r}$ is
$$
\dot{\boldsymbol{r}} =\dot{\boldsymbol{r}}_1-\dot{\boldsymbol{r}}_2,
$$
We know also that the momenta $\boldsymbol{p}_1=m_1\dot{\boldsymbol{r}}_1$ and
$\boldsymbol{p}_2=m_2\dot{\boldsymbol{r}}_2$. Using these expressions we can rewrite
$$
\dot{\boldsymbol{r}} =\frac{\boldsymbol{p}_1}{m_1}-\frac{\boldsymbol{p}_2}{m_2},
$$
which gives
$$
\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{m_1m_2},
$$
and dividing both sides with $M$ we have
$$
\frac{m_1m_2}{M}\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{M}.
$$
Introducing the reduced mass $\mu=m_1m_2/M$ we have finally
$$
\mu\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{M}.
$$
And $\mu\dot{\boldsymbol{r}}$ defines the relative momentum $\boldsymbol{q}=\mu\dot{\boldsymbol{r}}$.
With these definitions we can then calculate the kinetic energy in terms of the relative and CoM coordinates.
We have that
$$
K=\frac{p_1^2}{2m_1}+\frac{p_2^2}{2m_2},
$$
and with $\boldsymbol{p}_1=m_1\dot{\boldsymbol{r}}_1$ and $\boldsymbol{p}_2=m_2\dot{\boldsymbol{r}}_2$ and using
$$
\dot{\boldsymbol{r}}_1=\dot{\boldsymbol{R}}+\frac{m_2}{M}\dot{\boldsymbol{r}},
$$
and
$$
\dot{\boldsymbol{r}}_2=\dot{\boldsymbol{R}}-\frac{m_1}{M}\dot{\boldsymbol{r}},
$$
we obtain after squaring the expressions for $\dot{\boldsymbol{r}}_1$ and $\dot{\boldsymbol{r}}_2$
$$
K=\frac{(m_1+m_2)\dot{\boldsymbol{R}}^2}{2}+\frac{(m_1+m_2)m_1m_2\dot{\boldsymbol{r}}^2}{2M^2},
$$
which we simplify to
$$
K=\frac{\dot{\boldsymbol{P}}^2}{2M}+\frac{\mu\dot{\boldsymbol{q}}^2}{2}.
$$
Below we will define a reference frame, the so-called CoM-frame, where
$\boldsymbol{R}=0$. This is going to simplify our equations further.
### Conservation of Angular Momentum
The angular momentum (the total one) is the sum of the individual angular momenta. In our case we have two bodies only, meaning that our angular momentum is defined as
$$
\boldsymbol{L} = \boldsymbol{r}_1 \times \boldsymbol{p}_1+\boldsymbol{r}_2 \times \boldsymbol{p}_2,
$$
and using that $m_1\dot{\boldsymbol{r}}_1=\boldsymbol{p}_1$ and $m_2\dot{\boldsymbol{r}}_2=\boldsymbol{p}_2$ we have
$$
\boldsymbol{L} = m_1\boldsymbol{r}_1 \times \dot{\boldsymbol{r}}_1+m_2\boldsymbol{r}_2 \times \dot{\boldsymbol{r}}_2.
$$
We define now the CoM-Frame where we set $\boldsymbol{R}=0$. This means that the equations
for $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative motion simplify and we have
$$
\boldsymbol{r}_1=\frac{m_2}{M}\boldsymbol{r},
$$
and
$$
\boldsymbol{r}_2=-\frac{m_1}{M}\boldsymbol{r}.
$$
resulting in
$$
\boldsymbol{L} = m_1 \frac{m_2}{M}\boldsymbol{r}\times\frac{m_2}{M}\boldsymbol{r} +m_2 \frac{m_1}{M}\boldsymbol{r} \times \frac{m_1}{M}\dot{\boldsymbol{r}}.
$$
We see that can rewrite this equation as
$$
\boldsymbol{L}=\boldsymbol{r}\times \mu\dot{\boldsymbol{r}}=\mu\boldsymbol{r}\times \dot{\boldsymbol{r}}.
$$
If we now use a central force, we have that
$$
\mu\dot{\boldsymbol{r}}=\boldsymbol{F}(\boldsymbol{r})=f(r)\hat{\boldsymbol{r}},
$$
and inserting this in the equation for the angular momentum we have
$$
\boldsymbol{L}=\boldsymbol{r}\times f(r)\hat{\boldsymbol{r}},
$$
which equals zero since we are taking the cross product of the vector
$\boldsymbol{r}$ with itself. Angular momentum is thus conserved and in
addition to the total linear momentum being conserved, we know that
energy is also conserved with forces that depend only on position and
the relative coordinate only.
Since angular momentum is conserved, we can idealize
the motion of our two objects as two bodies moving in a plane spanned by the
relative coordinate and the relative momentum. The angular
momentum is perpendicular to the plane spanned by these two vectors.
It means also, since $\boldsymbol{L}$ is conserved, that we can reduce our
problem to a motion in say the $xy$-plane. What we have done then is to
reduce a two-body problem in three-dimensions with six degrees of
freedom (the six coordinates of the two objects) to a problem defined
entirely by the relative coordinate in two dimensions. We have thus
moved from a problem with six degrees of freedom to one with two degrees of freedom only.
Since we deal with central forces that depend only on the
relative coordinate, we will show below that transforming to polar
coordinates, we cna find analytical solution to
the equation of motion
$$
\mu\dot{\boldsymbol{r}}=\boldsymbol{F}(\boldsymbol{r})=f(r)\hat{\boldsymbol{r}}.
$$
Note the boldfaced symbols for the relative position $\boldsymbol{r}$. Our vector $\boldsymbol{r}$ is defined as
$$
\boldsymbol{r}=x\boldsymbol{e}_1+y\boldsymbol{e}_2
$$
and introducing polar coordinates $r\in[0,\infty)$ and $\phi\in [0,2\pi]$ and the transformation
$$
r=\sqrt{x^2+y^2},
$$
and $x=r\cos\phi$ and $y=r\sin\phi$, we will rewrite our equation of motion by transforming from Cartesian coordinates to Polar coordinates. By so doing, we end up with two differential equations which can be solved analytically (it depends on the form of the potential).
What follows now is a rewrite of these equations and the introduction of Kepler's laws as well.
## Deriving Elliptical Orbits
Kepler's laws state that a gravitational orbit should be an ellipse
with the source of the gravitational field at one focus. Deriving this
is surprisingly messy. To do this, we first use angular momentum
conservation to transform the equations of motion so that it is in
terms of $r$ and $\phi$ instead of $r$ and $t$. The overall strategy
is to
1. Find equations of motion for $r$ and $t$ with no angle ($\phi$) mentioned, i.e. $d^2r/dt^2=\cdots$. Angular momentum conservation will be used, and the equation will involve the angular momentum $L$.
2. Use angular momentum conservation to find an expression for $\dot{\phi}$ in terms of $r$.
3. Use the chain rule to convert the equations of motions for $r$, an expression involving $r,\dot{r}$ and $\ddot{r}$, to one involving $r,dr/d\phi$ and $d^2r/d\phi^2$. This is quitecomplicated because the expressions will also involve a substitution $u=1/r$ so that one finds an expression in terms of $u$ and $\phi$.
4. Once $u(\phi)$ is found, you need to show that this can be converted to the familiar form for an ellipse.
We will now rewrite the above equation of motion (note the boldfaced vector $\boldsymbol{r}$)
$$
\mu \ddot{\boldsymbol{r}}=\boldsymbol{F}(\boldsymbol{r}),
$$
in polar coordinates.
What follows here is a repeated application of the chain rule for derivatives.
We start with derivative for $r$ as function of time in a cartesian basis
<!-- Equation labels as ordinary links -->
<div id="eq:radialeqofmotion"></div>
$$
\begin{eqnarray}
\label{eq:radialeqofmotion} \tag{1}
\frac{d}{dt}r^2&=&\frac{d}{dt}(x^2+y^2)=2x\dot{x}+2y\dot{y}=2r\dot{r},\\
\nonumber
\dot{r}&=&\frac{x}{r}\dot{x}+\frac{y}{r}\dot{y},\\
\nonumber
\ddot{r}&=&\frac{x}{r}\ddot{x}+\frac{y}{r}\ddot{y}
+\frac{\dot{x}^2+\dot{y}^2}{r}
-\frac{\dot{r}^2}{r}.
\end{eqnarray}
$$
Note that there are no vectors involved here.
Recognizing that the numerator of the third term is the velocity squared, and that it can be written in polar coordinates,
<!-- Equation labels as ordinary links -->
<div id="_auto1"></div>
$$
\begin{equation}
v^2=\dot{x}^2+\dot{y}^2=\dot{r}^2+r^2\dot{\phi}^2,
\label{_auto1} \tag{2}
\end{equation}
$$
one can write $\ddot{r}$ as
<!-- Equation labels as ordinary links -->
<div id="eq:radialeqofmotion2"></div>
$$
\begin{equation}
\label{eq:radialeqofmotion2} \tag{3}
\ddot{r}=\frac{F_x\cos\phi+F_y\sin\phi}{m}+\frac{\dot{r}^2+r^2\dot{\phi}^2}{r}-\frac{\dot{r}^2}{r}
\end{equation}
$$
$$
\nonumber
=\frac{F}{m}+\frac{r^2\dot{\phi}^2}{r}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto2"></div>
$$
\begin{equation}
\label{_auto2} \tag{4}
\end{equation}
$$
or
$$
m\ddot{r}=F+\frac{L^2}{mr^3}.
$$
This derivation used the fact that the force was radial,
$F=F_r=F_x\cos\phi+F_y\sin\phi$, and that angular momentum is
$L=mrv_{\phi}=mr^2\dot{\phi}$. The term $L^2/mr^3=mv^2/r$ behaves
like an additional force. Sometimes this is referred to as a
centrifugal force, but it is not a force. Instead, it is the
consequence of considering the motion in a rotating (and therefore
accelerating) frame.
Now, we switch to the particular case of an attractive inverse square
force, $F=-\alpha/r^2$, and show that the trajectory, $r(\phi)$, is
an ellipse. To do this we transform derivatives w.r.t. time to
derivatives w.r.t. $\phi$ using the chain rule combined with angular
momentum conservation, $\dot{\phi}=L/mr^2$.
<!-- Equation labels as ordinary links -->
<div id="eq:rtotheta"></div>
$$
\begin{eqnarray}
\label{eq:rtotheta} \tag{5}
\dot{r}&=&\frac{dr}{d\phi}\dot{\phi}=\frac{dr}{d\phi}\frac{L}{mr^2},\\
\nonumber
\ddot{r}&=&\frac{d^2r}{d\phi^2}\dot{\phi}^2
+\frac{dr}{d\phi}\left(\frac{d}{dr}\frac{L}{mr^2}\right)\dot{r}\\
\nonumber
&=&\frac{d^2r}{d\phi^2}\left(\frac{L}{mr^2}\right)^2
-2\frac{dr}{d\phi}\frac{L}{mr^3}\dot{r}\\
\nonumber
&=&\frac{d^2r}{d\phi^2}\left(\frac{L}{mr^2}\right)^2
-\frac{2}{r}\left(\frac{dr}{d\phi}\right)^2\left(\frac{L}{mr^2}\right)^2
\end{eqnarray}
$$
Equating the two expressions for $\ddot{r}$ in Eq.s ([3](#eq:radialeqofmotion2)) and ([5](#eq:rtotheta)) eliminates all the derivatives w.r.t. time, and provides a differential equation with only derivatives w.r.t. $\phi$,
<!-- Equation labels as ordinary links -->
<div id="eq:rdotdot"></div>
$$
\begin{equation}
\label{eq:rdotdot} \tag{6}
\frac{d^2r}{d\phi^2}\left(\frac{L}{mr^2}\right)^2
-\frac{2}{r}\left(\frac{dr}{d\phi}\right)^2\left(\frac{L}{mr^2}\right)^2
=\frac{F}{m}+\frac{L^2}{m^2r^3},
\end{equation}
$$
that when solved yields the trajectory, i.e. $r(\phi)$. Up to this
point the expressions work for any radial force, not just forces that
fall as $1/r^2$.
The trick to simplifying this differential equation for the inverse
square problems is to make a substitution, $u\equiv 1/r$, and rewrite
the differential equation for $u(\phi)$.
$$
\begin{eqnarray}
r&=&1/u,\\
\nonumber
\frac{dr}{d\phi}&=&-\frac{1}{u^2}\frac{du}{d\phi},\\
\nonumber
\frac{d^2r}{d\phi^2}&=&\frac{2}{u^3}\left(\frac{du}{d\phi}\right)^2-\frac{1}{u^2}\frac{d^2u}{d\phi^2}.
\end{eqnarray}
$$
Plugging these expressions into Eq. ([6](#eq:rdotdot)) gives an
expression in terms of $u$, $du/d\phi$, and $d^2u/d\phi^2$. After
some tedious algebra,
<!-- Equation labels as ordinary links -->
<div id="_auto3"></div>
$$
\begin{equation}
\frac{d^2u}{d\phi^2}=-u-\frac{F m}{L^2u^2}.
\label{_auto3} \tag{7}
\end{equation}
$$
For the attractive inverse square law force, $F=-\alpha u^2$,
<!-- Equation labels as ordinary links -->
<div id="_auto4"></div>
$$
\begin{equation}
\frac{d^2u}{d\phi^2}=-u+\frac{m\alpha}{L^2}.
\label{_auto4} \tag{8}
\end{equation}
$$
The solution has two arbitrary constants, $A$ and $\phi_0$,
<!-- Equation labels as ordinary links -->
<div id="eq:Ctrajectory"></div>
$$
\begin{eqnarray}
\label{eq:Ctrajectory} \tag{9}
u&=&\frac{m\alpha}{L^2}+A\cos(\phi-\phi_0),\\
\nonumber
r&=&\frac{1}{(m\alpha/L^2)+A\cos(\phi-\phi_0)}.
\end{eqnarray}
$$
The radius will be at a minimum when $\phi=\phi_0$ and at a
maximum when $\phi=\phi_0+\pi$. The constant $A$ is related to the
eccentricity of the orbit. When $A=0$ the radius is a constant
$r=L^2/(m\alpha)$, and the motion is circular. If one solved the
expression $mv^2/r=-\alpha/r^2$ for a circular orbit, using the
substitution $v=L/(mr)$, one would reproduce the expression
$r=L^2/(m\alpha)$.
The form describing the elliptical trajectory in
Eq. ([9](#eq:Ctrajectory)) can be identified as an ellipse with one
focus being the center of the ellipse by considering the definition of
an ellipse as being the points such that the sum of the two distances
between the two foci are a constant. Making that distance $2D$, the
distance between the two foci as $2a$, and putting one focus at the
origin,
$$
\begin{eqnarray}
2D&=&r+\sqrt{(r\cos\phi-2a)^2+r^2\sin^2\phi},\\
\nonumber
4D^2+r^2-4Dr&=&r^2+4a^2-4ar\cos\phi,\\
\nonumber
r&=&\frac{D^2-a^2}{D+a\cos\phi}=\frac{1}{D/(D^2-a^2)-a\cos\phi/(D^2-a^2)}.
\end{eqnarray}
$$
By inspection, this is the same form as Eq. ([9](#eq:Ctrajectory)) with $D/(D^2-a^2)=m\alpha/L^2$ and $a/(D^2-a^2)=A$.
Let us remind ourselves about what an ellipse is before we proceed.
```
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
from math import pi
u=1. #x-position of the center
v=0.5 #y-position of the center
a=2. #radius on the x-axis
b=1.5 #radius on the y-axis
t = np.linspace(0, 2*pi, 100)
plt.plot( u+a*np.cos(t) , v+b*np.sin(t) )
plt.grid(color='lightgray',linestyle='--')
plt.show()
```
## Effective or Centrifugal Potential
The total energy of a particle is
$$
\begin{eqnarray}
E&=&V(r)+\frac{1}{2}mv_\phi^2+\frac{1}{2}m\dot{r}^2\\
\nonumber
&=&V(r)+\frac{1}{2}mr^2\dot{\phi}^2+\frac{1}{2}m\dot{r}^2\\
\nonumber
&=&V(r)+\frac{L^2}{2mr^2}+\frac{1}{2}m\dot{r}^2.
\end{eqnarray}
$$
The second term then contributes to the energy like an additional
repulsive potential. The term is sometimes referred to as the
"centrifugal" potential, even though it is actually the kinetic energy
of the angular motion. Combined with $V(r)$, it is sometimes referred
to as the "effective" potential,
$$
\begin{eqnarray}
V_{\rm eff}(r)&=&V(r)+\frac{L^2}{2mr^2}.
\end{eqnarray}
$$
Note that if one treats the effective potential like a real potential, one would expect to be able to generate an effective force,
$$
\begin{eqnarray}
F_{\rm eff}&=&-\frac{d}{dr}V(r) -\frac{d}{dr}\frac{L^2}{2mr^2}\\
\nonumber
&=&F(r)+\frac{L^2}{mr^3}=F(r)+m\frac{v_\perp^2}{r},
\end{eqnarray}
$$
which is indeed matches the form for $m\ddot{r}$ in Eq. ([3](#eq:radialeqofmotion2)), which included the **centrifugal** force.
The following code plots this effective potential for a simple choice of parameters, with a standard gravitational potential $-\alpha/r$. Here we have chosen $L=m=\alpha=1$.
```
# Common imports
import numpy as np
from math import *
import matplotlib.pyplot as plt
Deltax = 0.01
#set up arrays
xinitial = 0.3
xfinal = 5.0
alpha = 1.0 # spring constant
m = 1.0 # mass, you can change these
AngMom = 1.0 # The angular momentum
n = ceil((xfinal-xinitial)/Deltax)
x = np.zeros(n)
for i in range(n):
x[i] = xinitial+i*Deltax
V = np.zeros(n)
V = -alpha/x+0.5*AngMom*AngMom/(m*x*x)
# Plot potential
fig, ax = plt.subplots()
ax.set_xlabel('r[m]')
ax.set_ylabel('V[J]')
ax.plot(x, V)
fig.tight_layout()
plt.show()
```
### Gravitational force example
Using the above parameters, we can now study the evolution of the system using for example the velocity Verlet method.
This is done in the code here for an initial radius equal to the minimum of the potential well. We seen then that the radius is always the same and corresponds to a circle (the radius is always constant).
```
# Common imports
import numpy as np
import pandas as pd
from math import *
import matplotlib.pyplot as plt
import os
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
# Simple Gravitational Force -alpha/r
DeltaT = 0.01
#set up arrays
tfinal = 100.0
n = ceil(tfinal/DeltaT)
# set up arrays for t, v and r
t = np.zeros(n)
v = np.zeros(n)
r = np.zeros(n)
# Constants of the model, setting all variables to one for simplicity
alpha = 1.0
AngMom = 1.0 # The angular momentum
m = 1.0 # scale mass to one
c1 = AngMom*AngMom/(m*m)
c2 = AngMom*AngMom/m
rmin = (AngMom*AngMom/m/alpha)
# Initial conditions
r0 = rmin
v0 = 0.0
r[0] = r0
v[0] = v0
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up acceleration
a = -alpha/(r[i]**2)+c1/(r[i]**3)
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3)
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
# Plot position as function of time
fig, ax = plt.subplots(2,1)
ax[0].set_xlabel('time')
ax[0].set_ylabel('radius')
ax[0].plot(t,r)
ax[1].set_xlabel('time')
ax[1].set_ylabel('Velocity')
ax[1].plot(t,v)
save_fig("RadialGVV")
plt.show()
```
Changing the value of the initial position to a value where the energy is positive, leads to an increasing radius with time, a so-called unbound orbit. Choosing on the other hand an initial radius that corresponds to a negative energy and different from the minimum value leads to a radius that oscillates back and forth between two values.
### Harmonic Oscillator in two dimensions
Consider a particle of mass $m$ in a 2-dimensional harmonic oscillator with potential
$$
V=\frac{1}{2}kr^2=\frac{1}{2}k(x^2+y^2).
$$
If the orbit has angular momentum $L$, we can find the radius and angular velocity of the circular orbit as well as the b) the angular frequency of small radial perturbations.
We consider the effective potential. The radius of a circular orbit is at the minimum of the potential (where the effective force is zero).
The potential is plotted here with the parameters $k=m=0.1$ and $L=1.0$.
```
# Common imports
import numpy as np
from math import *
import matplotlib.pyplot as plt
Deltax = 0.01
#set up arrays
xinitial = 0.5
xfinal = 3.0
k = 1.0 # spring constant
m = 1.0 # mass, you can change these
AngMom = 1.0 # The angular momentum
n = ceil((xfinal-xinitial)/Deltax)
x = np.zeros(n)
for i in range(n):
x[i] = xinitial+i*Deltax
V = np.zeros(n)
V = 0.5*k*x*x+0.5*AngMom*AngMom/(m*x*x)
# Plot potential
fig, ax = plt.subplots()
ax.set_xlabel('r[m]')
ax.set_ylabel('V[J]')
ax.plot(x, V)
fig.tight_layout()
plt.show()
```
$$
\begin{eqnarray*}
V_{\rm eff}&=&\frac{1}{2}kr^2+\frac{L^2}{2mr^2}
\end{eqnarray*}
$$
The effective potential looks like that of a harmonic oscillator for
large $r$, but for small $r$, the centrifugal potential repels the
particle from the origin. The combination of the two potentials has a
minimum for at some radius $r_{\rm min}$.
$$
\begin{eqnarray*}
0&=&kr_{\rm min}-\frac{L^2}{mr_{\rm min}^3},\\
r_{\rm min}&=&\left(\frac{L^2}{mk}\right)^{1/4},\\
\dot{\phi}&=&\frac{L}{mr_{\rm min}^2}=\sqrt{k/m}.
\end{eqnarray*}
$$
For particles at $r_{\rm min}$ with $\dot{r}=0$, the particle does not
accelerate and $r$ stays constant, i.e. a circular orbit. The radius
of the circular orbit can be adjusted by changing the angular momentum
$L$.
For the above parameters this minimum is at $r_{\rm min}=1$.
Now consider small vibrations about $r_{\rm min}$. The effective spring constant is the curvature of the effective potential.
$$
\begin{eqnarray*}
k_{\rm eff}&=&\left.\frac{d^2}{dr^2}V_{\rm eff}(r)\right|_{r=r_{\rm min}}=k+\frac{3L^2}{mr_{\rm min}^4}\\
&=&4k,\\
\omega&=&\sqrt{k_{\rm eff}/m}=2\sqrt{k/m}=2\dot{\phi}.
\end{eqnarray*}
$$
Here, the second step used the result of the last step from part
(a). Because the radius oscillates with twice the angular frequency,
the orbit has two places where $r$ reaches a minimum in one
cycle. This differs from the inverse-square force where there is one
minimum in an orbit. One can show that the orbit for the harmonic
oscillator is also elliptical, but in this case the center of the
potential is at the center of the ellipse, not at one of the foci.
The solution is also simple to write down exactly in Cartesian coordinates. The $x$ and $y$ equations of motion separate,
$$
\begin{eqnarray*}
\ddot{x}&=&-kx,\\
\ddot{y}&=&-ky.
\end{eqnarray*}
$$
So the general solution can be expressed as
$$
\begin{eqnarray*}
x&=&A\cos\omega_0 t+B\sin\omega_0 t,\\
y&=&C\cos\omega_0 t+D\sin\omega_0 t.
\end{eqnarray*}
$$
The code here finds the solution for $x$ and $y$ using the code we developed in homework 5 and 6 and the midterm. Note that this code is tailored to run in Cartesian coordinates. There is thus no angular momentum dependent term.
```
DeltaT = 0.01
#set up arrays
tfinal = 10.0
n = ceil(tfinal/DeltaT)
# set up arrays
t = np.zeros(n)
v = np.zeros((n,2))
r = np.zeros((n,2))
radius = np.zeros(n)
# Constants of the model
k = 1.0 # spring constant
m = 1.0 # mass, you can change these
omega02 = sqrt(k/m) # Frequency
AngMom = 1.0 # The angular momentum
rmin = (AngMom*AngMom/k/m)**0.25
# Initial conditions as compact 2-dimensional arrays
x0 = rmin-0.5; y0= sqrt(rmin*rmin-x0*x0)
r0 = np.array([x0,y0])
v0 = np.array([0.0,0.0])
r[0] = r0
v[0] = v0
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up the acceleration
a = -r[i]*omega02
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
anew = -r[i+1]*omega02
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
# Plot position as function of time
radius = np.sqrt(r[:,0]**2+r[:,1]**2)
fig, ax = plt.subplots(3,1)
ax[0].set_xlabel('time')
ax[0].set_ylabel('radius squared')
ax[0].plot(t,r[:,0]**2+r[:,1]**2)
ax[1].set_xlabel('time')
ax[1].set_ylabel('x position')
ax[1].plot(t,r[:,0])
ax[2].set_xlabel('time')
ax[2].set_ylabel('y position')
ax[2].plot(t,r[:,1])
fig.tight_layout()
save_fig("2DimHOVV")
plt.show()
```
With some work using double angle formulas, one can calculate
$$
\begin{eqnarray*}
r^2&=&x^2+y^2\\
\nonumber
&=&(A^2+C^2)\cos^2(\omega_0t)+(B^2+D^2)\sin^2\omega_0t+(AB+CD)\cos(\omega_0t)\sin(\omega_0t)\\
\nonumber
&=&\alpha+\beta\cos 2\omega_0 t+\gamma\sin 2\omega_0 t,\\
\alpha&=&\frac{A^2+B^2+C^2+D^2}{2},~~\beta=\frac{A^2-B^2+C^2-D^2}{2},~~\gamma=AB+CD,\\
r^2&=&\alpha+(\beta^2+\gamma^2)^{1/2}\cos(2\omega_0 t-\delta),~~~\delta=\arctan(\gamma/\beta),
\end{eqnarray*}
$$
and see that radius oscillates with frequency $2\omega_0$. The
factor of two comes because the oscillation $x=A\cos\omega_0t$ has two
maxima for $x^2$, one at $t=0$ and one a half period later.
The following code shows first how we can solve this problem using the radial degrees of freedom only.
```
DeltaT = 0.01
#set up arrays
tfinal = 10.0
n = ceil(tfinal/DeltaT)
# set up arrays for t, v and r
t = np.zeros(n)
v = np.zeros(n)
r = np.zeros(n)
E = np.zeros(n)
# Constants of the model
AngMom = 1.0 # The angular momentum
m = 1.0
k = 1.0
omega02 = k/m
c1 = AngMom*AngMom/(m*m)
c2 = AngMom*AngMom/m
rmin = (AngMom*AngMom/k/m)**0.25
# Initial conditions
r0 = rmin
v0 = 0.0
r[0] = r0
v[0] = v0
E[0] = 0.5*m*v0*v0+0.5*k*r0*r0+0.5*c2/(r0*r0)
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up acceleration
a = -r[i]*omega02+c1/(r[i]**3)
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
anew = -r[i+1]*omega02+c1/(r[i+1]**3)
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
E[i+1] = 0.5*m*v[i+1]*v[i+1]+0.5*k*r[i+1]*r[i+1]+0.5*c2/(r[i+1]*r[i+1])
# Plot position as function of time
fig, ax = plt.subplots(2,1)
ax[0].set_xlabel('time')
ax[0].set_ylabel('radius')
ax[0].plot(t,r)
ax[1].set_xlabel('time')
ax[1].set_ylabel('Energy')
ax[1].plot(t,E)
save_fig("RadialHOVV")
plt.show()
```
## Stability of Orbits
The effective force can be extracted from the effective potential, $V_{\rm eff}$. Beginning from the equations of motion, Eq. ([1](#eq:radialeqofmotion)), for $r$,
$$
\begin{eqnarray}
m\ddot{r}&=&F+\frac{L^2}{mr^3}\\
\nonumber
&=&F_{\rm eff}\\
\nonumber
&=&-\partial_rV_{\rm eff},\\
\nonumber
F_{\rm eff}&=&-\partial_r\left[V(r)+(L^2/2mr^2)\right].
\end{eqnarray}
$$
For a circular orbit, the radius must be fixed as a function of time,
so one must be at a maximum or a minimum of the effective
potential. However, if one is at a maximum of the effective potential
the radius will be unstable. For the attractive Coulomb force the
effective potential will be dominated by the $-\alpha/r$ term for
large $r$ because the centrifugal part falls off more quickly, $\sim
1/r^2$. At low $r$ the centrifugal piece wins and the effective
potential is repulsive. Thus, the potential must have a minimum
somewhere with negative potential. The circular orbits are then stable
to perturbation.
The effective potential is sketched for two cases, a $1/r$ attractive
potential and a $1/r^3$ attractive potential. The $1/r$ case has a
stable minimum, whereas the circular orbit in the $1/r^3$ case is
unstable.
If one considers a potential that falls as $1/r^3$, the situation is
reversed and the point where $\partial_rV$ disappears will be a local
maximum rather than a local minimum. **Fig to come here with code**
The repulsive centrifugal piece dominates at large $r$ and the attractive
Coulomb piece wins out at small $r$. The circular orbit is then at a
maximum of the effective potential and the orbits are unstable. It is
the clear that for potentials that fall as $r^n$, that one must have
$n>-2$ for the orbits to be stable.
Consider a potential $V(r)=\beta r$. For a particle of mass $m$ with
angular momentum $L$, find the angular frequency of a circular
orbit. Then find the angular frequency for small radial perturbations.
For the circular orbit you search for the position $r_{\rm min}$ where the effective potential is minimized,
$$
\begin{eqnarray*}
\partial_r\left\{\beta r+\frac{L^2}{2mr^2}\right\}&=&0,\\
\beta&=&\frac{L^2}{mr_{\rm min}^3},\\
r_{\rm min}&=&\left(\frac{L^2}{\beta m}\right)^{1/3},\\
\dot{\phi}&=&\frac{L}{mr_{\rm min}^2}=\frac{\beta^{2/3}}{(mL)^{1/3}}
\end{eqnarray*}
$$
Now, we can find the angular frequency of small perturbations about the circular orbit. To do this we find the effective spring constant for the effective potential,
$$
\begin{eqnarray*}
k_{\rm eff}&=&\partial_r^2 \left.V_{\rm eff}\right|_{r_{\rm min}}\\
&=&\frac{3L^2}{mr_{\rm min}^4},\\
\omega&=&\sqrt{\frac{k_{\rm eff}}{m}}\\
&=&\frac{\beta^{2/3}}{(mL)^{1/3}}\sqrt{3}.
\end{eqnarray*}
$$
If the two frequencies, $\dot{\phi}$ and $\omega$, differ by an
integer factor, the orbit's trajectory will repeat itself each time
around. This is the case for the inverse-square force,
$\omega=\dot{\phi}$, and for the harmonic oscillator,
$\omega=2\dot{\phi}$. In this case, $\omega=\sqrt{3}\dot{\phi}$,
and the angles at which the maxima and minima occur change with each
orbit.
### Code example with gravitional force
The code example here is meant to illustrate how we can make a plot of the final orbit. We solve the equations in polar coordinates (the example here uses the minimum of the potential as initial value) and then we transform back to cartesian coordinates and plot $x$ versus $y$. We see that we get a perfect circle when we place ourselves at the minimum of the potential energy, as expected.
```
# Simple Gravitational Force -alpha/r
DeltaT = 0.01
#set up arrays
tfinal = 8.0
n = ceil(tfinal/DeltaT)
# set up arrays for t, v and r
t = np.zeros(n)
v = np.zeros(n)
r = np.zeros(n)
phi = np.zeros(n)
x = np.zeros(n)
y = np.zeros(n)
# Constants of the model, setting all variables to one for simplicity
alpha = 1.0
AngMom = 1.0 # The angular momentum
m = 1.0 # scale mass to one
c1 = AngMom*AngMom/(m*m)
c2 = AngMom*AngMom/m
rmin = (AngMom*AngMom/m/alpha)
# Initial conditions, place yourself at the potential min
r0 = rmin
v0 = 0.0 # starts at rest
r[0] = r0
v[0] = v0
phi[0] = 0.0
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up acceleration
a = -alpha/(r[i]**2)+c1/(r[i]**3)
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3)
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
phi[i+1] = t[i+1]*c2/(r0**2)
# Find cartesian coordinates for easy plot
x = r*np.cos(phi)
y = r*np.sin(phi)
fig, ax = plt.subplots(3,1)
ax[0].set_xlabel('time')
ax[0].set_ylabel('radius')
ax[0].plot(t,r)
ax[1].set_xlabel('time')
ax[1].set_ylabel('Angle $\cos{\phi}$')
ax[1].plot(t,np.cos(phi))
ax[2].set_ylabel('y')
ax[2].set_xlabel('x')
ax[2].plot(x,y)
save_fig("Phasespace")
plt.show()
```
Try to change the initial value for $r$ and see what kind of orbits you get.
In order to test different energies, it can be useful to look at the plot of the effective potential discussed above.
However, for orbits different from a circle the above code would need modifications in order to allow us to display say an ellipse. For the latter, it is much easier to run our code in cartesian coordinates, as done here. In this code we test also energy conservation and see that it is conserved to numerical precision. The code here is a simple extension of the code we developed for homework 4.
```
# Common imports
import numpy as np
import pandas as pd
from math import *
import matplotlib.pyplot as plt
DeltaT = 0.01
#set up arrays
tfinal = 10.0
n = ceil(tfinal/DeltaT)
# set up arrays
t = np.zeros(n)
v = np.zeros((n,2))
r = np.zeros((n,2))
E = np.zeros(n)
# Constants of the model
m = 1.0 # mass, you can change these
alpha = 1.0
# Initial conditions as compact 2-dimensional arrays
x0 = 0.5; y0= 0.
r0 = np.array([x0,y0])
v0 = np.array([0.0,1.0])
r[0] = r0
v[0] = v0
rabs = sqrt(sum(r[0]*r[0]))
E[0] = 0.5*m*(v[0,0]**2+v[0,1]**2)-alpha/rabs
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up the acceleration
rabs = sqrt(sum(r[i]*r[i]))
a = -alpha*r[i]/(rabs**3)
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
rabs = sqrt(sum(r[i+1]*r[i+1]))
anew = -alpha*r[i+1]/(rabs**3)
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
E[i+1] = 0.5*m*(v[i+1,0]**2+v[i+1,1]**2)-alpha/rabs
t[i+1] = t[i] + DeltaT
# Plot position as function of time
fig, ax = plt.subplots(3,1)
ax[0].set_ylabel('y')
ax[0].set_xlabel('x')
ax[0].plot(r[:,0],r[:,1])
ax[1].set_xlabel('time')
ax[1].set_ylabel('y position')
ax[1].plot(t,r[:,0])
ax[2].set_xlabel('time')
ax[2].set_ylabel('y position')
ax[2].plot(t,r[:,1])
fig.tight_layout()
save_fig("2DimGravity")
plt.show()
print(E)
```
## Scattering and Cross Sections
Scattering experiments don't measure entire trajectories. For elastic
collisions, they measure the distribution of final scattering angles
at best. Most experiments use targets thin enough so that the number
of scatterings is typically zero or one. The cross section, $\sigma$,
describes the cross-sectional area for particles to scatter with an
individual target atom or nucleus. Cross section measurements form the
basis for MANY fields of physics. BThe cross section, and the
differential cross section, encapsulates everything measurable for a
collision where all that is measured is the final state, e.g. the
outgoing particle had momentum $\boldsymbol{p}_f$. y studying cross sections,
one can infer information about the potential interaction between the
two particles. Inferring, or constraining, the potential from the
cross section is a classic {\it inverse} problem. Collisions are
either elastic or inelastic. Elastic collisions are those for which
the two bodies are in the same internal state before and after the
collision. If the collision excites one of the participants into a
higher state, or transforms the particles into different species, or
creates additional particles, the collision is inelastic. Here, we
consider only elastic collisions.
For Coulomb forces, the cross section is infinite because the range of
the Coulomb force is infinite, but for interactions such as the strong
interaction in nuclear or particle physics, there is no long-range
force and cross-sections are finite. Even for Coulomb forces, the part
of the cross section that corresponds to a specific scattering angle,
$d\sigma/d\Omega$, which is a function of the scattering angle
$\phi_s$ is still finite.
If a particle travels through a thin target, the chance the particle
scatters is $P_{\rm scatt}=\sigma dN/dA$, where $dN/dA$ is the number
of scattering centers per area the particle encounters. If the density
of the target is $\rho$ particles per volume, and if the thickness of
the target is $t$, the areal density (number of target scatterers per
area) is $dN/dA=\rho t$. Because one wishes to quantify the collisions
independently of the target, experimentalists measure scattering
probabilities, then divide by the areal density to obtain
cross-sections,
$$
\begin{eqnarray}
\sigma=\frac{P_{\rm scatt}}{dN/dA}.
\end{eqnarray}
$$
Instead of merely stating that a particle collided, one can measure
the probability the particle scattered by a given angle. The
scattering angle $\phi_s$ is defined so that at zero the particle is
unscattered and at $\phi_s=\pi$ the particle is scattered directly
backward. Scattering angles are often described in the center-of-mass
frame, but that is a detail we will neglect for this first discussion,
where we will consider the scattering of particles moving classically
under the influence of fixed potentials $U(\boldsymbol{r})$. Because the
distribution of scattering angles can be measured, one expresses the
differential cross section,
<!-- Equation labels as ordinary links -->
<div id="_auto5"></div>
$$
\begin{equation}
\frac{d^2\sigma}{d\cos\phi_s~d\phi}.
\label{_auto5} \tag{10}
\end{equation}
$$
Usually, the literature expresses differential cross sections as
<!-- Equation labels as ordinary links -->
<div id="_auto6"></div>
$$
\begin{equation}
d\sigma/d\Omega=\frac{d\sigma}{d\cos\phi d\phi}=\frac{1}{2\pi}\frac{d\sigma}{d\cos\phi},
\label{_auto6} \tag{11}
\end{equation}
$$
where the last equivalency is true when the scattering does not depend
on the azimuthal angle $\phi$, as is the case for spherically
symmetric potentials.
The differential solid angle $d\Omega$ can be thought of as the area
subtended by a measurement, $dA_d$, divided by $r^2$, where $r$ is the
distance to the detector,
$$
\begin{eqnarray}
dA_d=r^2 d\Omega.
\end{eqnarray}
$$
With this definition $d\sigma/d\Omega$ is independent of the distance
from which one places the detector, or the size of the detector (as
long as it is small).
Differential scattering cross sections are calculated by assuming a
random distribution of impact parameters $b$. These represent the
distance in the $xy$ plane for particles moving in the $z$ direction
relative to the scattering center. An impact parameter $b=0$ refers to
being aimed directly at the target's center. The impact parameter
describes the transverse distance from the $z=0$ axis for the
trajectory when it is still far away from the scattering center and
has not yet passed it. The differential cross section can be expressed
in terms of the impact parameter,
<!-- Equation labels as ordinary links -->
<div id="_auto7"></div>
$$
\begin{equation}
d\sigma=2\pi bdb,
\label{_auto7} \tag{12}
\end{equation}
$$
which is the area of a thin ring of radius $b$ and thickness $db$. In
classical physics, one can calculate the trajectory given the incoming
kinetic energy $E$ and the impact parameter if one knows the mass and
potential. From the trajectory, one then finds the scattering angle
$\phi_s(b)$. The differential cross section is then
<!-- Equation labels as ordinary links -->
<div id="_auto8"></div>
$$
\begin{equation}
\frac{d\sigma}{d\Omega}=\frac{1}{2\pi}\frac{d\sigma}{d\cos\phi_s}=b\frac{db}{d\cos\phi_s}=\frac{b}{(d/db)\cos\phi_s(b)}.
\label{_auto8} \tag{13}
\end{equation}
$$
Typically, one would calculate $\cos\phi_s$ and $(d/db)\cos\phi_s$
as functions of $b$. This is sufficient to plot the differential cross
section as a function of $\phi_s$.
The total cross section is
<!-- Equation labels as ordinary links -->
<div id="_auto9"></div>
$$
\begin{equation}
\sigma_{\rm tot}=\int d\Omega\frac{d\sigma}{d\Omega}=2\pi\int d\cos\phi_s~\frac{d\sigma}{d\Omega}.
\label{_auto9} \tag{14}
\end{equation}
$$
Even if the total cross section is infinite, e.g. Coulomb forces, one
can still have a finite differential cross section as we will see
later on.
An asteroid of mass $m$ and kinetic energy $E$ approaches a planet of
radius $R$ and mass $M$. What is the cross section for the asteroid to
impact the planet?
### Solution
Calculate the maximum impact parameter, $b_{\rm max}$, for which the asteroid will hit the planet. The total cross section for impact is $\sigma_{\rm impact}=\pi b_{\rm max}^2$. The maximum cross-section can be found with the help of angular momentum conservation. The asteroid's incoming momentum is $p_0=\sqrt{2mE}$ and the angular momentum is $L=p_0b$. If the asteroid just grazes the planet, it is moving with zero radial kinetic energy at impact. Combining energy and angular momentum conservation and having $p_f$ refer to the momentum of the asteroid at a distance $R$,
$$
\begin{eqnarray*}
\frac{p_f^2}{2m}-\frac{GMm}{R}&=&E,\\
p_fR&=&p_0b_{\rm max},
\end{eqnarray*}
$$
allows one to solve for $b_{\rm max}$,
$$
\begin{eqnarray*}
b_{\rm max}&=&R\frac{p_f}{p_0}\\
&=&R\frac{\sqrt{2m(E+GMm/R)}}{\sqrt{2mE}}\\
\sigma_{\rm impact}&=&\pi R^2\frac{E+GMm/R}{E}.
\end{eqnarray*}
$$
## Rutherford Scattering
This refers to the calculation of $d\sigma/d\Omega$ due to an inverse
square force, $F_{12}=\pm\alpha/r^2$ for repulsive/attractive
interaction. Rutherford compared the scattering of $\alpha$ particles
($^4$He nuclei) off of a nucleus and found the scattering angle at
which the formula began to fail. This corresponded to the impact
parameter for which the trajectories would strike the nucleus. This
provided the first measure of the size of the atomic nucleus. At the
time, the distribution of the positive charge (the protons) was
considered to be just as spread out amongst the atomic volume as the
electrons. After Rutherford's experiment, it was clear that the radius
of the nucleus tended to be roughly 4 orders of magnitude smaller than
that of the atom, which is less than the size of a football relative
to Spartan Stadium.
The incoming and outgoing angles of the trajectory are at
$\pm\phi'$. They are related to the scattering angle by
$2\phi'=\pi+\phi_s$.
In order to calculate differential cross section, we must find how the
impact parameter is related to the scattering angle. This requires
analysis of the trajectory. We consider our previous expression for
the trajectory where we derived the elliptic form for the trajectory,
Eq. ([9](#eq:Ctrajectory)). For that case we considered an attractive
force with the particle's energy being negative, i.e. it was
bound. However, the same form will work for positive energy, and
repulsive forces can be considered by simple flipping the sign of
$\alpha$. For positive energies, the trajectories will be hyperbolas,
rather than ellipses, with the asymptotes of the trajectories
representing the directions of the incoming and outgoing
tracks. Rewriting Eq. ([9](#eq:Ctrajectory)),
<!-- Equation labels as ordinary links -->
<div id="eq:ruthtraj"></div>
$$
\begin{equation}\label{eq:ruthtraj} \tag{15}
r=\frac{1}{\frac{m\alpha}{L^2}+A\cos\phi}.
\end{equation}
$$
Once $A$ is large enough, which will happen when the energy is
positive, the denominator will become negative for a range of
$\phi$. This is because the scattered particle will never reach
certain angles. The asymptotic angles $\phi'$ are those for which
the denominator goes to zero,
<!-- Equation labels as ordinary links -->
<div id="_auto10"></div>
$$
\begin{equation}
\cos\phi'=-\frac{m\alpha}{AL^2}.
\label{_auto10} \tag{16}
\end{equation}
$$
The trajectory's point of closest approach is at $\phi=0$ and the
two angles $\phi'$, which have this value of $\cos\phi'$, are the
angles of the incoming and outgoing particles. From
Fig (**to come**), one can see that the scattering angle
$\phi_s$ is given by,
<!-- Equation labels as ordinary links -->
<div id="eq:sthetover2"></div>
$$
\begin{eqnarray}
\label{eq:sthetover2} \tag{17}
2\phi'-\pi&=&\phi_s,~~~\phi'=\frac{\pi}{2}+\frac{\phi_s}{2},\\
\nonumber
\sin(\phi_s/2)&=&-\cos\phi'\\
\nonumber
&=&\frac{m\alpha}{AL^2}.
\end{eqnarray}
$$
Now that we have $\phi_s$ in terms of $m,\alpha,L$ and $A$, we wish
to re-express $L$ and $A$ in terms of the impact parameter $b$ and the
energy $E$. This will set us up to calculate the differential cross
section, which requires knowing $db/d\phi_s$. It is easy to write
the angular momentum as
<!-- Equation labels as ordinary links -->
<div id="_auto11"></div>
$$
\begin{equation}
L^2=p_0^2b^2=2mEb^2.
\label{_auto11} \tag{18}
\end{equation}
$$
Finding $A$ is more complicated. To accomplish this we realize that
the point of closest approach occurs at $\phi=0$, so from
Eq. ([15](#eq:ruthtraj))
<!-- Equation labels as ordinary links -->
<div id="eq:rminofA"></div>
$$
\begin{eqnarray}
\label{eq:rminofA} \tag{19}
\frac{1}{r_{\rm min}}&=&\frac{m\alpha}{L^2}+A,\\
\nonumber
A&=&\frac{1}{r_{\rm min}}-\frac{m\alpha}{L^2}.
\end{eqnarray}
$$
Next, $r_{\rm min}$ can be found in terms of the energy because at the
point of closest approach the kinetic energy is due purely to the
motion perpendicular to $\hat{r}$ and
<!-- Equation labels as ordinary links -->
<div id="_auto12"></div>
$$
\begin{equation}
E=-\frac{\alpha}{r_{\rm min}}+\frac{L^2}{2mr_{\rm min}^2}.
\label{_auto12} \tag{20}
\end{equation}
$$
One can solve the quadratic equation for $1/r_{\rm min}$,
<!-- Equation labels as ordinary links -->
<div id="_auto13"></div>
$$
\begin{equation}
\frac{1}{r_{\rm min}}=\frac{m\alpha}{L^2}+\sqrt{(m\alpha/L^2)^2+2mE/L^2}.
\label{_auto13} \tag{21}
\end{equation}
$$
We can plug the expression for $r_{\rm min}$ into the expression for $A$, Eq. ([19](#eq:rminofA)),
<!-- Equation labels as ordinary links -->
<div id="_auto14"></div>
$$
\begin{equation}
A=\sqrt{(m\alpha/L^2)^2+2mE/L^2}=\sqrt{(\alpha^2/(4E^2b^4)+1/b^2}
\label{_auto14} \tag{22}
\end{equation}
$$
Finally, we insert the expression for $A$ into that for the scattering angle, Eq. ([17](#eq:sthetover2)),
<!-- Equation labels as ordinary links -->
<div id="eq:scattangle"></div>
$$
\begin{eqnarray}
\label{eq:scattangle} \tag{23}
\sin(\phi_s/2)&=&\frac{m\alpha}{AL^2}\\
\nonumber
&=&\frac{a}{\sqrt{a^2+b^2}}, ~~a\equiv \frac{\alpha}{2E}
\end{eqnarray}
$$
The differential cross section can now be found by differentiating the
expression for $\phi_s$ with $b$,
<!-- Equation labels as ordinary links -->
<div id="eq:rutherford"></div>
$$
\begin{eqnarray}
\label{eq:rutherford} \tag{24}
\frac{1}{2}\cos(\phi_s/2)d\phi_s&=&\frac{ab~db}{(a^2+b^2)^{3/2}}=\frac{bdb}{a^2}\sin^3(\phi_s/2),\\
\nonumber
d\sigma&=&2\pi bdb=\frac{\pi a^2}{\sin^3(\phi_s/2)}\cos(\phi_s/2)d\phi_s\\
\nonumber
&=&\frac{\pi a^2}{2\sin^4(\phi_s/2)}\sin\phi_s d\phi_s\\
\nonumber
\frac{d\sigma}{d\cos\phi_s}&=&\frac{\pi a^2}{2\sin^4(\phi_s/2)},\\
\nonumber
\frac{d\sigma}{d\Omega}&=&\frac{a^2}{4\sin^4(\phi_s/2)}.
\end{eqnarray}
$$
where $a= \alpha/2E$. This the Rutherford formula for the differential
cross section. It diverges as $\phi_s\rightarrow 0$ because
scatterings with arbitrarily large impact parameters still scatter to
arbitrarily small scattering angles. The expression for
$d\sigma/d\Omega$ is the same whether the interaction is positive or
negative.
Consider a particle of mass $m$ and charge $z$ with kinetic energy $E$
(Let it be the center-of-mass energy) incident on a heavy nucleus of
mass $M$ and charge $Z$ and radius $R$. Find the angle at which the
Rutherford scattering formula breaks down.
### Solution
Let $\alpha=Zze^2/(4\pi\epsilon_0)$. The scattering angle in Eq. ([23](#eq:scattangle)) is
$$
\sin(\phi_s/2)=\frac{a}{\sqrt{a^2+b^2}}, ~~a\equiv \frac{\alpha}{2E}.
$$
The impact parameter $b$ for which the point of closest approach
equals $R$ can be found by using angular momentum conservation,
$$
\begin{eqnarray*}
p_0b&=&b\sqrt{2mE}=Rp_f=R\sqrt{2m(E-\alpha/R)},\\
b&=&R\frac{\sqrt{2m(E-\alpha/R)}}{\sqrt{2mE}}\\
&=&R\sqrt{1-\frac{\alpha}{ER}}.
\end{eqnarray*}
$$
Putting these together
$$
\phi_s=2\sin^{-1}\left\{
\frac{a}{\sqrt{a^2+R^2(1-\alpha/(RE))}}
\right\},~~~a=\frac{\alpha}{2E}.
$$
It was from this departure of the experimentally measured
$d\sigma/d\Omega$ from the Rutherford formula that allowed Rutherford
to infer the radius of the gold nucleus, $R$.
Just like electrodynamics, one can define "fields", which for a small
additional mass $m$ are the force per mass and the additional
potential energy per mass. The {\it gravitational field} related to
the force has dimensions of force per mass, or acceleration, and can
be labeled $\boldsymbol{g}(\boldsymbol{r})$. The potential energy per mass has
dimensions of energy per mass. This is analogous to the
electromagnetic potential, which is the potential energy per charge,
and the electric field which is the force per charge.
Because the field $\boldsymbol{g}$ obeys the same inverse square law for a
point mass as the electric field does for a point charge, the
gravitational field also satisfies a version of Gauss's law,
<!-- Equation labels as ordinary links -->
<div id="eq:GravGauss"></div>
$$
\begin{equation}
\label{eq:GravGauss} \tag{25}
\oint d\boldsymbol{A}\cdot\boldsymbol{g}=-4\pi GM_{\rm inside}.
\end{equation}
$$
Here, $M_{\rm inside}$ is the net mass inside a closed area.
Gauss's law can be understood by considering a nozzle that sprays
paint in all directions uniformly from a point source. Let $B$ be the
number of gallons per minute of paint leaving the nozzle. If the
nozzle is at the center of a sphere of radius $r$, the paint per
square meter per minute that is deposited on some part of the sphere
is
$$
\begin{eqnarray}
F(r)&=&\frac{B}{4\pi r^2}.
\end{eqnarray}
$$
Now, let $F$ also be assigned a direction, so that it becomes a vector
pointing along the direction of the flying paint. For any surface that
surrounds the nozzle, not necessarily a sphere, one can state that
<!-- Equation labels as ordinary links -->
<div id="eq:paint"></div>
$$
\begin{eqnarray}
\label{eq:paint} \tag{26}
\oint \boldsymbol{dA}\cdot\boldsymbol{F}&=&B,
\end{eqnarray}
$$
regardless of the shape of the surface. This follows because the rate
at which paint is deposited on the surface should equal the rate at
which it leaves the nozzle. The dot product ensures that only the
component of $\boldsymbol{F}$ into the surface contributes to the deposition
of paint. Similarly, if $\boldsymbol{F}$ is any radial inverse-square forces,
that falls as $B/(4\pi r^2)$, then one can apply
Eq. ([26](#eq:paint)). For gravitational fields, $B/(4\pi)$ is replaced
by $GM$, and one quickly "derives" Gauss's law for gravity,
Eq. ([25](#eq:GravGauss)).
Consider Earth to have its mass $M$ uniformly distributed in a sphere
of radius $R$. Find the magnitude of the gravitational acceleration as
a function of the radius $r$ in terms of the acceleration of gravity
at the surface $g(R)$. Assume $r<R$, i.e. you are inside the surface.
{\bf Solution}: Take the ratio of Eq. ([25](#eq:GravGauss)) for two radii, $R$ and $r<R$,
$$
\begin{eqnarray*}
\frac{4\pi r^2 g(r)}{4\pi R^2 g(R)}&=&\frac{4\pi GM_{\rm inside~r}}{4\pi GM_{\rm inside~R}}\\
\nonumber
&=&\frac{r^3}{R^3}\\
\nonumber
g(r)&=&g(R)\frac{r}{R}~.
\end{eqnarray*}
$$
The potential energy per mass is similar conceptually to the voltage, or electric potential energy per charge, that was studied in electromagnetism, if $V\equiv U/m$, $\boldsymbol{g}=-\nabla V$.
## Tidal Forces
Consider a spherical planet of radius $r$ a distance $D$ from another
body of mass $M$. The magnitude of the force due to $M$ on an small
object of mass $\delta m$ on surface of the planet can be calculated
by performing a Taylor expansion about the center of the spherical
planet.
<!-- Equation labels as ordinary links -->
<div id="_auto15"></div>
$$
\begin{equation}
F=-\frac{GM\delta m}{D^2}+2\frac{GM\delta m}{D^3}\Delta D+\cdots
\label{_auto15} \tag{27}
\end{equation}
$$
If the $z$ direction points toward the large object, $\Delta D$ can be
referred to as $z$. In the accelerating frame of an observer at the
center of the planet,
<!-- Equation labels as ordinary links -->
<div id="_auto16"></div>
$$
\begin{equation}
\delta m\frac{d^2 z}{dt^2}=F-\delta ma'+{\rm other~forces~acting~on~} \delta m,
\label{_auto16} \tag{28}
\end{equation}
$$
where $a'$ is the acceleration of the observer. Because $\delta ma'$
equals the gravitational force on $\delta m$ if it were located at the
planet's center, one can write
<!-- Equation labels as ordinary links -->
<div id="_auto17"></div>
$$
\begin{equation}
m\frac{d^2z}{dt^2}=2\frac{GM\delta m}{D^3}z+{\rm other~forces~acting~on~}\delta m.
\label{_auto17} \tag{29}
\end{equation}
$$
Here the other forces could represent the forces acting on $\delta m$
from the spherical planet such as the gravitational force or the
contact force with the surface. If $\phi$ is the angle w.r.t. the
$z$ axis, the effective force acting on $\delta m$ is
<!-- Equation labels as ordinary links -->
<div id="_auto18"></div>
$$
\begin{equation}
F_{\rm eff}\approx 2\frac{GM\delta m}{D^3}r\cos\phi\hat{z}+{\rm other~forces~acting~on~}\delta m.
\label{_auto18} \tag{30}
\end{equation}
$$
This first force is the "tidal" force. It pulls objects outward from the center of the object. If the object were covered with water, it would distort the objects shape so that the shape would be elliptical, stretched out along the axis pointing toward the large mass $M$. The force is always along (either parallel or antiparallel to) the $\hat{z}$ direction.
Consider the Earth to be a sphere of radius $R$ covered with water,
with the gravitational acceleration at the surface noted by $g$. Now
assume that a distant body provides an additional constant
gravitational acceleration $\boldsymbol{a}$ pointed along the $z$ axis. Find
the distortion of the radius as a function of $\phi$. Ignore
planetary rotation and assume $a<<g$.
{\bf Solution}: Because Earth would then accelerate with $a$, the
field $a$ would seem invisible in the accelerating frame. A tidal
force would only appear if $a$ depended on position, i.e. $\nabla
\boldsymbol{a}\ne 0$.
Now consider that the field is no longer constant, but that instead $a=-kz$ with $|kR|<<g$.
{\bf Solution}: The surface of the planet needs to be at constant
potential (if the planet is not accelerating). The force per mass,
$-kz$ is like a spring, and the potential per mass is
$kz^2/2$. Otherwise water would move to a point of lower
potential. Thus, the potential energy for a sample mass $\delta m$ is
$$
\begin{eqnarray*}
V(R)+\delta m gh(\phi)-\frac{\delta m}{2}kr^2\cos^2\phi={\rm Constant}\\
V(R)+\delta mgh(\phi)-\frac{\delta m}{2}kR^2\cos^2\phi-\delta m kRh(\phi)\cos^2\phi-\frac{\delta m}{2}kh^2(\phi)\cos^2\phi={\rm Constant}.
\end{eqnarray*}
$$
Here, the potential due to the external field is $(1/2)kz^2$ so that $-\nabla U=-kz$. One now needs to solve for $h(\phi)$. Absorbing all the constant terms from both sides of the equation into one constant $C$, and because both $h$ and $kR$ are small, we can through away terms of order $h^2$ or $kRh$. This gives
$$
\begin{eqnarray*}
gh(\phi)-\frac{1}{2}kR^2\cos^2\phi&=&C,\\
h(\phi)&=&\frac{C}{g}+\frac{1}{2g}kR^2\cos^2\phi,\\
h(\phi)&=&\frac{1}{2g}kR^2(\cos^2\phi-1/3).
\end{eqnarray*}
$$
The term with the factor of $1/3$ replaced the constant and was chosen so that the average height of the water would be zero.
The Sun's mass is $27\times 10^6$ the Moon's mass, but the Sun is 390 times further away from Earth as the Sun. What is ratio of the tidal force of the Sun to that of the Moon.
{\bf Solution}: The gravitational force due to an object $M$ a distance $D$ away goes as $M/D^2$, but the tidal force is only the difference of that force over a distance $R$,
$$
F_{\rm tidal}\propto \frac{M}{D^3}R.
$$
Therefore the ratio of force is
$$
\begin{eqnarray*}
\frac{F_{\rm Sun's~tidal~force}}{F_{\rm Moon's~tidal~force}}
&=&\frac{M_{\rm sun}/D_{\rm sun}^3}{M_{\rm moon}/D_{\rm moon}^3}\\
&=&\frac{27\times 10^6}{390^3}=0.46.
\end{eqnarray*}
$$
The Moon more strongly affects tides than the Sun.
## Exercises
### The Earth-Sun System
We start with a simpler case first, the Earth-Sun system in two dimensions only. The gravitational force $F_G$ on the earth from the sun is
$$
\boldsymbol{F}_G=-\frac{GM_{\odot}M_E}{r^3}\boldsymbol{r},
$$
where $G$ is the gravitational constant,
$$
M_E=6\times 10^{24}\mathrm{Kg},
$$
the mass of Earth,
$$
M_{\odot}=2\times 10^{30}\mathrm{Kg},
$$
the mass of the Sun and
$$
r=1.5\times 10^{11}\mathrm{m},
$$
is the distance between Earth and the Sun. The latter defines what we call an astronomical unit **AU**.
From Newton's second law we have then for the $x$ direction
$$
\frac{d^2x}{dt^2}=-\frac{F_{x}}{M_E},
$$
and
$$
\frac{d^2y}{dt^2}=-\frac{F_{y}}{M_E},
$$
for the $y$ direction.
Here we will use that $x=r\cos{(\theta)}$, $y=r\sin{(\theta)}$ and
$$
r = \sqrt{x^2+y^2}.
$$
We can rewrite these equations
$$
F_{x}=-\frac{GM_{\odot}M_E}{r^2}\cos{(\theta)}=-\frac{GM_{\odot}M_E}{r^3}x,
$$
and
$$
F_{y}=-\frac{GM_{\odot}M_E}{r^2}\sin{(\theta)}=-\frac{GM_{\odot}M_E}{r^3}y,
$$
as four first-order coupled differential equations
$$
\frac{dv_x}{dt}=-\frac{GM_{\odot}}{r^3}x,
$$
and
$$
\frac{dx}{dt}=v_x,
$$
and
$$
\frac{dv_y}{dt}=-\frac{GM_{\odot}}{r^3}y,
$$
and
$$
\frac{dy}{dt}=v_y.
$$
The four coupled differential equations
$$
\frac{dv_x}{dt}=-\frac{GM_{\odot}}{r^3}x,
$$
and
$$
\frac{dx}{dt}=v_x,
$$
and
$$
\frac{dv_y}{dt}=-\frac{GM_{\odot}}{r^3}y,
$$
and
$$
\frac{dy}{dt}=v_y,
$$
can be turned into dimensionless equations or we can introduce astronomical units with $1$ AU = $1.5\times 10^{11}$.
Using the equations from circular motion (with $r =1\mathrm{AU}$)
$$
\frac{M_E v^2}{r} = F = \frac{GM_{\odot}M_E}{r^2},
$$
we have
$$
GM_{\odot}=v^2r,
$$
and using that the velocity of Earth (assuming circular motion) is
$v = 2\pi r/\mathrm{yr}=2\pi\mathrm{AU}/\mathrm{yr}$, we have
$$
GM_{\odot}= v^2r = 4\pi^2 \frac{(\mathrm{AU})^3}{\mathrm{yr}^2}.
$$
The four coupled differential equations can then be discretized using Euler's method as (with step length $h$)
$$
v_{x,i+1}=v_{x,i}-h\frac{4\pi^2}{r_i^3}x_i,
$$
and
$$
x_{i+1}=x_i+hv_{x,i},
$$
and
$$
v_{y,i+1}=v_{y,i}-h\frac{4\pi^2}{r_i^3}y_i,
$$
and
$$
y_{i+1}=y_i+hv_{y,i},
$$
The code here implements Euler's method for the Earth-Sun system using a more compact way of representing the vectors. Alternatively, you could have spelled out all the variables $v_x$, $v_y$, $x$ and $y$ as one-dimensional arrays.
```
# Common imports
import numpy as np
import pandas as pd
from math import *
import matplotlib.pyplot as plt
import os
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
DeltaT = 0.01
#set up arrays
tfinal = 10 # in years
n = ceil(tfinal/DeltaT)
# set up arrays for t, a, v, and x
t = np.zeros(n)
v = np.zeros((n,2))
r = np.zeros((n,2))
# Initial conditions as compact 2-dimensional arrays
r0 = np.array([1.0,0.0])
v0 = np.array([0.0,2*pi])
r[0] = r0
v[0] = v0
Fourpi2 = 4*pi*pi
# Start integrating using Euler's method
for i in range(n-1):
# Set up the acceleration
# Here you could have defined your own function for this
rabs = sqrt(sum(r[i]*r[i]))
a = -Fourpi2*r[i]/(rabs**3)
# update velocity, time and position using Euler's forward method
v[i+1] = v[i] + DeltaT*a
r[i+1] = r[i] + DeltaT*v[i]
t[i+1] = t[i] + DeltaT
# Plot position as function of time
fig, ax = plt.subplots()
#ax.set_xlim(0, tfinal)
ax.set_xlabel('x[AU]')
ax.set_ylabel('y[AU]')
ax.plot(r[:,0], r[:,1])
fig.tight_layout()
save_fig("EarthSunEuler")
plt.show()
```
We notice here that Euler's method doesn't give a stable orbit with for example $\Delta t =0.01$. It
means that we cannot trust Euler's method. Euler's method does not conserve energy. It is an
example of an integrator which is not
[symplectic](https://en.wikipedia.org/wiki/Symplectic_integrator).
Here we present thus two methods, which with simple changes allow us
to avoid these pitfalls. The simplest possible extension is the
so-called Euler-Cromer method. The changes we need to make to our
code are indeed marginal here. We need simply to replace
```
r[i+1] = r[i] + DeltaT*v[i]
```
in the above code with the velocity at the new time $t_{i+1}$
```
r[i+1] = r[i] + DeltaT*v[i+1]
```
By this simple caveat we get stable orbits. Below we derive the
Euler-Cromer method as well as one of the most utlized algorithms for
solving the above type of problems, the so-called Velocity-Verlet
method.
Let us repeat Euler's method.
We have a differential equation
<!-- Equation labels as ordinary links -->
<div id="_auto19"></div>
$$
\begin{equation}
y'(t_i)=f(t_i,y_i)
\label{_auto19} \tag{31}
\end{equation}
$$
and if we truncate at the first derivative, we have from the Taylor expansion
<!-- Equation labels as ordinary links -->
<div id="eq:euler"></div>
$$
\begin{equation}
y_{i+1}=y(t_i) + (\Delta t) f(t_i,y_i) + O(\Delta t^2), \label{eq:euler} \tag{32}
\end{equation}
$$
which when complemented with $t_{i+1}=t_i+\Delta t$ forms
the algorithm for the well-known Euler method.
Note that at every step we make an approximation error
of the order of $O(\Delta t^2)$, however the total error is the sum over all
steps $N=(b-a)/(\Delta t)$ for $t\in [a,b]$, yielding thus a global error which goes like
$NO(\Delta t^2)\approx O(\Delta t)$.
To make Euler's method more precise we can obviously
decrease $\Delta t$ (increase $N$), but this can lead to loss of numerical precision.
Euler's method is not recommended for precision calculation,
although it is handy to use in order to get a first
view on how a solution may look like.
Euler's method is asymmetric in time, since it uses information about the derivative at the beginning
of the time interval. This means that we evaluate the position at $y_1$ using the velocity
at $v_0$. A simple variation is to determine $x_{n+1}$ using the velocity at
$v_{n+1}$, that is (in a slightly more generalized form)
<!-- Equation labels as ordinary links -->
<div id="_auto20"></div>
$$
\begin{equation}
y_{n+1}=y_{n}+ v_{n+1}+O(\Delta t^2)
\label{_auto20} \tag{33}
\end{equation}
$$
and
<!-- Equation labels as ordinary links -->
<div id="_auto21"></div>
$$
\begin{equation}
v_{n+1}=v_{n}+(\Delta t) a_{n}+O(\Delta t^2).
\label{_auto21} \tag{34}
\end{equation}
$$
The acceleration $a_n$ is a function of $a_n(y_n, v_n, t_n)$ and needs to be evaluated
as well. This is the Euler-Cromer method. It is easy to change the above code and see that with the same
time step we get stable results.
Let us stay with $x$ (position) and $v$ (velocity) as the quantities we are interested in.
We have the Taylor expansion for the position given by
$$
x_{i+1} = x_i+(\Delta t)v_i+\frac{(\Delta t)^2}{2}a_i+O((\Delta t)^3).
$$
The corresponding expansion for the velocity is
$$
v_{i+1} = v_i+(\Delta t)a_i+\frac{(\Delta t)^2}{2}v^{(2)}_i+O((\Delta t)^3).
$$
Via Newton's second law we have normally an analytical expression for the derivative of the velocity, namely
$$
a_i= \frac{d^2 x}{dt^2}\vert_{i}=\frac{d v}{dt}\vert_{i}= \frac{F(x_i,v_i,t_i)}{m}.
$$
If we add to this the corresponding expansion for the derivative of the velocity
$$
v^{(1)}_{i+1} = a_{i+1}= a_i+(\Delta t)v^{(2)}_i+O((\Delta t)^2)=a_i+(\Delta t)v^{(2)}_i+O((\Delta t)^2),
$$
and retain only terms up to the second derivative of the velocity since our error goes as $O(h^3)$, we have
$$
(\Delta t)v^{(2)}_i\approx a_{i+1}-a_i.
$$
We can then rewrite the Taylor expansion for the velocity as
$$
v_{i+1} = v_i+\frac{(\Delta t)}{2}\left( a_{i+1}+a_{i}\right)+O((\Delta t)^3).
$$
Our final equations for the position and the velocity become then
$$
x_{i+1} = x_i+(\Delta t)v_i+\frac{(\Delta t)^2}{2}a_{i}+O((\Delta t)^3),
$$
and
$$
v_{i+1} = v_i+\frac{(\Delta t)}{2}\left(a_{i+1}+a_{i}\right)+O((\Delta t)^3).
$$
Note well that the term $a_{i+1}$ depends on the position at $x_{i+1}$. This means that you need to calculate
the position at the updated time $t_{i+1}$ before the computing the next velocity. Note also that the derivative of the velocity at the time
$t_i$ used in the updating of the position can be reused in the calculation of the velocity update as well.
We can now easily add the Verlet method to our original code as
```
DeltaT = 0.01
#set up arrays
tfinal = 10
n = ceil(tfinal/DeltaT)
# set up arrays for t, a, v, and x
t = np.zeros(n)
v = np.zeros((n,2))
r = np.zeros((n,2))
# Initial conditions as compact 2-dimensional arrays
r0 = np.array([1.0,0.0])
v0 = np.array([0.0,2*pi])
r[0] = r0
v[0] = v0
Fourpi2 = 4*pi*pi
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up forces, air resistance FD, note now that we need the norm of the vecto
# Here you could have defined your own function for this
rabs = sqrt(sum(r[i]*r[i]))
a = -Fourpi2*r[i]/(rabs**3)
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
rabs = sqrt(sum(r[i+1]*r[i+1]))
anew = -4*(pi**2)*r[i+1]/(rabs**3)
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
# Plot position as function of time
fig, ax = plt.subplots()
ax.set_xlabel('x[AU]')
ax.set_ylabel('y[AU]')
ax.plot(r[:,0], r[:,1])
fig.tight_layout()
save_fig("EarthSunVV")
plt.show()
```
You can easily generalize the calculation of the forces by defining a function
which takes in as input the various variables. We leave this as a challenge to you.
Running the above code for various time steps we see that the Velocity-Verlet is fully stable for various time steps.
We can also play around with different initial conditions in order to find the escape velocity from an orbit around the sun with distance one astronomical unit, 1 AU. The theoretical value for the escape velocity, is given by
$$
v = \sqrt{8\pi^2}{r},
$$
and with $r=1$ AU, this means that the escape velocity is $2\pi\sqrt{2}$ AU/yr. To obtain this we required that the kinetic energy of Earth equals the potential energy given by the gravitational force.
Setting
$$
\frac{1}{2}M_{\mathrm{Earth}}v^2=\frac{GM_{\odot}}{r},
$$
and with $GM_{\odot}=4\pi^2$ we obtain the above relation for the velocity. Setting an initial velocity say equal to $9$ in the above code, yields a planet (Earth) which escapes a stable orbit around the sun, as seen by running the code here.
```
DeltaT = 0.01
#set up arrays
tfinal = 100
n = ceil(tfinal/DeltaT)
# set up arrays for t, a, v, and x
t = np.zeros(n)
v = np.zeros((n,2))
r = np.zeros((n,2))
# Initial conditions as compact 2-dimensional arrays
r0 = np.array([1.0,0.0])
# setting initial velocity larger than escape velocity
v0 = np.array([0.0,9.0])
r[0] = r0
v[0] = v0
Fourpi2 = 4*pi*pi
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up forces, air resistance FD, note now that we need the norm of the vecto
# Here you could have defined your own function for this
rabs = sqrt(sum(r[i]*r[i]))
a = -Fourpi2*r[i]/(rabs**3)
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
rabs = sqrt(sum(r[i+1]*r[i+1]))
anew = -4*(pi**2)*r[i+1]/(rabs**3)
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
# Plot position as function of time
fig, ax = plt.subplots()
ax.set_xlabel('x[AU]')
ax.set_ylabel('y[AU]')
ax.plot(r[:,0], r[:,1])
fig.tight_layout()
save_fig("EscapeEarthSunVV")
plt.show()
```
### Testing Energy conservation
The code here implements Euler's method for the Earth-Sun system using
a more compact way of representing the vectors. Alternatively, you
could have spelled out all the variables $v_x$, $v_y$, $x$ and $y$ as
one-dimensional arrays. It tests conservation of potential and
kinetic energy as functions of time, in addition to the total energy,
again as function of time
**Note**: in all codes we have used scaled equations so that the gravitational constant times the mass of the sum is given by $4\pi^2$ and the mass of the earth is set to **one** in the calculations of kinetic and potential energies. Else, we would get very large results.
```
# Common imports
import numpy as np
import pandas as pd
from math import *
import matplotlib.pyplot as plt
import os
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
# Initial values, time step, positions and velocites
DeltaT = 0.0001
#set up arrays
tfinal = 100 # in years
n = ceil(tfinal/DeltaT)
# set up arrays for t, a, v, and x
t = np.zeros(n)
v = np.zeros((n,2))
r = np.zeros((n,2))
# setting up the kinetic, potential and total energy, note only functions of time
EKinetic = np.zeros(n)
EPotential = np.zeros(n)
ETotal = np.zeros(n)
# Initial conditions as compact 2-dimensional arrays
r0 = np.array([1.0,0.0])
v0 = np.array([0.0,2*pi])
r[0] = r0
v[0] = v0
Fourpi2 = 4*pi*pi
# Setting up variables for the calculation of energies
# distance that defines rabs in potential energy
rabs0 = sqrt(sum(r[0]*r[0]))
# Initial kinetic energy. Note that we skip the mass of the Earth here, that is MassEarth=1 in all codes
EKinetic[0] = 0.5*sum(v0*v0)
# Initial potential energy (note negative sign, why?)
EPotential[0] = -4*pi*pi/rabs0
# Initial total energy
ETotal[0] = EPotential[0]+EKinetic[0]
# Start integrating using Euler's method
for i in range(n-1):
# Set up the acceleration
# Here you could have defined your own function for this
rabs = sqrt(sum(r[i]*r[i]))
a = -Fourpi2*r[i]/(rabs**3)
# update Energies, velocity, time and position using Euler's forward method
v[i+1] = v[i] + DeltaT*a
r[i+1] = r[i] + DeltaT*v[i]
t[i+1] = t[i] + DeltaT
EKinetic[i+1] = 0.5*sum(v[i+1]*v[i+1])
EPotential[i+1] = -4*pi*pi/sqrt(sum(r[i+1]*r[i+1]))
ETotal[i+1] = EPotential[i+1]+EKinetic[i+1]
# Plot energies as functions of time
fig, axs = plt.subplots(3, 1)
axs[0].plot(t, EKinetic)
axs[0].set_xlim(0, tfinal)
axs[0].set_ylabel('Kinetic energy')
axs[1].plot(t, EPotential)
axs[1].set_ylabel('Potential Energy')
axs[2].plot(t, ETotal)
axs[2].set_xlabel('Time [yr]')
axs[2].set_ylabel('Total Energy')
fig.tight_layout()
save_fig("EarthSunEuler")
plt.show()
```
We see very clearly that Euler's method does not conserve energy!! Try to reduce the time step $\Delta t$. What do you see?
With the Euler-Cromer method, the only thing we need is to update the
position at a time $t+1$ with the update velocity from the same
time. Thus, the change in the code is extremely simply, and **energy is
suddenly conserved**. Note that the error runs like $O(\Delta t)$ and
this is why we see the larger oscillations. But within this
oscillating energy envelope, we see that the energies swing between a
max and a min value and never exceed these values.
```
# Common imports
import numpy as np
import pandas as pd
from math import *
import matplotlib.pyplot as plt
import os
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
# Initial values, time step, positions and velocites
DeltaT = 0.0001
#set up arrays
tfinal = 100 # in years
n = ceil(tfinal/DeltaT)
# set up arrays for t, a, v, and x
t = np.zeros(n)
v = np.zeros((n,2))
r = np.zeros((n,2))
# setting up the kinetic, potential and total energy, note only functions of time
EKinetic = np.zeros(n)
EPotential = np.zeros(n)
ETotal = np.zeros(n)
# Initial conditions as compact 2-dimensional arrays
r0 = np.array([1.0,0.0])
v0 = np.array([0.0,2*pi])
r[0] = r0
v[0] = v0
Fourpi2 = 4*pi*pi
# Setting up variables for the calculation of energies
# distance that defines rabs in potential energy
rabs0 = sqrt(sum(r[0]*r[0]))
# Initial kinetic energy. Note that we skip the mass of the Earth here, that is MassEarth=1 in all codes
EKinetic[0] = 0.5*sum(v0*v0)
# Initial potential energy
EPotential[0] = -4*pi*pi/rabs0
# Initial total energy
ETotal[0] = EPotential[0]+EKinetic[0]
# Start integrating using Euler's method
for i in range(n-1):
# Set up the acceleration
# Here you could have defined your own function for this
rabs = sqrt(sum(r[i]*r[i]))
a = -Fourpi2*r[i]/(rabs**3)
# update velocity, time and position using Euler's forward method
v[i+1] = v[i] + DeltaT*a
# Only change when we add the Euler-Cromer method
r[i+1] = r[i] + DeltaT*v[i+1]
t[i+1] = t[i] + DeltaT
EKinetic[i+1] = 0.5*sum(v[i+1]*v[i+1])
EPotential[i+1] = -4*pi*pi/sqrt(sum(r[i+1]*r[i+1]))
ETotal[i+1] = EPotential[i+1]+EKinetic[i+1]
# Plot energies as functions of time
fig, axs = plt.subplots(3, 1)
axs[0].plot(t, EKinetic)
axs[0].set_xlim(0, tfinal)
axs[0].set_ylabel('Kinetic energy')
axs[1].plot(t, EPotential)
axs[1].set_ylabel('Potential Energy')
axs[2].plot(t, ETotal)
axs[2].set_xlabel('Time [yr]')
axs[2].set_ylabel('Total Energy')
fig.tight_layout()
save_fig("EarthSunEulerCromer")
plt.show()
```
### Adding the velocity Verlet method
Our final equations for the position and the velocity become then
$$
x_{i+1} = x_i+(\Delta t)v_i+\frac{(\Delta t)^2}{2}a_{i}+O((\Delta t)^3),
$$
and
$$
v_{i+1} = v_i+\frac{(\Delta t)}{2}\left(a_{i+1}+a_{i}\right)+O((\Delta t)^3).
$$
Note well that the term $a_{i+1}$ depends on the position at $x_{i+1}$. This means that you need to calculate
the position at the updated time $t_{i+1}$ before the computing the next velocity. Note also that the derivative of the velocity at the time
$t_i$ used in the updating of the position can be reused in the calculation of the velocity update as well.
We can now easily add the Verlet method to our original code as
```
DeltaT = 0.001
#set up arrays
tfinal = 100
n = ceil(tfinal/DeltaT)
# set up arrays for t, a, v, and x
t = np.zeros(n)
v = np.zeros((n,2))
r = np.zeros((n,2))
# Initial conditions as compact 2-dimensional arrays
r0 = np.array([1.0,0.0])
v0 = np.array([0.0,2*pi])
r[0] = r0
v[0] = v0
Fourpi2 = 4*pi*pi
# setting up the kinetic, potential and total energy, note only functions of time
EKinetic = np.zeros(n)
EPotential = np.zeros(n)
ETotal = np.zeros(n)
# Setting up variables for the calculation of energies
# distance that defines rabs in potential energy
rabs0 = sqrt(sum(r[0]*r[0]))
# Initial kinetic energy. Note that we skip the mass of the Earth here, that is MassEarth=1 in all codes
EKinetic[0] = 0.5*sum(v0*v0)
# Initial potential energy
EPotential[0] = -4*pi*pi/rabs0
# Initial total energy
ETotal[0] = EPotential[0]+EKinetic[0]
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up forces, air resistance FD, note now that we need the norm of the vecto
# Here you could have defined your own function for this
rabs = sqrt(sum(r[i]*r[i]))
a = -Fourpi2*r[i]/(rabs**3)
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
rabs = sqrt(sum(r[i+1]*r[i+1]))
anew = -4*(pi**2)*r[i+1]/(rabs**3)
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
EKinetic[i+1] = 0.5*sum(v[i+1]*v[i+1])
EPotential[i+1] = -4*pi*pi/sqrt(sum(r[i+1]*r[i+1]))
ETotal[i+1] = EPotential[i+1]+EKinetic[i+1]
# Plot energies as functions of time
fig, axs = plt.subplots(3, 1)
axs[0].plot(t, EKinetic)
axs[0].set_xlim(0, tfinal)
axs[0].set_ylabel('Kinetic energy')
axs[1].plot(t, EPotential)
axs[1].set_ylabel('Potential Energy')
axs[2].plot(t, ETotal)
axs[2].set_xlabel('Time [yr]')
axs[2].set_ylabel('Total Energy')
fig.tight_layout()
save_fig("EarthSunVelocityVerlet")
plt.show()
```
And we see that due to the smaller truncation error that energy conservation is improved as a function of time.
Try out different time steps $\Delta t$ and see if the results improve or worsen.
### Exercise: Center-of-Mass and Relative Coordinates and Reference Frames
We define the two-body center-of-mass coordinate and relative coordinate by expressing the trajectories for
$\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ into the center-of-mass coordinate
$\boldsymbol{R}_{\rm cm}$
$$
\boldsymbol{R}_{\rm cm}\equiv\frac{m_1\boldsymbol{r}_1+m_2\boldsymbol{r}_2}{m_1+m_2},
$$
and the relative coordinate
$$
\boldsymbol{r}\equiv\boldsymbol{r}_1-\boldsymbol{r_2}.
$$
Here, we assume the two particles interact only with one another, so $\boldsymbol{F}_{12}=-\boldsymbol{F}_{21}$ (where $\boldsymbol{F}_{ij}$ is the force on $i$ due to $j$.
* 2a (5pt) Show that the equations of motion then become $\ddot{\boldsymbol{R}}_{\rm cm}=0$ and $\mu\ddot{\boldsymbol{r}}=\boldsymbol{F}_{12}$, with the reduced mass $\mu=m_1m_2/(m_1+m_2)$.
The first expression simply states that the center of mass coordinate $\boldsymbol{R}_{\rm cm}$ moves at a fixed velocity. The second expression can be rewritten in terms of the reduced mass $\mu$.
Let us first start with some basic definitions. We have the center of mass coordinate $\boldsymbol{R}$ defined as (for two particles)
$$
\boldsymbol{R}=\frac{m_1\boldsymbol{r}_1+m_2\boldsymbol{r}_2}{M},
$$
where $m_1$ and $m_2$ are the masses of the two objects and $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ their respective positions defined according to a chosen origin. Here $M=m_1+m_2$ is the total mass.
The relative position is defined as
$$
\boldsymbol{r} =\boldsymbol{r}_1-\boldsymbol{r}_2,
$$
and we then define $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative and center of mass positions as
$$
\boldsymbol{r}_1=\boldsymbol{R}+\frac{m_2}{M}\boldsymbol{r},
$$
and
$$
\boldsymbol{r}_2=\boldsymbol{R}-\frac{m_1}{M}\boldsymbol{r},
$$
The total linear momentum is then defined as
$$
\boldsymbol{P}=\sum_{i=1}^Nm_i\frac{\boldsymbol{r}_i}{dt},
$$
where $N=2$ in our case. With the above definition of the center of mass position, we see that we can rewrite the total linear momentum as (multiplying the center of mass position with $M$)
$$
\boldsymbol{P}=M\frac{d\boldsymbol{R}}{dt}=M\dot{\boldsymbol{R}}.
$$
This result is also an answer to a part of exercise 2b, see below.
The net force acting on the system is given by the time derivative of the linear momentum (assuming mass is time independent)
and we have
$$
\boldsymbol{F}^{\mathrm{net}}=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}.
$$
The net force acting on the system is given by the sum of the forces acting on the two object, that is we have
$$
\boldsymbol{F}^{\mathrm{net}}=\boldsymbol{F}_1+\boldsymbol{F}_2=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}.
$$
In our case the forces are given by the internal forces only. The force acting on object $1$ is thus $\boldsymbol{F}_{12}$ and the one acting on object $2$ is $\boldsymbol{F}_{12}$. We have also defined that $\boldsymbol{F}_{12}=-\boldsymbol{F}_{21}$. This means thar we have
$$
\boldsymbol{F}_1+\boldsymbol{F}_2=\boldsymbol{F}_{12}+\boldsymbol{F}_{21}=0=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}},
$$
which is what we wanted to show. The center of mass velocity is thus a constant of the motion. We could also define the so-called center of mass reference frame where we simply set $\boldsymbol{R}=0$.
This has also another important consequence for our forces. If we assume that our force depends only on the positions, it means that the gradient of the potential with respect to the center of mass position is zero, that is
$$
M\ddot{d\boldsymbol{R}}=-\boldsymbol{\nabla}_{\boldsymbol{R}}V =0!
$$
An alternative way is
$$
\begin{eqnarray}
\ddot{\boldsymbol{R}}_{\rm cm}&=&\frac{1}{m_1+m_2}\left\{m_1\ddot{\boldsymbol{r}}_1+m_2\ddot{\boldsymbol{r}}_2\right\}\\
\nonumber
&=&\frac{1}{m_1+m_2}\left\{\boldsymbol{F}_{12}+\boldsymbol{F}_{21}\right\}=0.\\
\ddot{\boldsymbol{r}}&=&\ddot{\boldsymbol{r}}_1-\ddot{\boldsymbol{r}}_2=\left(\frac{\boldsymbol{F}_{12}}{m_1}-\frac{\boldsymbol{F}_{21}}{m_2}\right)\\
\nonumber
&=&\left(\frac{1}{m_1}+\frac{1}{m_2}\right)\boldsymbol{F}_{12}.
\end{eqnarray}
$$
The first expression simply states that the center of mass coordinate
$\boldsymbol{R}_{\rm cm}$ moves at a fixed velocity. The second expression
can be rewritten in terms of the reduced mass $\mu$.
$$
\begin{eqnarray}
\mu \ddot{\boldsymbol{r}}&=&\boldsymbol{F}_{12},\\
\frac{1}{\mu}&=&\frac{1}{m_1}+\frac{1}{m_2},~~~~\mu=\frac{m_1m_2}{m_1+m_2}.
\end{eqnarray}
$$
Thus, one can treat the trajectory as a one-body problem where the
reduced mass is $\mu$, and a second trivial problem for the center of
mass. The reduced mass is especially convenient when one is
considering gravitational problems, as we have seen during the lectures of weeks 11-13.
* 2b (5pt) Show that the linear momenta for the center-of-mass $\boldsymbol{P}$ motion and the relative motion $\boldsymbol{q}$ are given by $\boldsymbol{P}=M\dot{\boldsymbol{R}}_{\rm cm}$ with $M=m_1+m_2$ and $\boldsymbol{q}=\mu\dot{\boldsymbol{r}}$. The linear momentum of the relative motion is defined $\boldsymbol{q} = (m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2)/(m_1+m_2)$.
In 2a we showed, as an intermediate step that the total linear momentum is given by
$$
\boldsymbol{P}=\sum_{i=1}^Nm_i\frac{d\boldsymbol{r}_i}{dt}=M\dot{\boldsymbol{R}}.
$$
For the relative momentum $\boldsymbol{q}$, we have that the time derivative of $\boldsymbol{r}$ is
$$
\dot{\boldsymbol{r}} =\dot{\boldsymbol{r}}_1-\dot{\boldsymbol{r}}_2,
$$
We now also that the momenta $\boldsymbol{p}_1=m_1\dot{\boldsymbol{r}}_1$ and
$\boldsymbol{p}_2=m_2\dot{\boldsymbol{r}}_2$. Using these expressions we can rewrite
$$
\dot{\boldsymbol{r}} =\frac{\boldsymbol{p}_1}{m_1}-\frac{\boldsymbol{p}_2}{m_2},
$$
which we can rewrite as
$$
\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{m_1m_2},
$$
and dividing both sides with $M$ we have
$$
\frac{m_1m_2}{M}\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{M}.
$$
Introducing the reduced mass $\mu=m_1m_2/M$ we have finally
$$
\mu\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{M}.
$$
And $\mu\dot{\boldsymbol{r}}$ defines the relative momentum $\boldsymbol{q}=\mu\dot{\boldsymbol{r}}$.
When we introduce the Lagrangian formalism we will see that it is much easier to derive these equations.
* 2c (5pt) Show then that the kinetic energy for two objects can then be written as
$$
K=\frac{P^2}{2M}+\frac{q^2}{2\mu}.
$$
Here we just need to use our definitions of kinetic energy in terms of the coordinates $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$.
We have that
$$
K=\frac{p_1^2}{2m_1}+\frac{p_2^2}{2m_2},
$$
and with $\boldsymbol{p}_1=m_1\dot{\boldsymbol{r}}_1$ and $\boldsymbol{p}_2=m_2\dot{\boldsymbol{r}}_2$ and using
$$
\dot{\boldsymbol{r}}_1=\dot{\boldsymbol{R}}+\frac{m_2}{M}\dot{\boldsymbol{r}},
$$
and
$$
\dot{\boldsymbol{r}}_2=\dot{\boldsymbol{R}}-\frac{m_1}{M}\dot{\boldsymbol{r}},
$$
we obtain (after squaring the expressions for $\dot{\boldsymbol{r}}_1$ and $\dot{\boldsymbol{r}}_2$) we have
$$
K=\frac{(m_1+m_2)\dot{\boldsymbol{R}}^2}{2}+\frac{(m_1+m_2)m_1m_2\dot{\boldsymbol{r}}^2}{2M^2},
$$
which we simplify to
$$
K=\frac{\dot{\boldsymbol{P}}^2}{2M}+\frac{\mu\dot{\boldsymbol{q}}^2}{2},
$$
which is what we wanted to show.
* 2d (5pt) Show that the total angular momentum for two-particles in the center-of-mass frame $\boldsymbol{R}=0$, is given by
$$
\boldsymbol{L}=\boldsymbol{r}\times \mu\dot{\boldsymbol{r}}.
$$
Here we need again that
$$
\boldsymbol{r} =\boldsymbol{r}_1-\boldsymbol{r}_2,
$$
and we then define $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative and center of mass positions with $\boldsymbol{R}=0$
$$
\boldsymbol{r}_1=\frac{m_2}{M}\boldsymbol{r},
$$
and
$$
\boldsymbol{r}_2=-\frac{m_1}{M}\boldsymbol{r},
$$
The angular momentum (the total one) is the sum of the individual angular momenta (see homework 4) and we have
$$
\boldsymbol{L} = \boldsymbol{r}_1 \times \boldsymbol{p}_1+\boldsymbol{r}_2 \times \boldsymbol{p}_2,
$$
and using that $m_1\dot{\boldsymbol{r}}_1=\boldsymbol{p}_1$ and $m_2\dot{\boldsymbol{r}}_2=\boldsymbol{p}_2$ we have
$$
\boldsymbol{L} = m_1\boldsymbol{r}_1 \times \dot{\boldsymbol{r}}_1+m_2\boldsymbol{r}_2 \times \dot{\boldsymbol{r}}_2.
$$
Inserting the equations for $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative motion, we have
$$
\boldsymbol{L} = m_1 \frac{m_2}{M}\boldsymbol{r}\times\frac{m_2}{M}\boldsymbol{r} +m_2 \frac{m_1}{M}\boldsymbol{r} \times \frac{m_1}{M}\dot{\boldsymbol{r}}.
$$
We see that can rewrite this equation as
$$
\boldsymbol{L}=\boldsymbol{r}\times \mu\dot{\boldsymbol{r}},
$$
which is what we wanted to derive.
### Exercise: Conservation of Energy
The equations of motion in the center-of-mass frame in two dimensions with $x=r\cos{(\phi)}$ and $y=r\sin{(\phi)}$ and
$r\in [0,\infty)$, $\phi\in [0,2\pi]$ and $r=\sqrt{x^2+y^2}$ are given by
$$
\mu \ddot{r}=-\frac{dV(r)}{dr}+\mu r\dot{\phi}^2,
$$
and
$$
\dot{\phi}=\frac{L}{\mu r^2}.
$$
Here $V(r)$ is any central force which depends only on the relative coordinate.
* 1a (5pt) Show that you can rewrite the radial equation in terms of an effective potential $V_{\mathrm{eff}}(r)=V(r)+L^2/(2\mu r^2)$.
Here we use that
$$
\dot{\phi}=\frac{L}{\mu r^2}.
$$
and rewrite the above equation of motion as
$$
\mu \ddot{r}=-\frac{dV(r)}{dr}+\frac{L^2}{\mu r^3}.
$$
If we now define an effective potential
$$
V_{\mathrm{eff}}=V(r)+\frac{L^2}{2\mu r^2},
$$
we can rewrite our equation of motion in terms of
$$
\mu \ddot{r}=-\frac{dV_{\mathrm{eff}}(r)}{dr}=-\frac{dV(r)}{dr}+\frac{L^2}{\mu r^3}.
$$
The addition due to the angular momentum comes from the kinetic energy
when we rewrote it in terms of polar coordinates. It introduces a
so-called centrifugal barrier due to the angular momentum. This
centrifugal barrier pushes the object farther away from the origin.
Alternatively,
<!-- Equation labels as ordinary links -->
<div id="_auto22"></div>
$$
\begin{equation}
-\frac{dV_{\text{eff}}(r)}{dr} = \mu \ddot{r} =-\frac{dV(r)}{dr}+\mu\dot{\phi}^2r
\label{_auto22} \tag{35}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto23"></div>
$$
\begin{equation}
-\frac{dV_{\text{eff}}(r)}{dr} = -\frac{dV(r)}{dr}+\mu\left( \frac{L}{\mu r^2}\right) ^2r
\label{_auto23} \tag{36}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto24"></div>
$$
\begin{equation}
= -\frac{dV(r)}{dr}+\mu\frac{L^2}{\mu}r^{-3}
\label{_auto24} \tag{37}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto25"></div>
$$
\begin{equation}
= -\frac{d\left( V(r)+\frac{1}{2} \frac{L^2}{\mu r^2}\right) }{dr}.
\label{_auto25} \tag{38}
\end{equation}
$$
Integrating we obtain
<!-- Equation labels as ordinary links -->
<div id="_auto26"></div>
$$
\begin{equation}
V_{\text{eff}}(r) = V(r) + \frac{L^2}{2\mu r^2} + C
\label{_auto26} \tag{39}
\end{equation}
$$
Imposing the extra condition that $V_{\text{eff}}(r\rightarrow \infty) = V(r\rightarrow \infty)$,
<!-- Equation labels as ordinary links -->
<div id="_auto27"></div>
$$
\begin{equation}
V_{\text{eff}}(r) = V(r) + \frac{L^2}{2\mu r^2}
\label{_auto27} \tag{40}
\end{equation}
$$
Write out the final differential equation for the radial degrees of freedom when we specify that $V(r)=-\alpha/r$. Plot the effective potential. You can choose values for $\alpha$ and $L$ and discuss (see Taylor section 8.4 and example 8.2) the physics of the system for two energies, one larger than zero and one smaller than zero. This is similar to what you did in the first midterm, except that the potential is different.
We insert now the explicit potential form $V(r)=-\alpha/r$. This gives us the following equation of motion
$$
\mu \ddot{r}=-\frac{dV_{\mathrm{eff}}(r)}{dr}=-\frac{d(-\alpha/r)}{dr}+\frac{L^2}{\mu r^3}=-\frac{\alpha}{r^2}+\frac{L^2}{\mu r^3}.
$$
The following code plots this effective potential for a simple choice of parameters, with a standard gravitational potential $-\alpha/r$. Here we have chosen $L=m=\alpha=1$.
```
# Common imports
import numpy as np
from math import *
import matplotlib.pyplot as plt
Deltax = 0.01
#set up arrays
xinitial = 0.3
xfinal = 5.0
alpha = 1.0 # spring constant
m = 1.0 # mass, you can change these
AngMom = 1.0 # The angular momentum
n = ceil((xfinal-xinitial)/Deltax)
x = np.zeros(n)
for i in range(n):
x[i] = xinitial+i*Deltax
V = np.zeros(n)
V = -alpha/x+0.5*AngMom*AngMom/(m*x*x)
# Plot potential
fig, ax = plt.subplots()
ax.set_xlabel('r[m]')
ax.set_ylabel('V[J]')
ax.plot(x, V)
fig.tight_layout()
plt.show()
```
If we select a potential energy below zero (and not necessarily one
which corresponds to the minimum point), the object will oscillate
between two values of $r$, a value $r_{\mathrm{min}}$ and a value
$r_{\mathrm{max}}$. We can assume that for example the kinetic energy
is zero at these two points. The object will thus oscillate back and
forth between these two points. As we will see in connection with the
solution of the equations of motion, this case corresponds to
elliptical orbits. If we select $r$ equal to the minimum of the
potential and use initial conditions for the velocity that correspond
to circular motion, the object will have a constant value of $r$ given
by the value at the minimum and the orbit is a circle.
If we select a potential energy larger than zero, then, since the
kinetic energy is always larger or equal to zero, the object will move
away from the origin. See also the discussion in Taylor, sections 8.4-8.6.
### Exercise: Harmonic oscillator again
Consider a particle of mass $m$ in a $2$-dimensional harmonic oscillator with potential
$$
V(r)=\frac{1}{2}kr^2=\frac{1}{2}k(x^2+y^2).
$$
We assume the orbit has a final non-zero angular momentum $L$. The
effective potential looks like that of a harmonic oscillator for large
$r$, but for small $r$, the centrifugal potential repels the particle
from the origin. The combination of the two potentials has a minimum
for at some radius $r_{\rm min}$.
Set up the effective potential and plot it. Find $r_{\rm min}$ and $\dot{\phi}$. Show that the latter is given by $\dot{\phi}=\sqrt{k/m}$. At $r_{\rm min}$ the particle does not accelerate and $r$ stays constant and the motion is circular. With fixed $k$ and $m$, which parameter can we adjust to change the value of $r$ at $r_{\rm min}$?
We consider the effective potential. The radius of a circular orbit is at the minimum of the potential (where the effective force is zero).
The potential is plotted here with the parameters $k=m=1.0$ and $L=1.0$.
```
# Common imports
import numpy as np
from math import *
import matplotlib.pyplot as plt
Deltax = 0.01
#set up arrays
xinitial = 0.5
xfinal = 3.0
k = 1.0 # spring constant
m = 1.0 # mass, you can change these
AngMom = 1.0 # The angular momentum
n = ceil((xfinal-xinitial)/Deltax)
x = np.zeros(n)
for i in range(n):
x[i] = xinitial+i*Deltax
V = np.zeros(n)
V = 0.5*k*x*x+0.5*AngMom*AngMom/(m*x*x)
# Plot potential
fig, ax = plt.subplots()
ax.set_xlabel('r[m]')
ax.set_ylabel('V[J]')
ax.plot(x, V)
fig.tight_layout()
plt.show()
```
We have an effective potential
$$
\begin{eqnarray*}
V_{\rm eff}&=&\frac{1}{2}kr^2+\frac{L^2}{2mr^2}
\end{eqnarray*}
$$
The effective potential looks like that of a harmonic oscillator for
large $r$, but for small $r$, the centrifugal potential repels the
particle from the origin. The combination of the two potentials has a
minimum for at some radius $r_{\rm min}$.
$$
\begin{eqnarray*}
0&=&kr_{\rm min}-\frac{L^2}{mr_{\rm min}^3},\\
r_{\rm min}&=&\left(\frac{L^2}{mk}\right)^{1/4},\\
\dot{\theta}&=&\frac{L}{mr_{\rm min}^2}=\sqrt{k/m}.
\end{eqnarray*}
$$
For particles at $r_{\rm min}$ with $\dot{r}=0$, the particle does not
accelerate and $r$ stays constant, i.e. a circular orbit. The radius
of the circular orbit can be adjusted by changing the angular momentum
$L$.
For the above parameters this minimum is at $r_{\rm min}=1$.
Now consider small vibrations about $r_{\rm min}$. The effective spring constant is the curvature of the effective potential. Use the curvature at $r_{\rm min}$ to find the effective spring constant (hint, look at exercise 4 in homework 6) $k_{\mathrm{eff}}$. Show also that $\omega=\sqrt{k_{\mathrm{eff}}/m}=2\dot{\phi}$
$$
\begin{eqnarray*}
k_{\rm eff}&=&\left.\frac{d^2}{dr^2}V_{\rm eff}(r)\right|_{r=r_{\rm min}}=k+\frac{3L^2}{mr_{\rm min}^4}\\
&=&4k,\\
\omega&=&\sqrt{k_{\rm eff}/m}=2\sqrt{k/m}=2\dot{\theta}.
\end{eqnarray*}
$$
Because the radius oscillates with twice the angular frequency,
the orbit has two places where $r$ reaches a minimum in one
cycle. This differs from the inverse-square force where there is one
minimum in an orbit. One can show that the orbit for the harmonic
oscillator is also elliptical, but in this case the center of the
potential is at the center of the ellipse, not at one of the foci.
The solution to the equations of motion in Cartesian coordinates is simple. The $x$ and $y$ equations of motion separate, and we have $\ddot{x}=-kx/m$ and $\ddot{y}=-ky/m$. The harmonic oscillator is indeed a system where the degrees of freedom separate and we can find analytical solutions. Define a natural frequency $\omega_0=\sqrt{k/m}$ and show that (where $A$, $B$, $C$ and $D$ are arbitrary constants defined by the initial conditions)
$$
\begin{eqnarray*}
x&=&A\cos\omega_0 t+B\sin\omega_0 t,\\
y&=&C\cos\omega_0 t+D\sin\omega_0 t.
\end{eqnarray*}
$$
The solution is also simple to write down exactly in Cartesian coordinates. The $x$ and $y$ equations of motion separate,
$$
\begin{eqnarray*}
\ddot{x}&=&-kx,\\
\ddot{y}&=&-ky.
\end{eqnarray*}
$$
We know from our studies of the harmonic oscillator that the general solution can be expressed as
$$
\begin{eqnarray*}
x&=&A\cos\omega_0 t+B\sin\omega_0 t,\\
y&=&C\cos\omega_0 t+D\sin\omega_0 t.
\end{eqnarray*}
$$
With the solutions for $x$ and $y$, and $r^2=x^2+y^2$ and the definitions $\alpha=\frac{A^2+B^2+C^2+D^2}{2}$, $\beta=\frac{A^2-B^2+C^2-D^2}{2}$ and $\gamma=AB+CD$, show that
$$
r^2=\alpha+(\beta^2+\gamma^2)^{1/2}\cos(2\omega_0 t-\delta),
$$
with
$$
\delta=\arctan(\gamma/\beta).
$$
We start with $r^2 & = x^2+y^2$ and square the above analytical solutions and after some **exciting algebraic manipulations** we arrive at
<!-- Equation labels as ordinary links -->
<div id="_auto28"></div>
$$
\begin{equation}
r^2 = x^2+y^2
\label{_auto28} \tag{41}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto29"></div>
$$
\begin{equation}
= \left( A\cos\omega_0 t+B\sin\omega_0 t\right) ^2 + \left( C\cos\omega_0 t+D\sin\omega_0 t\right) ^2
\label{_auto29} \tag{42}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto30"></div>
$$
\begin{equation}
= A^2\cos^2\omega_0 t+B^2\sin^2\omega_0 t + 2AB\sin\omega_0 t \cos\omega_0 t + C^2\cos^2\omega_0 t+D^2\sin^2\omega_0 t + 2CD\sin\omega_0 t \cos\omega_0 t
\label{_auto30} \tag{43}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto31"></div>
$$
\begin{equation}
= (A^2+C^2)\cos^2\omega_0 t + (B^2+D^2)\sin^2\omega_0 t + 2(AC + BD)\sin\omega_0 t \cos\omega_0 t
\label{_auto31} \tag{44}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto32"></div>
$$
\begin{equation}
= (B^2+D^2) + (A^2+C^2-B^2-D^2)\cos^2\omega_0 t + 2(AC + BD)2\sin2\omega_0 t
\label{_auto32} \tag{45}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto33"></div>
$$
\begin{equation}
= (B^2+D^2) + (A^2+C^2-B^2-D^2)\frac{1+\cos{2\omega_0 t}}{2} + 2(AC + BD)\frac{1}{2}\sin2\omega_0 t
\label{_auto33} \tag{46}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto34"></div>
$$
\begin{equation}
= \frac{2B^2+2D^2+A^2+C^2-B^2-D^2}{2} + (A^2+C^2-B^2-D^2)\frac{\cos{2\omega_0 t}}{2} + (AC + BD)\sin2\omega_0 t
\label{_auto34} \tag{47}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto35"></div>
$$
\begin{equation}
= \frac{B^2+D^2+A^2+C^2}{2} + \frac{A^2+C^2-B^2-D^2}{2}\cos{2\omega_0 t} + (AC + BD)\sin2\omega_0 t
\label{_auto35} \tag{48}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto36"></div>
$$
\begin{equation}
= \alpha + \beta\cos{2\omega_0 t} + \gamma\sin2\omega_0 t
\label{_auto36} \tag{49}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto37"></div>
$$
\begin{equation}
= \alpha + \sqrt{\beta^2+\gamma^2}\left( \frac{\beta}{\sqrt{\beta^2+\gamma^2}}\cos{2\omega_0 t} + \frac{\gamma}{\sqrt{\beta^2+\gamma^2}}\sin2\omega_0 t\right)
\label{_auto37} \tag{50}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto38"></div>
$$
\begin{equation}
= \alpha + \sqrt{\beta^2+\gamma^2}\left( \cos{\delta}\cos{2\omega_0 t} + \sin{\delta}\sin2\omega_0 t\right)
\label{_auto38} \tag{51}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto39"></div>
$$
\begin{equation}
= \alpha + \sqrt{\beta^2+\gamma^2}\cos{\left( 2\omega_0 t - \delta\right) },
\label{_auto39} \tag{52}
\end{equation}
$$
which is what we wanted to show.
### Exercise: Numerical Solution of the Harmonic Oscillator
Using the code we developed in homeworks 5 and/or 6 for the Earth-Sun system, we can solve the above harmonic oscillator problem in two dimensions using our code from this homework. We need however to change the acceleration from the gravitational force to the one given by the harmonic oscillator potential.
* 3a (20pt) Use for example the code in the exercise set to set up the acceleration and use the initial conditions fixed by for example $r_{\rm min}$ from exercise 2. Which value should the initial velocity take if you place yourself at $r_{\rm min}$ and you require a circular motion? Hint: see the first midterm, part 2. There you used the centripetal acceleration.
Instead of solving the equations in the cartesian frame we will now rewrite the above code in terms of the radial degrees of freedom only. Our differential equation is now
$$
\mu \ddot{r}=-\frac{dV(r)}{dr}+\mu\dot{\phi}^2,
$$
and
$$
\dot{\phi}=\frac{L}{\mu r^2}.
$$
* 3b (20pt) We will use $r_{\rm min}$ to fix a value of $L$, as seen in exercise 2. This fixes also $\dot{\phi}$. Write a code which now implements the radial equation for $r$ using the same $r_{\rm min}$ as you did in 3a. Compare the results with those from 3a with the same initial conditions. Do they agree? Use only one set of initial conditions.
The code here finds the solution for $x$ and $y$ using the code we
developed in homework 5 and 6 and the midterm. Note that this code is
tailored to run in Cartesian coordinates. There is thus no angular
momentum dependent term.
Here we have chosen initial conditions that
correspond to the minimum of the effective potential
$r_{\mathrm{min}}$. We have chosen $x_0=r_{\mathrm{min}}$ and
$y_0=0$. Similarly, we use the centripetal acceleration to determine
the initial velocity so that we have a circular motion (see back to the
last question of the midterm). This means that we set the centripetal
acceleration $v^2/r$ equal to the force from the harmonic oscillator $-k\boldsymbol{r}$. Taking the
magnitude of $\boldsymbol{r}$ we have then
$v^2/r=k/mr$, which gives $v=\pm\omega_0r$.
Since the code here solves the equations of motion in cartesian
coordinates and the harmonic oscillator potential leads to forces in
the $x$- and $y$-directions that are decoupled, we have to select the initial velocities and positions so that we don't get that for example $y(t)=0$.
We set $x_0$ to be different from zero and $v_{y0}$ to be different from zero.
```
# Common imports
import numpy as np
import pandas as pd
from math import *
import matplotlib.pyplot as plt
import os
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
DeltaT = 0.001
#set up arrays
tfinal = 10.0
n = ceil(tfinal/DeltaT)
# set up arrays
t = np.zeros(n)
v = np.zeros((n,2))
r = np.zeros((n,2))
radius = np.zeros(n)
# Constants of the model
k = 1.0 # spring constant
m = 1.0 # mass, you can change these
omega02 = k/m # Frequency
AngMom = 1.0 # The angular momentum
# Potential minimum
rmin = (AngMom*AngMom/k/m)**0.25
# Initial conditions as compact 2-dimensional arrays, x0=rmin and y0 = 0
x0 = rmin; y0= 0.0
r0 = np.array([x0,y0])
vy0 = sqrt(omega02)*rmin; vx0 = 0.0
v0 = np.array([vx0,vy0])
r[0] = r0
v[0] = v0
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up the acceleration
a = -r[i]*omega02
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
anew = -r[i+1]*omega02
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
# Plot position as function of time
radius = np.sqrt(r[:,0]**2+r[:,1]**2)
fig, ax = plt.subplots(3,1)
ax[0].set_xlabel('time')
ax[0].set_ylabel('radius squared')
ax[0].plot(t,r[:,0]**2+r[:,1]**2)
ax[1].set_xlabel('time')
ax[1].set_ylabel('x position')
ax[1].plot(t,r[:,0])
ax[2].set_xlabel('time')
ax[2].set_ylabel('y position')
ax[2].plot(t,r[:,1])
fig.tight_layout()
save_fig("2DimHOVV")
plt.show()
```
We see that the radius (to within a given error), we obtain a constant radius.
The following code shows first how we can solve this problem using the radial degrees of freedom only.
Here we need to add the explicit centrifugal barrier. Note that the variable $r$ depends only on time. There is no $x$ and $y$ directions
since we have transformed the equations to polar coordinates.
```
DeltaT = 0.01
#set up arrays
tfinal = 10.0
n = ceil(tfinal/DeltaT)
# set up arrays for t, v and r
t = np.zeros(n)
v = np.zeros(n)
r = np.zeros(n)
E = np.zeros(n)
# Constants of the model
AngMom = 1.0 # The angular momentum
m = 1.0
k = 1.0
omega02 = k/m
c1 = AngMom*AngMom/(m*m)
c2 = AngMom*AngMom/m
rmin = (AngMom*AngMom/k/m)**0.25
# Initial conditions
r0 = rmin
v0 = 0.0
r[0] = r0
v[0] = v0
E[0] = 0.5*m*v0*v0+0.5*k*r0*r0+0.5*c2/(r0*r0)
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up acceleration
a = -r[i]*omega02+c1/(r[i]**3)
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
anew = -r[i+1]*omega02+c1/(r[i+1]**3)
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
E[i+1] = 0.5*m*v[i+1]*v[i+1]+0.5*k*r[i+1]*r[i+1]+0.5*c2/(r[i+1]*r[i+1])
# Plot position as function of time
fig, ax = plt.subplots(2,1)
ax[0].set_xlabel('time')
ax[0].set_ylabel('radius')
ax[0].plot(t,r)
ax[1].set_xlabel('time')
ax[1].set_ylabel('Energy')
ax[1].plot(t,E)
save_fig("RadialHOVV")
plt.show()
```
### Exercise: Equations for an ellipse
Consider an ellipse defined by the sum of the distances from the two foci being $2D$, which expressed in a Cartesian coordinates with the middle of the ellipse being at the origin becomes
$$
\sqrt{(x-a)^2+y^2}+\sqrt{(x+a)^2+y^2}=2D.
$$
Here the two foci are at $(a,0)$ and $(-a,0)$. Show that this form is can be written as
$$
\frac{x^2}{D^2}+\frac{y^2}{D^2-a^2}=1.
$$
We start by squaring the two sides and, again, after some **exciting algebraic manipulations** we arrive at
$$
\sqrt{(x-a)^2+y^2}+\sqrt{(x+a)^2+y^2} =2D
\\ (x-a)^2 + y^2 + (x+a)^2 + y^2 + 2\sqrt{(x-a)^2 + y^2}\sqrt{(x+a)^2+y^2} = 4D^2
\\ 2y^2 + 2x^2 + 2a^2 + 2\sqrt{(x-a)^2(x+a)^2 + y^4 + y^2[(x-a)^2+(x+a)^2]} = 4D^2
\\ y^2 + x^2 + a^2 + \sqrt{(x^2-a^2)^2 + y^4 + y^2(2x^2+2a^2)} = 2D^2
\\ \sqrt{(x^2-a^2)^2 + y^4 + y^2(2x^2+2a^2)} = 2D^2 -( y^2 + x^2 + a^2 )
\\ (x^2-a^2)^2 + y^4 + y^2(2x^2+2a^2) = 4D^4 + y^4 + x^4 + a^4 - 4D^2( y^2 + x^2 + a^2 ) + 2(y^2x^2+y^2a^2+x^2a^2)
\\ x^4-2x^2a^2+a^4 + y^4 + 2y^2x^2+2y^2a^2 = 4D^4 + y^4 + x^4 + a^4 - 4D^2y^2 -4D^2 x^2 -4D^2 a^2 + 2y^2x^2+2y^2a^2+2x^2a^2
\\ 4D^4 - 4D^2y^2 -4D^2 x^2 -4D^2 a^2 +4x^2a^2 = 0
\\ D^4 - D^2y^2 -D^2 x^2 -D^2 a^2 +x^2a^2 = 0
\\ D^2(D^2-a^2) - x^2(D^2-a^2) = D^2y^2
\\ D^2 - x^2 = \frac{D^2y^2}{D^2-a^2}
\\ 1 - \frac{x^2}{D^2} = \frac{y^2}{D^2-a^2}
\\ \frac{x^2}{D^2} + \frac{y^2}{D^2-a^2} = 1,
$$
where the last line is indeed the equation for an ellipse.
### Exercise: Attractive Potential
Consider a particle in an attractive potential
$$
U(r)=-\alpha/r.
$$
The quantity $r$ is the absolute value of the relative position. We
will use the reduced mass $\mu$ and the angular momentum $L$, as
discussed during the lectures. With the transformation of a two-body
problem to the center-of-mass frame, the actual equations look like an
*effective* one-body problem. The energy of the system is $E$ and the
minimum of the effective potential is $r_{\rm min}$.
The analytical solution to the radial equation of motion is
$$
r(\phi) = \frac{1}{\frac{\mu\alpha}{L^2}+A\cos{(\phi)}}.
$$
Find the value of $A$. Hint: Use the fact that at $r_{\rm min}$
there is no radial kinetic energy and $E=-\alpha/r_{\rm min}+L^2/2mr_{\rm min}^2$.
At $r_{\mathrm{min}}$ and $r_{\mathrm{max}}$ , all the kinetic energy is stored in the velocity in the direction perpendicular to $r$ since the radial velocity is set to zero . We can calculate using angular momentum and from there, find 𝐴 in terms of the energy $E$ which is constant. But first, we need to find $r_{\mathrm{min}}$ from the conservation of energy (noting that the radial velocity $\ddot{r}$ at the mininum is zero):
$$
E = U(r) + \frac{1}{2} \mu(\ddot{r}^2 + (r\ddot{\phi})^2)
\\
E = \frac{-\alpha}{r_{\min}} + \frac{1}{2} \mu\left( \frac{L}{\mu r_{\min}}\right) ^2
\\
E r_{\min}^2 - \frac{1}{2}\mu\left( \frac{L}{\mu}\right) ^2 + \alpha r_{\min} = 0
\\
r_{\min}^2 + \frac{\alpha}{E} r_{\min} - \frac{L^2}{2E\mu} = 0
\\
r_{\min} = - \frac{\alpha}{2E} \pm \frac{1}{2} \sqrt{\frac{\alpha^2}{E^2} + 2\frac{L^2}{E\mu}}
$$
Since we're looking for the minimum, the ± sign must be negative (then 𝑟min will not be negative since 𝐸<0 ). Therefore, we have
$$
\frac{1}{\frac{\mu\alpha}{L^2}+A} = -\frac{\alpha}{2E} - \frac{1}{2} \sqrt{\frac{\alpha^2}{E^2} + 2\frac{L^2}{E\mu}}
\\
A = - \frac{\mu\alpha}{L^2} - \frac{2E}{\alpha + \sqrt{\alpha^2 + 2\frac{L^2E}{\mu}}}
$$
### Exercise: Inverse-square force
Consider again the same effective potential as in the previous exercise. This leads to an attractive inverse-square-law force, $F=-\alpha/r^2$. Consider a particle of mass $m$ with angular momentum $L$. Taylor sections 8.4-8.7 are relevant background material. See also the harmonic oscillator potential from hw8. The equation of motion for the radial degrees of freedom is (see also hw8) in the center-of-mass frame in two dimensions with $x=r\cos{(\phi)}$ and $y=r\sin{(\phi)}$ and
$r\in [0,\infty)$, $\phi\in [0,2\pi]$ and $r=\sqrt{x^2+y^2}$ are given by
$$
\ddot{r}=-\frac{1}{m}\frac{dV(r)}{dr}+r\dot{\phi}^2,
$$
and
$$
\dot{\phi}=\frac{L}{m r^2}.
$$
Here $V(r)$ is any central force which depends only on the relative coordinate.
Find the radius of a circular orbit by solving for the position of the minimum of the effective potential.
<!-- Equation labels as ordinary links -->
<div id="_auto40"></div>
$$
\begin{equation}
\frac{1}{m}\frac{dV(r)}{dr} = r\dot{\phi}^2
\label{_auto40} \tag{53}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto41"></div>
$$
\begin{equation} \frac{1}{m}\left( -\frac{-\alpha}{r^2}\right) = r \frac{L^2}{m^2r^4}
\label{_auto41} \tag{54}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto42"></div>
$$
\begin{equation} \frac{\alpha}{mr^2} = \frac{L^2}{m^2r^3}
\label{_auto42} \tag{55}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto43"></div>
$$
\begin{equation} r = \frac{L^2}{m\alpha}
\label{_auto43} \tag{56}
\end{equation}
$$
At the minimum, the radial velocity is zero and it is only the [centripetal velocity](https://en.wikipedia.org/wiki/Centripetal_force) which is nonzero. This implies that $\ddot{r}=0$. What is the angular frequency, $\dot{\theta}$, of the orbit? Solve this by setting $\ddot{r}=0=F/m+\dot{\theta}^2r$.
<!-- Equation labels as ordinary links -->
<div id="_auto44"></div>
$$
\begin{equation}
\dot{\theta}^2 r = - \frac{F}{m}
\label{_auto44} \tag{57}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto45"></div>
$$
\begin{equation} \dot{\theta}^2 r = - \frac{-\frac{\alpha}{r^2}}{m}
\label{_auto45} \tag{58}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto46"></div>
$$
\begin{equation} \dot{\theta}^2 = \frac{\alpha}{mr^3}
\label{_auto46} \tag{59}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto47"></div>
$$
\begin{equation} \dot{\theta} = \pm \sqrt{\frac{\alpha}{mr^3}}
\label{_auto47} \tag{60}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto48"></div>
$$
\begin{equation} \dot{\theta} = \pm \sqrt{\frac{\alpha}{m\frac{L^6}{m^3\alpha^3}}}
\label{_auto48} \tag{61}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto49"></div>
$$
\begin{equation} \dot{\theta} = \pm \sqrt{\frac{\alpha^4m^2}{L^6}}
\label{_auto49} \tag{62}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto50"></div>
$$
\begin{equation} \dot{\theta} = \pm \frac{\alpha^2m}{L^3}
\label{_auto50} \tag{63}
\end{equation}
$$
Find the effective spring constant for the particle at the minimum.
We have shown in class that from the taylor expansion, we have
$$
k = \frac{d^2V_{\text{eff}}}{dr^2}
$$
Therefore, all we have to do is find the second derivative of $V_{\text{eff}}$ around the minimum point of $V_{\text{eff}}$ where $\dot{r} = \ddot{r} = 0$.
<!-- Equation labels as ordinary links -->
<div id="_auto51"></div>
$$
\begin{equation}
k = \frac{d^2V_{\text{eff}}}{dr^2}
\label{_auto51} \tag{64}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto52"></div>
$$
\begin{equation} = \frac{d^2\left( -\frac{\alpha}{r} + \frac{1}{2} \frac{L^2}{mr^2}\right) }{dr^2}
\label{_auto52} \tag{65}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto53"></div>
$$
\begin{equation} = -\frac{2\alpha}{r^3} + \frac{3L^2}{mr^4}
\label{_auto53} \tag{66}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto54"></div>
$$
\begin{equation} = -\frac{2\alpha}{\frac{L^6}{m^3\alpha^3}} + \frac{3L^2}{m\frac{L^8}{m^4\alpha^4}}
\label{_auto54} \tag{67}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto55"></div>
$$
\begin{equation} = -\frac{2m^3\alpha^4}{L^6} + \frac{3m^3\alpha^4}{L^6}
\label{_auto55} \tag{68}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto56"></div>
$$
\begin{equation} = \frac{m^3\alpha^4}{L^6}
\label{_auto56} \tag{69}
\end{equation}
$$
What is the angular frequency for small vibrations about the minimum? How does this compare with the answer to (3b)?
For small deviations $\delta r$ of $r$,
$$
m\frac{d^2\left( \delta r \right) }{dt^2} = -k \delta r
$$
The solution of this differential equation is of the form
$$
\delta r = A \cos(\omega t + \phi)
$$
where
<!-- Equation labels as ordinary links -->
<div id="_auto57"></div>
$$
\begin{equation}
\omega = \sqrt{\frac{k}{m}}
\label{_auto57} \tag{70}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto58"></div>
$$
\begin{equation} = \sqrt{\frac{m^2\alpha^4}{L^6}}
\label{_auto58} \tag{71}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto59"></div>
$$
\begin{equation} = \frac{m\alpha^2}{L^3}
\label{_auto59} \tag{72}
\end{equation}
$$
This is in fact equal to the expression for $\dot{\theta}$. This means that small perturbations oscillate in sync with the orbit and this traces out an ellipse with a very small eccentricity, a very nice physical result.
### Exercise: Inverse-square force again
Consider again a particle of mass $m$ in the same attractive potential, $U(r)=-\alpha/r$, with angular momentum $L$ with just the right energy so that
$$
A=m\alpha/L^2
$$
where $A$ comes from the expression
$$
r=\frac{1}{(m\alpha/L^2)+A\cos{(\phi)}}.
$$
The trajectory can then be rewritten as
$$
r=\frac{2r_0}{1+\cos\theta},~~~r_0=\frac{L^2}{2m\alpha}.
$$
Show that for this case the total energy $E$ approaches zero.
<!-- Equation labels as ordinary links -->
<div id="_auto60"></div>
$$
\begin{equation}
E = - \frac{\alpha}{r} + \frac{1}{2} m \left( (\dot{\theta}r)^2+\dot{r}^2\right)
\label{_auto60} \tag{73}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto61"></div>
$$
\begin{equation} = - \frac{\alpha}{r} + \frac{1}{2} m \left[ \left( \frac{L}{mr^2}r\right) ^2+\left( \frac{dr}{d\theta}\dot{\theta}\right) ^2\right]
\label{_auto61} \tag{74}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto62"></div>
$$
\begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) + \frac{1}{2} m \left[ \left( \frac{L(1+\cos\theta)}{2mr_0}\right) ^2+\left( 2r_0\frac{-1}{(1+\cos\theta)^2}(-\sin\theta)\frac{L}{mr^2}\right) ^2\right]
\label{_auto62} \tag{75}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto63"></div>
$$
\begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) + \frac{1}{2} m \left[ \left( \frac{L(1+\cos\theta)}{2mr_0}\right) ^2+\left( 2r_0\frac{-1}{(1+\cos\theta)^2}(-\sin\theta)\frac{L(1+\cos\theta)^2}{4mr_0^2}\right) ^2\right]
\label{_auto63} \tag{76}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto64"></div>
$$
\begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) +
\frac{1}{2} m \left[ \left( \frac{L(1+\cos\theta)}{2mr_0}\right) ^2+\left( \sin\theta\frac{L}{2mr_0}\right) ^2\right]
\label{_auto64} \tag{77}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto65"></div>
$$
\begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) +
\frac{1}{2} m \left[ \left( \frac{L(1+\cos\theta)}{2mr_0}\right) ^2+\left( \sin\theta\frac{L}{2mr_0}\right) ^2\right]
\label{_auto65} \tag{78}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto66"></div>
$$
\begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) +
\frac{1}{2} m \frac{L^2}{4m^2r_0^2} \left[ \left( 1+\cos\theta\right) ^2+\left( \sin\theta\right) ^2\right]
\label{_auto66} \tag{79}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto67"></div>
$$
\begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) +
\frac{1}{2} \frac{L^2}{4mr_0^2} \left( 1 + \cos^2\theta + 2\cos \theta + \sin^2\theta\right)
\label{_auto67} \tag{80}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto68"></div>
$$
\begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) +
\frac{1}{2} \frac{L^2}{4mr_0^2} \left( 2 + 2\cos \theta \right)
\label{_auto68} \tag{81}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto69"></div>
$$
\begin{equation} = (1+\cos\theta) \left( - \frac{\alpha}{2r_0} + \frac{L^2}{4mr_0^2}\right)
\label{_auto69} \tag{82}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto70"></div>
$$
\begin{equation} = (1+\cos\theta) \left( - \frac{\alpha}{2\frac{L^2}{2m\alpha}} + \frac{L^2}{4m\frac{L^4}{4m^2\alpha^2}}\right)
\label{_auto70} \tag{83}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto71"></div>
$$
\begin{equation} = (1+\cos\theta) \left( - \frac{m\alpha^2}{L^2} + \frac{m\alpha^2}{L^2}\right)
\label{_auto71} \tag{84}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto72"></div>
$$
\begin{equation} = 0
\label{_auto72} \tag{85}
\end{equation}
$$
With zero energy $E=0$, write this trajectory in a more recognizable parabolic form, that is express $x_0$ and $R$ in terms of $r_0$ using
$$
x=x_0-\frac{y^2}{R}.
$$
We have that
<!-- Equation labels as ordinary links -->
<div id="_auto73"></div>
$$
\begin{equation}
x = r \cos\theta
\label{_auto73} \tag{86}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto74"></div>
$$
\begin{equation}
y = r \sin \theta.
\label{_auto74} \tag{87}
\end{equation}
$$
Using the general solution with eccintricity $\epsilon=1$, we have
$$
r(\theta)=\frac{c}{1+\cos\theta},
$$
and multiplying both sides with $1+\cos\theta$ and using that $x=r\cos\theta$,
$$
r = c -x,
$$
and using that $r^2=x^2+y^2$, we square both sides
$$
r^2 = x^2+y^2=c^2 +x^2-2cx,
$$
leading to
$$
y^2=c^2-2cx,
$$
and using that we defined
$$
c=2r_0=\frac{L^2}{m\alpha},
$$
we divide by $2c$
and we get the final answer
$$
x = r_0 - \frac{y^2}{4r_0}
$$
### Exercise: Parabolic and hyperbolic orbits
The solution to the radial function for an inverse-square-law force, see for example Taylor equation (8.59) or the equation above, is
$$
r(\phi) = \frac{c}{1+\epsilon\cos{(\phi)}}.
$$
For $\epsilon=1$ (or the energy $E=0$) the orbit reduces to a parabola as we saw in the previous exercise,
while for $\epsilon > 1$ (or energy positive) the orbit becomes a hyperbola. The equation for a hyperbola in Cartesian coordinates is
$$
\frac{(x-\delta)^2}{\alpha^2}-\frac{y^2}{\beta^2}=1.
$$
For a hyperbola, identify the constants $\alpha$, $\beta$ and $\delta$ in terms of the constants $c$ and $\epsilon$ for $r(\phi)$.
<!-- Equation labels as ordinary links -->
<div id="_auto75"></div>
$$
\begin{equation}
x = r\cos\phi
\label{_auto75} \tag{88}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto76"></div>
$$
\begin{equation} = \frac{c\cos\phi}{1+\epsilon\cos\phi}
\label{_auto76} \tag{89}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto77"></div>
$$
\begin{equation}
y = r\sin\phi
\label{_auto77} \tag{90}
\end{equation}
$$
<!-- Equation labels as ordinary links -->
<div id="_auto78"></div>
$$
\begin{equation} = \frac{c\sin\phi}{1+\epsilon\cos\phi}
\label{_auto78} \tag{91}
\end{equation}
$$
Here $\epsilon>1$. We use our equation for $r$, multiply with the denominator $1+\epsilon\cos\phi$ on both sides and have
$$
r(1+\epsilon\cos\phi)=c,
$$
use $x=r\cos\phi$ and square and use that $r^2=x^2+y^2$ and we have
$$
r^2=x^2+y^2=c^2+\epsilon^2x^2-2cx\epsilon,
$$
and reorder
$$
x^2(\epsilon^2-1)-y^2-2cx\epsilon= -c^2.
$$
We complete the square in $x$ by adding and subtracting on both sides $\epsilon^2c^2/(\epsilon^2-1)$
and we obtain
$$
(\epsilon^2-1)(x-\delta)^2-y^2= -c^2+\frac{\epsilon^2c^2}{\epsilon^2-1}.
$$
Here we have defined
$$
\delta = \frac{c\epsilon}{\epsilon^2-1},
$$
and introducing the constants
$$
\alpha = \frac{c}{\epsilon^2-1},
$$
and
$$
\beta = \frac{c}{\sqrt{\epsilon^2-1}},
$$
we can rewrite the above equation as
$$
\frac{(x-\delta)^2}{\alpha^2}-\frac{y^2}{\beta^2}=1,
$$
which is nothing but the equation for a hyperbola.
### Exercise: Testing orbit types
In this exercise we can use the program for $r(\phi)$ we developed in hw8. We will use an inverse-square-law force as in the previous four exercises. The aim is to see that the orbits we get for $E<0$ become ellipses (or circles), parabola for $E=0$ and hyperbola for $E>0$. An example code is shown here.
Here we have defined the constants $L=m=\alpha=1$. Feel free to set new values. **You need also to set the initial conditions** in order to study the different types of orbits. It may be useful to plot the potential here and find the values for the initial conditions that fit $E<0$, $E=0$ and $E>0$.
```
# Common imports
import numpy as np
import pandas as pd
from math import *
import matplotlib.pyplot as plt
# Simple Gravitational Force -alpha/r
DeltaT = 0.01
#set up arrays
tfinal = 100.0
n = ceil(tfinal/DeltaT)
# set up arrays for t, v and r
t = np.zeros(n)
v = np.zeros(n)
r = np.zeros(n)
# Constants of the model, setting all variables to one for simplicity
alpha = 1.0
AngMom = 1.0 # The angular momentum
m = 1.0 # scale mass to one
c1 = AngMom*AngMom/(m*m)
c2 = AngMom*AngMom/m
# You need to specify the initial conditions
# Here we have chosen the conditions which lead to circular orbit and thereby a constant r
r0 = (AngMom*AngMom/m/alpha)
v0 = 0.0
r[0] = r0
v[0] = v0
# Start integrating using the Velocity-Verlet method
for i in range(n-1):
# Set up acceleration
a = -alpha/(r[i]**2)+c1/(r[i]**3)
# update velocity, time and position using the Velocity-Verlet method
r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a
anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3)
v[i+1] = v[i] + 0.5*DeltaT*(a+anew)
t[i+1] = t[i] + DeltaT
# Plot position as function of time
fig, ax = plt.subplots(2,1)
ax[0].set_xlabel('time')
ax[0].set_ylabel('radius')
ax[0].plot(t,r)
ax[1].set_xlabel('time')
ax[1].set_ylabel('Velocity')
ax[1].plot(t,v)
plt.show()
```
Run your code and study and discuss the situations where you have
elliptical, parabolic and hyperbolic orbits. Discuss the physics of
these cases. The results from the four previous exercises 4 may be useful
here. In the code here we have chosen initial conditions which correspond to circular motion.
This corresponds to
$$
r_{\mathrm{min}} = \frac{L^2}{m\alpha}.
$$
Note well that the velocity is now the radial velocity. If we want to
study the angular velocity we would need to add the equations for this
quantity. The solution to exercises 1-4 give you the minimum $r$
values needed to find the elliptical, parabolic and hyperbolic
orbits. For elliptical orbits you should have $\frac{L^2}{2m\alpha} <
r_{\mathrm{min}} <\frac{L^2}{m\alpha}$. For parabolic orbits
$r_{\mathrm{min}} =\frac{L^2}{m\alpha}$ and for hyperbolic orbits we
have $0<r_{\mathrm{min}} <\frac{L^2}{m\alpha}$. Try out these
different initial conditions in order to test these different types of
motion.
### Exercise: New reference frame
Show that if one transforms to a reference frame where the total
momentum is zero, $\boldsymbol{p}_1=-\boldsymbol{p}_2$, that the relative momentum
$\boldsymbol{q}$ corresponds to either $\boldsymbol{p}_1$ or $-\boldsymbol{p}_2$. This
means that in this frame the magnitude of $\boldsymbol{q}$ is one half the
magnitude of $\boldsymbol{p}_1-\boldsymbol{p}_2$.
### Exercise: Center of mass and relative coordinates
Given the center of mass and relative coordinates $\boldsymbol{R}$ and $\boldsymbol{r}$, respectively, for
particles of mass $m_1$ and $m_2$, find the coordinates $\boldsymbol{r}_1$
and $\boldsymbol{r}_2$ in terms of the masses, $\boldsymbol{R}$ and $\boldsymbol{r}$.
### Exercise: Two-body problems
Consider a particle of mass $m$ moving in a potential
$$
V(r)=\alpha\ln(r/\alpha),
$$
where $\alpha$ is a constant.
* (a) If the particle is moving in a circular orbit of radius $R$, find the angular frequency $\dot{\theta}$. Solve this by setting $F=-m\dot{\theta}^2r$ (force and acceleration point inward).
* (b) Express the angular momentum $L$ in terms of the constant $\alpha$, the mass $m$ and the radius $R$. Also express $R$ in terms of $L$, $\alpha$ and $m$.
* (c) Sketch the effective radial potential, $V_{\rm eff}(r)$, for a particle with angular momentum $L$. (No longer necessarily moving in a circular orbit.)
* (d) Find the position of the minimum of $V_{\rm eff}$ in terms of $L$, $\alpha$ and $m$, then compare to the result of (b).
* (e) What is the effective spring constant for a particle at the minimum of $V_{\rm eff}$? Express your answer in terms of $L$, $m$ and $\alpha$.
* (f) What is the angular frequency, $\omega$, for small oscillations of $r$ about the $R_{\rm min}$? Express your answer in terms of $\dot{\theta}$ from part (3a).
| github_jupyter |
# Lets play pool
Today, we will look at image rectification, a common need for a wide range of applications. Here, we will try to undo perspective effects to get a birds-eye view. This is very useful in sport, augmented reality and robotics applications. A similar technique is used to warp sponsor logos to undo unwanted perspective effects from cameras in support of advertising.
We'll also use today to highlight just how useful the RANSAC technique we taught is.
```
import numpy as np
import cv2
from matplotlib import pyplot as plt
from IPython import display
im = cv2.imread('./test_images/pool.png')[:,:,[2,1,0]]
plt.imshow(im)
plt.show()
```
Let's find the boundaries of the table by segmenting out the blue region and then get some edges.
```
felt = (im[:,:,2]<165)&(im[:,:,2]>135)&(im[:,:,0]<35)
plt.imshow(felt)
plt.show()
edges = cv2.Canny(felt.astype(np.uint8)*255,100,200)
plt.imshow(edges,cmap = 'gray')
plt.colorbar()
plt.show()
```
Last week we saw that ransac was a really good way of fitting homographies, by discarding outliers, but this idea can be used to fit any model. Let's use it to fit straight lines to find the edges of the pool table.
We'll extend ransac to return the 4 best lines with sufficient evidence (an edge response), and with an intersection point on the y-axis that differs from others.
Recall that the equation of a line is $ax + by + c = 0$, we can draw two edge points at random, fit a line through these, and then check consensus, repeating until we find all the key lines. We'll use lines and conics to achieve this efficiently. Let's visualise this.
```
# get all edgels
points_x,points_y = np.where(edges>0)
# convert to homogenous coordinates
points_homog = np.vstack([points_x,points_y,np.ones(len(points_x))]).T
for j in range(20):
# Pick two points at random
bins = np.random.choice(len(points_x),2,replace=False)
# find the line intersecting these using the cross (wedge) product
line = np.cross(points_homog[bins[0],:],points_homog[bins[1],:])
# Check how many other points lie within 5 pixels of this using the dot product
consensus = (np.abs(np.sum(line*points_homog,axis=-1)) < 5)
plt.clf()
plt.plot(points_homog[bins,1],points_homog[bins,0])
bins_c = consensus
plt.plot(points_homog[~bins_c,1],points_homog[~bins_c,0],'g.')
plt.plot(points_homog[bins_c,1],points_homog[bins_c,0],'bo')
plt.title('Consensus %d'%np.sum(consensus))
plt.ylim(edges.shape[0],0)
display.clear_output(wait=True)
display.display(plt.gcf())
```
Cool, let's turn this into a function to find the boundaries
```
def ransac_line(image,N=1000,max_error=5, existing_line_threshold=5):
good_lines = []
consensus_list = []
points_x,points_y = np.where(edges>0)
points_homog = np.vstack([points_x,points_y,np.ones(len(points_x))]).T
for j in range(N):
bins = np.random.choice(len(points_x),2,replace=False)
line = np.cross(points_homog[bins[0],:],points_homog[bins[1],:])
line = line/np.sqrt(line[0]**2 + line[1]**2)
line = line.reshape(1,3)
consensus = np.sum((np.abs(np.sum(line*points_homog,axis=-1)) <= max_error))
if len(good_lines) > 0:
# Check if line already found by comparing intercepts
c_good = -np.vstack(good_lines)[:,2]/(np.vstack(good_lines)[:,0]+1e-19)
c_line = -line[0,2]/(line[0,0]+1e-19)
d = np.abs(c_good-c_line)
best_d = np.argmin(d)
# Check if line alread exists
if (np.min(d) < existing_line_threshold):
#if better than current consensus, replace line
if (np.sum(d<existing_line_threshold)==1)&(consensus > consensus_list[best_d]): # existing line
good_lines[best_d] = line
consensus_list[best_d] = consensus
else:
# less than 4 lines - add a new one
if len(good_lines) < 4:
good_lines.append(line)
consensus_list.append(consensus)
# more than four lines, replace if better than worst line consensus
elif (consensus > np.min(np.array(consensus_list))):
worst_consensus = np.argmin(np.array(consensus_list))
good_lines[worst_consensus] = line
consensus_list[worst_consensus] = consensus
else:
good_lines.append(line)
consensus_list.append(consensus)
# Some plotting
if (j %100==0):
plt.clf()
plt.title(consensus_list)
plt.imshow(edges,cmap = 'gray')
x = np.linspace(0,edges.shape[0]-1,edges.shape[0],dtype=int)
for l in good_lines:
l = l.ravel()
#ax + by + c = 0 y = -ax/b -c/b
m = -l[0]/(l[1]+1e-19)
c = -l[2]/(l[1]+1e-19)
plt.plot(m*x + c,x)
m = -line[0,0]/(line[0,1]+1e-19)
c = -line[0,2]/(line[0,1]+1e-19)
plt.plot(m*x + c,x)
plt.xlim(0,edges.shape[1])
plt.ylim(edges.shape[0],0)
display.clear_output(wait=True)
display.display(plt.gcf())
return good_lines, consensus_list
plt.imshow(edges,cmap = 'gray')
lines,consensus_list = ransac_line(edges,N=5000,max_error=2,existing_line_threshold=100)
x = np.linspace(0,edges.shape[0]-1,edges.shape[0],dtype=int)
for l in lines:
l = l.ravel()
#ax + by + c = 0 y = -ax/b -c/b
m = -l[0]/(l[1]+1e-19)
c = -l[2]/(l[1]+1e-19)
plt.plot(m*x + c,x)
plt.xlim(0,edges.shape[1])
plt.ylim(edges.shape[0],0)
plt.show()
```
### Activity 1
- Write pseudocode to find all the circles in the image using a ransac-like approach.
Now lets find the corners, by getting the intercepts using the cross product
```
intercepts = []
plt.imshow(edges)
for l1 in lines:
for l2 in lines:
point = np.cross(l1,l2)
point = point/(point[0,2]+1e-19)
plt.plot(point[0,1],point[0,0],'o')
if (point[0,0]>0)&(point[0,1]>0)&(point[0,0]<edges.shape[0])&(point[0,1]<edges.shape[1]):
intercepts.append(point)
plt.xlim(0,edges.shape[1])
plt.ylim(edges.shape[0],0)
plt.show()
intercepts = np.unique(np.vstack((intercepts)),axis=0)
intercepts = intercepts[np.argsort(intercepts[:,0]),:]
```
To rectify this image, I want to warp it so that the points I've detected move to the 4 corners of the image, as plotted below. We'll do this by solving for the homography
```
image_corners = np.array([[0,edges.shape[1]],
[edges.shape[0],edges.shape[1]],
[0,0],
[edges.shape[0],0]])
#Sanity check on correspondences
colour_list = ['b','g','r','m']
plt.imshow(im)
for i in range(4):
plt.plot(intercepts[i,1],intercepts[i,0],'o',color=colour_list[i])
plt.plot(image_corners[i,1],image_corners[i,0],'o',color=colour_list[i])
plt.axis('equal')
plt.show()
H,_ = cv2.findHomography(intercepts[:,[1,0]],image_corners[:,[1,0]],method=0)
```
The homography maps intercepts onto image corners, using the transform
$\begin{bmatrix}u'\\v'\\1 \end{bmatrix} = \mathbf{H} \begin{bmatrix}u\\v\\1 \end{bmatrix}$
Applying this to all pixels rectifies our image. We can now do all sorts of future steps, eg. build a best shot predictor by detecting ball colours and assessing complexity using angles to pockets.
```
rectified_image = cv2.warpPerspective(im,H,(edges.shape[1],edges.shape[0]))
plt.imshow(rectified_image,cmap='gray')
plt.show()
```
### Activity 2
- Convince yourself that lines are transformed using the equation $l' = \mathbf{H}^{-\text{T}} l$
- The code below applies the homography to lines. Why do lines with near zero elements indicate?
- Why is $ax+by+c =0$ a better representation of a line than $y=mx+c$?
```
x = np.linspace(0,edges.shape[0]-1,edges.shape[0],dtype=int)
for i, l in enumerate(lines):
lp = (np.linalg.inv(H).T)@l[:,[1,0,2]].T
lp = lp/(lp[0]**2+lp[1]**2)
print('Line %d: \n '%(i+1), lp.ravel())
```
### Wrap up:
Some take home messages.
- Images and objects in these have geometric properties that impose a range of constraints (eg. Lines, circles).
- Camera's are ANGLE and intensity sensors, and subject to perspective geometry effects.
- We can use these constraints to aid in various detection strategies
- This is quite useful in a range of applications, particularly when you have a lot of prior knowledge about the problem (eg. sport, many industrial production lines).
- BUT, these approaches are difficult to tune, and require MANY hand-tuned thresholds
- As a result, it's quite easy to make these work on one image, only to find them fail on another
- Data-driven approaches (like neural networks) and systematic testing strategies can avoid this.
- Incorporating these geometric constraints into data-driven techniques is an active area of research in computer vision
| github_jupyter |
<a href="https://colab.research.google.com/github/elrichgro/irccam-pmodwrc/blob/main/cloudseg/notebooks/night_predictions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# Get code
%cd /content
!rm -rf irccam-pmodwrc/
!git clone https://github.com/elrichgro/irccam-pmodwrc.git
# Mount data
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
requirements = """
torch
torchvision
tqdm
h5py
jupyterlab
opencv-contrib-python
opencv-python
pytorch-lightning==1.0.5
future==0.17.1
scipy
scikit-learn
astral
test-tube
pysolar
"""
with open('requirements.txt', 'w') as f:
f.write(requirements)
!pip install -r requirements.txt
%cd /content/irccam-pmodwrc/
from cloudseg.training.cloud_segmentation import CloudSegmentation
from cloudseg.utils.constants import *
from cloudseg.datasets.cloud_dataset import HDF5Dataset
import torch
import matplotlib.pyplot as plt
import h5py
import cv2
import numpy as np
from tqdm.auto import tqdm
from torchvision import transforms
import matplotlib.gridspec as gridspec
%matplotlib inline
checkpoint_path = "/content/drive/My Drive/dsl/training_logs/20201215152108-experiment_deeplab/tube_logs/version_0/checkpoints/best-epoch=12-val_iou=0.77.ckpt" # 3
model = CloudSegmentation.load_from_checkpoint(checkpoint_path)
trans = transforms.Compose([transforms.ToTensor(),])
test_data = HDF5Dataset("/content/drive/My Drive/dsl/datasets/optimized_3/", "test", trans, use_clear_sky=True, use_sun_mask=True)
test_data_no_sky = HDF5Dataset("/content/drive/My Drive/dsl/datasets/optimized_3/", "test", trans, use_clear_sky=False, use_sun_mask=False)
test_data_no_mask = HDF5Dataset("/content/drive/My Drive/dsl/datasets/optimized_3/", "test", trans, use_clear_sky=True, use_sun_mask=False)
def get_vis_img(timestamp):
file = "/content/drive/My Drive/dsl/datasets/main_3/{}.h5".format(timestamp[:8])
with h5py.File(file, 'r') as f:
idx = None
for i, ts in enumerate(f['timestamp']):
if timestamp[:12] in ts:
idx = i
break
assert idx is not None, "Could not find image for timestamp {}".format(timestamp)
return cv2.cvtColor(np.nan_to_num(f['vis'][idx], nan=255).astype(np.uint8), cv2.COLOR_BGR2RGB)
from cloudseg.datasets.create_dataset import convert_timestamp
from cloudseg.datasets.preprocessing import process_irccam_img
def get_irc_img(timestamp):
file = "/content/drive/My Drive/dsl/irccam/irccam_{}_rad.mat".format(timestamp[:8])
with h5py.File(file, 'r') as f:
idx = None
for i, ts in enumerate(f['TM'][0]):
if timestamp[:12] in convert_timestamp(timestamp[:8], ts).strftime('%Y%m%d%H%M'):
idx = i
break
assert idx is not None, "Could not find image for timestamp {}".format(timestamp)
return process_irccam_img(f['BT'][idx])
def get_clear_sky(timestamp):
file = "/content/drive/My Drive/dsl/irccam/irccam_{}_rad.mat".format(timestamp[:8])
with h5py.File(file, 'r') as f:
idx = None
for i, ts in enumerate(f['TM'][0]):
if timestamp[:12] in convert_timestamp(timestamp[:8], ts).strftime('%Y%m%d%H%M'):
idx = i
break
assert idx is not None, "Could not find image for timestamp {}".format(timestamp)
return process_irccam_img(f['TB'][idx])
idx = np.random.randint(0, len(test_data_no_mask))
time = np.random.randint(1, 6)
ts = test_data_no_mask[idx]['timestamp']
irc = get_irc_img('{}0100'.format(ts[:8]))
print('{}0{}00'.format(ts[:8], time))
plt.imshow(irc)
timestamps = [
'201810070100',
'201812070100',
'201809090100',
'201807100100',
'201805030400', # ?
'201807050100',
'201810040400'
]
# Plot results
def plot_ax(gs, img):
ax = plt.subplot(gs)
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.imshow(img)
def plot_results(results):
dim_size = 5
rows = len(results)
cols = len(results[0])
plt.figure(figsize = (dim_size*cols,dim_size*rows))
gs = gridspec.GridSpec(rows, cols)
gs.update(wspace=0.025, hspace=0.05) # set the spacing between axes.
for i in range(rows):
for j in range(cols):
plot_ax(gs[i*cols+j], results[i][j])
plt.show()
def save_results(results, filename):
dim_size = 5
rows = len(results)
cols = len(results[0])
plt.figure(figsize = (dim_size*cols,dim_size*rows))
gs = gridspec.GridSpec(rows, cols)
gs.update(wspace=0.025, hspace=0.05) # set the spacing between axes.
for i in range(rows):
for j in range(cols):
plot_ax(gs[i*cols+j], results[i][j])
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig(filename, bbox_inches = 'tight', pad_inches = 0)
plt.close()
from cloudseg.datasets.preprocessing import process_irccam_img
from cloudseg.datasets.create_dataset import convert_timestamp
def get_pmod_label(timestamp):
day = timestamp[:8]
file = "/content/drive/My Drive/dsl/irccam/irccam_{}_rad.mat".format(day)
with h5py.File(file, 'r') as f:
idx = None
for i, ts in enumerate(f['TM'][0]):
if timestamp[:12] in convert_timestamp(timestamp[:8], ts).strftime('%Y%m%d%H%M'):
idx = i
break
assert idx is not None, "Could not find image for timestamp {}".format(timestamp)
cloud = process_irccam_img(f['CLOUDS'][idx])
cloud = np.nan_to_num(cloud, copy=False, nan=0.0)
cloud[cloud != 0] = 1
return cloud
from cloudseg.datasets.masking import apply_full_mask
def predict(model, input):
pred = model.model(input.unsqueeze(0))
pred = torch.argmax(pred, 1).squeeze().numpy()
apply_full_mask(pred, fill=0)
return pred
trans = transforms.Compose([transforms.ToTensor(),])
def transform(irc_raw, clear_sky):
np.nan_to_num(irc_raw, copy=False, nan=255.0)
irc = irc_raw - clear_sky
# Scale to [0,1]
mi = -30
ma = 100
np.nan_to_num(irc, copy=False, nan=mi)
irc[irc_raw == 255] = mi
irc[irc < mi] = mi
irc[irc > ma] = ma
irc -= mi
irc /= ma - mi
return trans(irc)
def get_data_and_pred(model, ts):
irc = get_irc_img(ts)
cs = get_clear_sky(ts)
irc = transform(irc, cs)
pmod_label = get_pmod_label(ts)
pred = predict(model, irc)
return [irc.squeeze(), pred, pmod_label, ts]
model.eval()
results = [get_data_and_pred(model, i)[:3] for i in timestamps]
plot_results(results)
```
| github_jupyter |
# Data Preparation I
*Note: this notebook is the complete (wordy) version of the [slide-oriented notebook](https://drive.google.com/file/d/1EOSzX3u4fyvYyHWzdM0WhQCduJnq8YkJ/view?usp=sharing) shown in lecture.*
Data preparation is a *very* broad subject, covering everything from data models to statistical assessments of data to string algorithms to scalable data processing. In some sense, most of Data Engineering---most of data science!---boils down to Data Preparation.
In today's first lecture we'll cover a few key topics:
1. Data "Unboxing": parsing & structure assessment
2. Structural Data Transformations
3. Type Induction/Coercion
4. String Manipulation
## 1. "Unboxing" Data
Recall some basic tools:
- `du -h`: show the disk size of a file in human-readable form
- `head -c 1024`: show me the first 1024 bytes of a file
- your eyes: in addition to being the window to your soul, they're a very common tool for understanding data
### Assessing Structure
Start by running `du -h` and `head -c 1024` on some files, or have a peek in your Finder/Explorer and favorite (scale-savvy) text editor.
1. Look out for header info, metadata, comments, etc.
- They may be inline, or in external documentation, "data dictionaries", etc.
2. Most files you'll run across fall into one of these categories:
1. **Record per line**: newline-delimited rows of uniform symbol-delimited data.
- E.g. `csv` and `tsv` files
- Also newline-delimited rows of uniform but ad-hoc structured text
2. **Dictionaries/Objects**: explicit key:value pairs, may be nested! Two common cases:
- Object-per-line: e.g. newline-delimited rows of JSON, XML, YAML, etc. (JSON in this format is sometimes called [json lines or jsonl](https://jsonlines.org/)).
- Complex object: the entire dataset is one fully-nested JSON, XML or YAML object
3. **Unions**: a mixture of rows from *k* distinct schemas. Two common cases:
- *Tagged Unions*: each row has an ID or name identifying its schema. Often the tag is in the first column.
- *Untagged Unions*: the schema for the row must be classified by its content
4. **Natural Language (prose)**: A lot of data files are mostly or entirely natural language intended for human consumption.
5. **Everything else**: There is a long tail of file formats in the world. If they're not readable as text, there's likely a commercial or open source tool to translate them to a readable text format.
One final note: text formats themselves are a complex issue. Traditionally there were two encodings of roman-alphabet characters: EBCDIC and ASCII. ASCII mostly won. But in our multilingual world, we now deal with characters from multiple languages and beyond 😟! There are many character encodings now. We won't dwell on this subject in this class, but some day you may have to be aware of issues like Unicode, UTF-8 and more. You can search the web for resources on these issues.
For the rest of this class, we will focus on the common case of text that can be read and written easily in tools like Jupyter, Python, PostgreSQL, etc.
### Examples
Without further ado, let's unbox some data!
```
!du -h data/*
!head -c 1024 data/jc1.txt
```
What category of data is the file above? Any observations about the data?
Let's look at another
```
!head -c 1024 data/jq2.txt
```
What do you see this time? Category? Interesting features of the data?
Keep in mind: this process is a form of *data visualization*: just because it's not pretty graphs doesn't mean you aren't interpreting the data based on a visual representation! This happens to a be a text-based visualization, but be aware of the power and biases of your eyeballs and cognition. You are probably making all kinds of assumptions based on what your eyeballs are sensing! Mostly good, I'm sure. But you're working with limited information given this fairly lean data visualization.
### Richer Visualizations and Low-Code Interaction in Trifacta
In DS100 you learned a bit about how to use pandas and some python graphing packages, and you could definitely use those skills to ingest and plot this data. But to move things along more quickly, let's load this into a purpose-built visual data preparation tool called [Trifacta](cloud.trifacta.com), also known as [Google Cloud Dataprep](https://cloud.google.com/dataprep). This is a visual environment for "low-code" dataprep that is the commercialization of joint research at Berkeley and Stanford in the [Wrangler](http://vis.stanford.edu/wrangler/) and [Potter's Wheel](http://control.cs.berkeley.edu/abc) projects.
We could simply drag-and-drop our files into the Trifacta web UI, but to stick with our familiar Jupyter notebook we can instead use Trifacta's Python library to pop open Trifacta at will. We may have to be a bit patient as Trifacta uploads the data to the cloud. The `tf.wrangle` call will upload the data and return a "flow" object from Trifacta. We can then call the `open()` method on that flow object to open the Trifacta UI in a new browser tab.
```
import trifacta as tf
import pandas as pd
jc1 = tf.wrangle('data/jc1.txt')
jc1.open()
```
In Trifacta you see more data visualizations---including visualizations of some analyses. What do you see that's different? What do you see that's additional?
### Let's Look at More Files!
OK, moving on to another file. How would you describe this one?
```
!head -c 1024 data/mm.txt
```
Looks like a matrix! When we get "rectangular" data, we should be able to distinguish whether it's in (dense) matrix form, or in a relational form.
How does that differ from the next file?
```
!head -c 1024 data/mmp.txt
```
And how about this one?
```
!head -c 1024 data/mmr.txt
```
## 2. Structural Transformation: From Relations to Matrices and Back
We discussed in class last time that we can convert matrices to relations, and that we can convert some conveniently-formed relations to matrices. Pivot/Unpivot can be confusing in the abstract, but it's easy to understand visually. So we'll learn it in Trifacta.
To start, let's take our matrix in `mm.txt`, and load it into Trifacta.
```
mm = tf.wrangle('data/mm.txt')
```
Now let's use Trifacta to convert it to a relation, with one row for each (year, month, value) triple. This is called an "UNPIVOT" operation, and you'll find an icon for it in Trifacta: it looks like an arrow swiveling down from column *headers* to a new column: <img src="files/unpivot.png"> Click on that icon and you'll get a dialog to choose the columns to unpivot.
But for now we'll use an alternative "no-code" technique: Simply click on the header of the `OCT` column, then scroll all the way to the right and shift-click on the header of the `SEP` column. 12 columns should be highlighted in blue, *and a list of suggested transformations should pop up on the right-hand-side of the screen*. You can mouse over these to see what they would do, but eventually click on the suggestion to `Unpivot columns into rows`. You will get a split-screen preview of the result, which should look right. Click `Add` to accept the suggestion. You should now see one grid of data, transformed the way we like. You will also now see a natural-language summary of the "Recipe" (script) that Trifacta is tracking---note that it did some work automatically before we unpivoted, and included it in the recipe in case we want to override it.
Once you're done unpivoting, you can close the Trifacta tab if you like and return here---Trifacta will save your work to call `mm.open()` again later. Or you can leave that tab open and click back and forth.
```
mm.open()
```
So UNPIVOT translates matrices in relations. As you might expect, PIVOT translates relations into matrices! Let's do that to our result in Trifacta. Open `mm` in Trifacta again, and this time let's use the PIVOT menu item: <img src="files/pivot.png"> For variety, let's flip things so the row labels are months, and the column labels are years.
What familiar matrix operation was achieved by this pair of UNPIVOT followed by PIVOT?
```
mm.open()
```
### Extra Columns
Now, as an exercise, load up that more complex version of the dataset in `mmp.txt` that we looked at above. Is it a matrix or relation? What's going on? Try doing some PIVOT/UNPIVOT work in Trifacta on your own. Feel free to play with the data, and the Trifacta interface.
```
mmp = tf.wrangle('data/mmp.txt')
mmp.open()
```
### Duplicate Entries and Aggregation
This time let's load up a slightly different version of this data in relational form from the `mmr.txt` file, and PIVOT it into `year`x`month` form.
```
mmr = tf.wrangle('data/mmr.txt')
```
Once again, we'd like to PIVOT this data into matrix form, with rows labeled by `year`, and columns labeled by `month`. Click the PIVOT icon and go to it! What problem do we face that we didn't see before?
Well, the header above gives it away: we have many rows that have the same `(year, month)` pair, which means our PIVOT needs to pack many values into a single cell. To do this, Trifacta asks us to choose an aggregate function -- a reasonable choice might be `AVERAGE({Inches of Precipitation})`. If you prefer, Trifacta (like Postgres) actually has an aggregate function that will just store a nested list (array) of all the values in a single cell---this is the `LIST` aggregate. Play with it and see what you get!
```
mmr.open()
```
### Spreadsheets
As an exercise on your own, load this data into a spreadsheet and play with PIVOT/UNPIVOT in the spreadsheet. Beware that some spreadsheets only support PIVOT but not UNPIVOT: Excel on Mac is an example. (Excel on Windows supports UNPIVOT, but you have to go into the "PowerQuery" interface to do it.)
### PIVOT/UNPIVOT and the Relational Model??!
We can do PIVOT/UNPIVOT in Trifacta, in Pandas, and in Spreadsheets. But can we do it in SQL?
Before we answer that question, let's go to the foundations. Can we do this in Relational Algebra?
Here the answer is a resounding *no*. Think about how we declare column values in relational algebra: we write an expression like $\pi_{c1, c2, c3}(T)$. The subscripts of the $\pi$ operator are part of the *syntax* of your relational expression---they *do not change* as the relation instance (the data in the database!) changes.
By contrast, for PIVOT the subscript of the $\pi$ operator essentially needs to be "the set of distinct values in the relation instance", which *absolutely changes* as the relation instances changes. Similarly, UNPIVOT returns data values (an output instance) that come from the input *schema* which isn't allowed.
*If you don't know what First Order Logic is, no sweat: you can safely skip this paragraph!*
UNPIVOT hints at what's going on here. Relational languages are based on First Order Logic, in which the EXISTS and FORALL quantifiers range over the data in the instance. By contrast, UNPIVOT somehow has a quantifier that ranges over the variable (column) names. Logics that quantify over variable names are called Second Order Logic. They are strictly more expressive than First Order Logic, and as such also more computationally complex.
Anyhow, "pure" SQL as we've learned it---an equivalent to the relational algebra---shouldn't be able to express PIVOT or UNPIVOT. However, given how useful this is, many SQL systems have (proprietary) extensions. They are often called PIVOT/UNPIVOT, though in Postgres the extension is called [crosstab](https://www.postgresql.org/docs/current/tablefunc.html).
### What about performance and scale
Have you ever seen a table with 10 million rows? Sure! Have you ever seen one with 10 million columns?
Many database systems and other data tools scale wonderfully in the number of rows, but lay an egg if you generate too many columns, or simply prevent you from doing so. There are exceptions to this rule, but it's a very common limitation. It's also sensible from a user experience perspective: wide tables are unwieldy to query (imagine almost any SELECT clause other than `SELECT *`!) Some tools like Trifacta will truncate your PIVOTs (and related operators that generate new columns) to prevent disasters, but the result is often non-deterministic in terms of which columns get added and which don't.
Mathematically, "wide matrices" can also be unattractive. A wide matrix is basically a set of *very* high-dimensional vectors, and high dimensionality is traditionally hard in statistics (the so-called [curse of dimensionality](https://en.wikipedia.org/wiki/Curse_of_dimensionality)). However in Machine Learning in recent years, high dimensionality has become more useful---in part because massive real-world data sets aren't uniformly distributed in the high-dimensional spaces that cause the curse. In essence, in real-world data there's some lower-dimensional embedding latent in most real-world data, but modern ML techniques can kind of find it. We will come back to this point later.
## 3. Type Induction and Coercion
To begin let's review "statistical" data types. This is a slight refinement from the terms in DS100:
- *nominal* / *categorical*: types that have no inherent ordering, used as names for categories
- *ordinals*: types that are used to encode order. Typically the integers $1, 2, \ldots$
- *cardinals*: types that are used to express cardinality ("how many"). Typically the integers $0,1,\ldots$. Cardinals are common as the output of statistics (frequencies).
- *numerical* / *measures*: types that capture a numerical value or measurement. Typically a real (floating point) number.
### Data types in the wild
We've seen that some systems like databases keep data types as metadata, and enforce strong typing in storage when data is inserted or modified. Used carefully, databases will carry the data-type metadata along with the data when they communicate with tools or other databases.
But it's very, very common to work with data that has little or no metadata. In that case, we *have* to interpret the data somehow. As a very first step, we need to guess ("induce") types for the data.
### Techniques for Type Induction
Suppose I give you a column of potentially dirty data. Suppose you have a set of types H. You need to write an algorithm to choose a type. How does it choose?
- "Hard" Rules: E.g. Occam's razor.
- Try types from most- to least-specific. (e.g. boolean, int, float, string)
- Choose the first one that matches *all* the values.
- Minimum Description Length (MDL): See below
- Classification (i.e. Supervised Learning): You know how this goes.
#### MDL
Intuition is similar to Occam's razor, but accounts for the "weight" or "penalty" of encoding exceptions to the best type. The "fitness" of a type to some data is the description length of the data using that type---including the cost of "explicitly" storing the data that doesn't fit the type as a string. Let's say $len(v)$ is the bit-length for encoding of a value $v$ "explicitly". Given a type $T$ with $|T|$ distinct values, the bit-length of encoding a value in that type is $log|T|$. (E.g. there are $2^64$ 64-bit integers, and each one is $log(2^64)=64$ bits long.)
Let's say that indicator variable $I_T(v) = 1$ if $v \in T$, and $0$ otherwise.
For MDL, we choose the type that minimizes the description length for the set of data $c$ in a column:
$$\min_{T \in H} \sum_{v \in c}(I_T(v)log(|T|) + (1-I_T(v))len(v))$$
Consider a "column" of values: $\{\mbox{'Joe'}, 2, 12, 4750\}$. Assume the default type is "string", which costs us 8 bits per character.
- We can encode this as 3 16-bit integers and 'Joe': length is $3*16 + 3*8 = 72$
- Or we can encode it all as strings: $(3 + 1 + 2 + 4)*8 = 80$.
MDL would favor "int16" over "string" in this example.
Note that one can enhance MDL in various ways. One approach that's interesting to consider is to induce *compound* types: i.e. the string "12/31/2021" could be *string* or *date* or a compound type like *int4 '/' int8 '/' int16*. Another approach is to use compression techniques to get tighter measures for the length of encoding---for both type-matches and for strings.
#### In practice
Some systems will break if the chosen type doesn't fit all the data in the column, in which case they'll choose a "hard rules" approach. For systems that can handle a mix of types, something like MDL is not unusual, though it may be more naive (e.g. pick the type that matched the largest number of entries).
### Type Coercion/Casting
You can explicitly set the type of a column. If the column has values that don't match the type, you will have to live with a lossy representation of those values (often NULL).
Typecasting can be useful for ensuring that a system treats your type right *statistically*. For example, ID columns are often arbitrary integers. These are not really numeric columns, they're categorical. To ensure the system/processes don't get confused, you can cast them to strings.
## 4. String Manipulation
I don't have a lot to add here that wasn't already covered in DS100 and SQL.
- Typical transforms include the following (names may vary across systems/DSLs):
- **Split** a string into separate rows/columns
- Often by position or delimiter
- Sometimes via parsing: e.g. counting nested parentheses (e.g. JSON/XML rowsplits)
- **CountMatches**: Create a new column with the count of matches of a pattern in a string column
- **Extract**: create a column of substrings derived from another column
- **Replace**: a (sub)string with a constant, a "captured group", or any string formula (e.g. lowercase, trim, etc)
- Facility with regular expressions goes a VERY long way.
- All of these can be done directly in SQL
## Cleaning The Real Data
The previous few files were the results of wrangling a raw dataset. Let's look at that dataset now! It's a scrape of [rainfall data](https://www.cnrfc.noaa.gov/monthly_precip_2020.php) from the website of the National Oceanic and Atmospheric Administration (NOAA).
```
!head -c 1024 data/mpf.txt
```
Looks kinda messy. You can play with it in bash or pandas if you like. Since it's pretty nasty we'll clean it up in Trifacta. This will illustrate some of the benefits of having tooling at hand that combines live visualization with AI-based recommendations (software synthesis) to speed you on your way. In essence, we are leveraging computer science techniques (HCI, AI, Database languages) to reduce the work needed to do data science!
```
mpf = tf.wrangle('data/mpf.txt')
mpf.open()
```
| github_jupyter |
```
import lux
```
This notebook is originally derived from [this notebook on Kaggle](https://www.kaggle.com/dgomonov/data-exploration-on-nyc-airbnb).
```
# {{NO LUX}}
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
import pandas as pd
numPoints=100
# {{NO LUX}}
airbnb=pd.read_csv("../../data/airbnb_250x.csv")
# airbnb=pd.read_csv("../../data/airbnb_nyc.csv")
airbnb = airbnb.sample(n=int(numPoints))
airbnb.compute_meta_recs()
# {{NO LUX}}
airbnb.dtypes
airbnb.compute_meta_recs()
# {{PRINT SERIES}}
airbnb.isnull().sum()
# {{NO LUX}}
airbnb.drop(['id','host_name','last_review'], axis=1, inplace=True)
airbnb.compute_meta_recs()
# {{PRINT DF}}
airbnb
# {{PRINT DF}}
airbnb.fillna({'reviews_per_month':0}, inplace=True)
airbnb.reviews_per_month.isnull().sum()
# {{PRINT DF}}
airbnb
# {{NO LUX}}
airbnb.neighbourhood_group.unique()
airbnb.compute_meta_recs()
# {{PRINT DF}}
airbnb
# {{NO LUX}}
len(airbnb.neighbourhood.unique())
airbnb.compute_meta_recs()
# {{NO LUX}}
airbnb.room_type.unique()
airbnb.compute_meta_recs()
# {{NO LUX}}
top_host=airbnb.host_id.value_counts()
airbnb.compute_meta_recs()
# {{PRINT SERIES}}
top_host
# {{NO LUX}}
top_host_check=airbnb.calculated_host_listings_count.max()
airbnb.compute_meta_recs()
# {{PRINT SERIES}}
top_host_check
# {{NO LUX}}
top_host_df=pd.DataFrame(top_host)
top_host_df.reset_index(inplace=True)
top_host_df.rename(columns={'index':'Host_ID', 'host_id':'P_Count'}, inplace=True)
airbnb.compute_meta_recs()
# {{PRINT DF}}
top_host_df
# {{NO LUX}}
sub_1=airbnb.loc[airbnb['neighbourhood_group'] == 'Brooklyn']
price_sub1=sub_1[['price']]
sub_2=airbnb.loc[airbnb['neighbourhood_group'] == 'Manhattan']
price_sub2=sub_2[['price']]
sub_3=airbnb.loc[airbnb['neighbourhood_group'] == 'Queens']
price_sub3=sub_3[['price']]
sub_4=airbnb.loc[airbnb['neighbourhood_group'] == 'Staten Island']
price_sub4=sub_4[['price']]
sub_5=airbnb.loc[airbnb['neighbourhood_group'] == 'Bronx']
price_sub5=sub_5[['price']]
price_list_by_n=[price_sub1, price_sub2, price_sub3, price_sub4, price_sub5]
airbnb.compute_meta_recs()
# {{PRINT DF}}
sub_1
# {{PRINT DF}}
sub_5
# {{PRINT SERIES}}
price_sub5
# {{PRINT DF}}
airbnb
# {{NO LUX}}
p_l_b_n_2=[]
nei_list=['Brooklyn', 'Manhattan', 'Queens', 'Staten Island', 'Bronx']
for x in price_list_by_n:
i=x.describe(percentiles=[.25, .50, .75])
i=i.iloc[3:]
i.reset_index(inplace=True)
i.rename(columns={'index':'Stats'}, inplace=True)
p_l_b_n_2.append(i)
airbnb.compute_meta_recs()
# {{NO LUX}}
p_l_b_n_2[0].rename(columns={'price':nei_list[0]}, inplace=True)
p_l_b_n_2[1].rename(columns={'price':nei_list[1]}, inplace=True)
p_l_b_n_2[2].rename(columns={'price':nei_list[2]}, inplace=True)
p_l_b_n_2[3].rename(columns={'price':nei_list[3]}, inplace=True)
p_l_b_n_2[4].rename(columns={'price':nei_list[4]}, inplace=True)
stat_df=p_l_b_n_2
stat_df=[df.set_index('Stats') for df in stat_df]
stat_df=stat_df[0].join(stat_df[1:])
airbnb.compute_meta_recs()
# {{PRINT DF}}
stat_df
# {{PRINT DF}}
airbnb
# {{PRINT SERIES}}
airbnb.price
# {{NO LUX}}
sub_6=airbnb[airbnb.price < 500]
airbnb.compute_meta_recs()
# {{PRINT DF}}
sub_6
# {{PRINT SERIES}}
viz_2=sns.violinplot(data=sub_6, x='neighbourhood_group', y='price')
viz_2.set_title('Density and distribution of prices for each neighberhood_group')
# {{PRINT DF}}
airbnb
# {{PRINT SERIES}}
airbnb.neighbourhood.value_counts()
# {{NO LUX}}
sub_7=airbnb.loc[airbnb['neighbourhood'].isin(['Williamsburg','Bedford-Stuyvesant','Harlem','Bushwick',
'Upper West Side','Hell\'s Kitchen','East Village','Upper East Side','Crown Heights','Midtown'])]
airbnb.compute_meta_recs()
# {{PRINT DF}}
sub_7
# {{NO LUX}}
top_reviewed_listings=airbnb.nlargest(10,'number_of_reviews')
airbnb.compute_meta_recs()
# {{PRINT DF}}
top_reviewed_listings
# {{NO LUX}}
price_avrg=top_reviewed_listings.price.mean()
print('Average price per night: {}'.format(price_avrg))
airbnb.compute_meta_recs()
```
| github_jupyter |
```
# Import libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
import nltk
import string
import re
%matplotlib inline
df1=pd.read_csv("train.csv")
print(df1.shape)
df1.head()
df1.info()
sns.countplot(x='original_author', hue="sentiment_class", data = df1)
sns.countplot( x="sentiment_class", data = df1)
print(df1.lang.nunique())
df1.lang.unique()
print(df1.original_author.nunique())
df1.original_author.unique()
df1.isnull().sum()
y=df1['sentiment_class']
y.shape
```
*** ***
***retweet_count***
```
print(df1.retweet_count[0])
isinstance(df1.retweet_count[1], (str))
print(df1.retweet_count.nunique())
df1.retweet_count.unique()
rc=df1['retweet_count']
rc
def convertible(v):
try:
int(v)
return True
except (TypeError, ValueError):
return False
res = [int(ele) if convertible(ele) else int(0) for ele in rc]
res
res=pd.DataFrame(res)
res.head()
print(res[0].nunique())
res[0].unique()
df1['retweet_count']=res[0]
df1['retweet_count'].unique()
```
** **
***Orginal_author***
```
print(df1.original_author.nunique())
df1.original_author.unique()
oa=df1['original_author']
oa
def convertibles(v):
try:
float(v)
return True
except (TypeError, ValueError):
return False
res2 = [str('unkn') if convertibles(ele) else ele for ele in oa]
res2
res2=pd.DataFrame(res2)
print(res2[0].nunique())
res2[0].unique()
df1['original_author']=res2[0]
df1['original_author'].nunique()
```
** **
**test_data**
```
df2=pd.read_csv("test.csv")
print(df2.shape)
df2.head()
print(df2.retweet_count.nunique())
df2.retweet_count.unique()
rct=df2['retweet_count']
rct
def convertible(v):
try:
int(v)
return True
except (TypeError, ValueError):
return False
rest = [int(ele) if convertible(ele) else int(0) for ele in rct]
rest
rest=pd.DataFrame(rest)
rest.head()
print(rest[0].nunique())
rest[0].unique()
df2['retweet_count']=rest[0]
df2['retweet_count'].unique()
```
** **
```
print(df2.original_author.nunique())
#df2.original_author.unique()
oat=df2['original_author']
oat
def convertibles(v):
try:
float(v)
return True
except (TypeError, ValueError):
return False
rest2 = [str('unkn') if convertibles(ele) else ele for ele in oat]
rest2
rest2=pd.DataFrame(rest2)
print(rest2[0].nunique())
#rest2[0].unique()
df2['original_author']=rest2[0]
df2['original_author'].nunique()
```
** **
```
print(df1.head())
df1.info()
print(df2.head())
df2.info()
np.intersect1d([1,2,3,1,4,3,5,7], [1,3,4,6]) #testing
com=np.intersect1d(df1.original_author, df2.original_author)
com.shape #246 common in(1528-736)
```
** **
***tweets***
```
x1=df1['original_text']
print(x1.shape)
x1.head
x2=df2['original_text']
print(x2.shape)
x2.tail()
x=pd.concat([x1,x2],axis=0)
x=pd.DataFrame(x)
x.reset_index(inplace=True)
x=x['original_text']
x=pd.DataFrame(x)
print(x.shape)
x.tail()
```
**Data cleaning**
```
def remove_pattern1(input_txt, pattern):
r = re.findall(pattern, input_txt)
for i in r:
input_txt = re.sub(i, '', input_txt)
return input_txt
# remove twitter handles (@user)
x['tidy_tweet'] = np.vectorize(remove_pattern1)(x['original_text'], "@[\w]*")
x.head()
```
**removing links and mentions**
```
def remove_pattern(pattern):
for i in range(x['tidy_tweet'].shape[0]):
twt=x['tidy_tweet'][i]
res=twt.split(pattern, maxsplit=1)
x['tidy_tweet'][i]=res[0]
remove_pattern('http')
remove_pattern('pic.twitter')
x.head
x['original_text'][7]
x['tidy_tweet'][7]
```
** **
**NLTK**
```
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 4622):
review = re.sub('[^a-zA-Z]', ' ',x['tidy_tweet'][i])
review = review.lower()
review = review.split()
ps = PorterStemmer()
review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
review = ' '.join(review)
corpus.append(review)
corpus[2]
x['tidy_tweet'][2]
```
** **
**Embedding Representation**
```
from tensorflow.keras.layers import Embedding
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from keras import utils
from tensorflow.keras.preprocessing.text import one_hot
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout
voc_size=5000
onehot_repr=[one_hot(words,voc_size)for words in corpus]
sent_length=40
embedded_docs=pad_sequences(onehot_repr,padding='pre',maxlen=sent_length)
print(embedded_docs)
embedded_docs[10]
import numpy as np
X_=np.array(embedded_docs)
print(X_.shape)
```
** **
```
f1=df1[['retweet_count','original_author']]
print(f1.shape)
f1.head()
f2=df2[['retweet_count','original_author']]
print(f2.shape)
f2.head()
f=pd.concat([f1,f2],axis=0)
f.reset_index(inplace=True)
f=f.drop("index",axis=1)
print(f.shape)
f.head()
f=pd.get_dummies(f, prefix=['original_author'])
print(f.shape)
X_pd=pd.DataFrame(X_)
X=pd.concat([X_pd,f],axis=1)
X.reset_index(inplace=True)
X=X.drop("index",axis=1)
print(X.shape)
X.tail()
xtrain=X.iloc[:3235,: ].values
xtest=X.iloc[3235:,: ].values
print(xtrain.shape)
xtest.shape
from sklearn.model_selection import train_test_split
X_train, X_val, y_train, y_val = train_test_split(xtrain,y ,test_size=0.15, random_state=0)
```
**svm**
```
from sklearn.svm import SVC
classifier1 = SVC(kernel = 'poly', random_state = 0, degree=4,C=10)
classifier1.fit(X_train, y_train)
from sklearn.model_selection import cross_val_score
acc=cross_val_score(estimator=classifier1, X=X_train, y=y_train , cv=10)
print(acc.mean())
print(acc.std())
acc
y_pred1 = classifier1.predict(X_val)
y_pred1.shape
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_val, y_pred1)
cm
array([[ 21, 89, 7],
[ 30, 190, 23],
[ 10, 101, 15]])
'''from sklearn.model_selection import GridSearchCV
parameters = [{'C':[15,10]}] #svm-2
grid_search = GridSearchCV(estimator = classifier1,
param_grid = parameters,
scoring = 'accuracy',
cv = 10,
n_jobs = -1)
grid_search = grid_search.fit(x, y)
best_accuracy = grid_search.best_score_
best_parameters = grid_search.best_params_
print('done')
print(best_accuracy)
best_parameters'''
226/486
y_pred2 = classifier1.predict(xtest)
y_pred2.shape
ID=df2['id']
ID.shape
pred=pd.DataFrame(y_pred2)
datasets=pd.concat([ID,pred], axis=1)
datasets.columns =['id', 'sentiment_class']
datasets.to_csv('asvm3.csv',index=False)
!cp asvm3.csv "drive/My Drive/"
print(pred[0].value_counts())
sns.countplot( x=-pred[0], data = pred)
```
** **
```
from xgboost import XGBClassifier
classifier4=XGBClassifier(n_estimators=600,reg_lambda=0.1 ,max_depth=4,seed=42,learning_rate=0.1,tree_method='gpu_exact',colsample_bytree=0.9)
classifier4.fit(X_train, y_train)
from sklearn.model_selection import cross_val_score
acc=cross_val_score(estimator=classifier4, X=X_train, y=y_train , cv=10)
print(acc.mean())
print(acc.std())
acc
y_pred1 = classifier4.predict(X_val)
print(y_pred1.shape)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_val, y_pred1)
cm
array([[ 9, 97, 11],
[ 19, 192, 32],
[ 17, 88, 21]])
y_pred2 = classifier4.predict(xtest)
y_pred2.shape
ID=df2['id']
ID.shape
pred=pd.DataFrame(y_pred2)
datasets=pd.concat([ID,pred], axis=1)
datasets.columns =['id', 'sentiment_class']
datasets.to_csv('axg23.csv',index=False)
!cp axg23.csv "drive/My Drive/"
print(pred[0].value_counts())
sns.countplot( x=pred[0], data = pred)
```
| github_jupyter |
```
%%html
<link href="http://mathbook.pugetsound.edu/beta/mathbook-content.css" rel="stylesheet" type="text/css" />
<link href="https://aimath.org/mathbook/mathbook-add-on.css" rel="stylesheet" type="text/css" />
<style>.subtitle {font-size:medium; display:block}</style>
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400italic,600,600italic" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Inconsolata:400,700&subset=latin,latin-ext" rel="stylesheet" type="text/css" /><!-- Hide this cell. -->
<script>
var cell = $(".container .cell").eq(0), ia = cell.find(".input_area")
if (cell.find(".toggle-button").length == 0) {
ia.after(
$('<button class="toggle-button">Toggle hidden code</button>').click(
function (){ ia.toggle() }
)
)
ia.hide()
}
</script>
```
**Important:** to view this notebook properly you will need to execute the cell above, which assumes you have an Internet connection. It should already be selected, or place your cursor anywhere above to select. Then press the "Run" button in the menu bar above (the right-pointing arrowhead), or press Shift-Enter on your keyboard.
$\newcommand{\identity}{\mathrm{id}}
\newcommand{\notdivide}{\nmid}
\newcommand{\notsubset}{\not\subset}
\newcommand{\lcm}{\operatorname{lcm}}
\newcommand{\gf}{\operatorname{GF}}
\newcommand{\inn}{\operatorname{Inn}}
\newcommand{\aut}{\operatorname{Aut}}
\newcommand{\Hom}{\operatorname{Hom}}
\newcommand{\cis}{\operatorname{cis}}
\newcommand{\chr}{\operatorname{char}}
\newcommand{\Null}{\operatorname{Null}}
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
$
<div class="mathbook-content"><h2 class="heading hide-type" alt="Exercises 11.4 Additional Exercises: Automorphisms"><span class="type">Section</span><span class="codenumber">11.4</span><span class="title">Additional Exercises: Automorphisms</span></h2><a href="homomorph-exercises-automorphisms.ipynb" class="permalink">¶</a></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-406"><h6 class="heading"><span class="codenumber">1</span></h6><p id="p-1782">Let $\aut(G)$ be the set of all automorphisms of $G\text{;}$ that is, isomorphisms from $G$ to itself. Prove this set forms a group and is a subgroup of the group of permutations of $G\text{;}$ that is, $\aut(G) \leq S_G\text{.}$</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-407"><h6 class="heading"><span class="codenumber">2</span></h6><p id="p-1783">An <dfn class="terminology">inner automorphism</dfn> of $G\text{,}$</p><div class="displaymath">
\begin{equation*}
i_g : G \rightarrow G,
\end{equation*}
</div><p>is defined by the map</p><div class="displaymath">
\begin{equation*}
i_g(x) = g x g^{-1},
\end{equation*}
</div><p>for $g \in G\text{.}$ Show that $i_g \in \aut(G)\text{.}$</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-408"><h6 class="heading"><span class="codenumber">3</span></h6><p id="p-1784">The set of all inner automorphisms is denoted by $\inn(G)\text{.}$ Show that $\inn(G)$ is a subgroup of $\aut(G)\text{.}$</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-409"><h6 class="heading"><span class="codenumber">4</span></h6><p id="p-1785">Find an automorphism of a group $G$ that is not an inner automorphism.</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-410"><h6 class="heading"><span class="codenumber">5</span></h6><p id="p-1786">Let $G$ be a group and $i_g$ be an inner automorphism of $G\text{,}$ and define a map</p><div class="displaymath">
\begin{equation*}
G \rightarrow \aut(G)
\end{equation*}
</div><p>by</p><div class="displaymath">
\begin{equation*}
g \mapsto i_g.
\end{equation*}
</div><p>Prove that this map is a homomorphism with image $\inn(G)$ and kernel $Z(G)\text{.}$ Use this result to conclude that</p><div class="displaymath">
\begin{equation*}
G/Z(G) \cong \inn(G).
\end{equation*}
</div></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-411"><h6 class="heading"><span class="codenumber">6</span></h6><p id="p-1787">Compute $\aut(S_3)$ and $\inn(S_3)\text{.}$ Do the same thing for $D_4\text{.}$</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-412"><h6 class="heading"><span class="codenumber">7</span></h6><p id="p-1788">Find all of the homomorphisms $\phi : {\mathbb Z} \rightarrow {\mathbb Z}\text{.}$ What is $\aut({\mathbb Z})\text{?}$</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-413"><h6 class="heading"><span class="codenumber">8</span></h6><p id="p-1789">Find all of the automorphisms of ${\mathbb Z}_8\text{.}$ Prove that $\aut({\mathbb Z}_8) \cong U(8)\text{.}$</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-414"><h6 class="heading"><span class="codenumber">9</span></h6><p id="p-1790">For $k \in {\mathbb Z}_n\text{,}$ define a map $\phi_k : {\mathbb Z}_n \rightarrow {\mathbb Z}_n$ by $a \mapsto ka\text{.}$ Prove that $\phi_k$ is a homomorphism.</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-415"><h6 class="heading"><span class="codenumber">10</span></h6><p id="p-1791">Prove that $\phi_k$ is an isomorphism if and only if $k$ is a generator of ${\mathbb Z}_n\text{.}$</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-416"><h6 class="heading"><span class="codenumber">11</span></h6><p id="p-1792">Show that every automorphism of ${\mathbb Z}_n$ is of the form $\phi_k\text{,}$ where $k$ is a generator of ${\mathbb Z}_n\text{.}$</p></article></div>
<div class="mathbook-content"><article class="exercise-like" id="exercise-417"><h6 class="heading"><span class="codenumber">12</span></h6><p id="p-1793">Prove that $\psi : U(n) \rightarrow \aut({\mathbb Z}_n)$ is an isomorphism, where $\psi : k \mapsto \phi_k\text{.}$</p></article></div>
| github_jupyter |
```
import os
import sys
import subprocess
import collections
import time
import nbformat
import socket
import re
import pickle
import numpy as np
import sklearn.metrics
import torch
lib_path = 'I:/code'
if not os.path.exists(lib_path):
lib_path = '/media/6T/.tianle/.lib'
if not os.path.exists(lib_path):
lib_path = '/projects/academic/azhang/tianlema/lib'
if os.path.exists(lib_path) and lib_path not in sys.path:
sys.path.append(lib_path)
from dl.utils.visualization.visualization import *
from dl.utils.train import eval_classification, get_label_prob
from dl.utils.utils import *
%load_ext autoreload
%autoreload 2
def submit_job(model_type='nn', dense=False, residual=True, hidden_dim=[500, 500],
train_portion=0.7, val_portion=0.1, test_portion=0.2,
num_sets=10, num_folds=10, sel_set_idx=0,
num_train_types=-1,
num_val_types=-1,
num_test_types=-1,
cv_type='instance-shuffle',
sel_disease_types='all',
min_num_samples_per_type_cls=[100, 0],
predefined_sample_set_file='auto-search',
target_variable='PFI',
target_variable_type='discrete',
target_variable_range=[0, 1],
data_type=['gene', 'mirna', 'methy', 'rppa'],
additional_vars=[],#['age_at_initial_pathologic_diagnosis', 'gender']
additional_var_types=[],#['continuous', 'discrete']
additional_var_ranges=[],
normal_transform_feature=True,
randomize_labels=False,
lr=5e-4,
weight_decay=1e-4,
num_epochs=1000,
reduce_every=500,
show_results_in_notebook=True,
idx_folder='results/data_split_idx', # no longer used
notebook_folder='.',
template_file='exp_template.ipynb',
slurm_script='../gpu-slurm',
new_file=True, submit=True,
cell_idx=2, gpu_id=3):
"""Create notebook and run it on dlm or submit to ccr slurm
"""
# This is for filename
if sel_disease_types == 'all':
sel_disease_type_str = 'all'
else:
sel_disease_type_str = '-'.join(sorted(sel_disease_types))
if isinstance(data_type, str):
data_type_str = data_type
else:
data_type_str = '-'.join(sorted(data_type))
if model_type == 'nn': # model_type, dense, residual are dependent
assert not (residual and dense)
if residual:
model_type = 'resnet'
if dense:
model_type = 'densenet'
args = {'model_type': model_type, # model_type may be different from the argument
'dense': dense,
'residual': residual,
'hidden_dim': hidden_dim,
'train_portion': train_portion,
'val_portion': val_portion,
'test_portion': test_portion,
'num_sets': num_sets,
'num_folds': num_folds,
'num_train_types': num_train_types,
'num_val_types': num_val_types,
'num_test_types': num_test_types,
'cv_type': cv_type,
'sel_set_idx': sel_set_idx,
'sel_disease_types': sel_disease_types,
'min_num_samples_per_type_cls': min_num_samples_per_type_cls,
'predefined_sample_set_file': predefined_sample_set_file,
'target_variable': target_variable,
'target_variable_type': target_variable_type,
'target_variable_range': target_variable_range,
'data_type': data_type,
'additional_vars': additional_vars,#['age_at_initial_pathologic_diagnosis', 'gender']
'additional_var_types': additional_var_types,#['continuous', 'discrete']
'additional_var_ranges': additional_var_ranges,
'normal_transform_feature': normal_transform_feature,
'randomize_labels': randomize_labels,
'lr': lr,
'weight_decay': weight_decay,
'num_epochs': num_epochs,
'reduce_every': reduce_every,
'show_results_in_notebook': show_results_in_notebook
}
predefined_sample_set_filename = (target_variable if isinstance(target_variable,str)
else '-'.join(target_variable))
predefined_sample_set_filename += f'_{cv_type}'
if len(additional_vars) > 0:
predefined_sample_set_filename += f"_{'-'.join(sorted(additional_vars))}"
predefined_sample_set_filename += (f"_{data_type_str}_{sel_disease_type_str}_"
f"{'-'.join(map(str, min_num_samples_per_type_cls))}")
predefined_sample_set_filename += f"_{'-'.join(map(str, [train_portion, val_portion, test_portion]))}"
if cv_type == 'group-shuffle' and num_train_types > 0:
predefined_sample_set_filename += f"_{'-'.join(map(str, [num_train_types, num_val_types, num_test_types]))}"
predefined_sample_set_filename += f'_{num_sets}sets'
filename_prefix = f"{predefined_sample_set_filename}_{sel_set_idx}_{'-'.join(map(str, hidden_dim))}_{model_type}"
filename = f'{filename_prefix}.ipynb'
nb = nbformat.read(f'{notebook_folder}/{template_file}', 4)
nb['cells'][0]['source'] = ("import socket\nif socket.gethostname() == 'dlm':\n"
" %env CUDA_DEVICE_ORDER=PCI_BUS_ID\n"
f" %env CUDA_VISIBLE_DEVICES={gpu_id}")
nb['cells'][cell_idx]['source'] = '\n'.join(
[f"{k} = '{v}'" if isinstance(v, str) else f'{k} = {v}' for k, v in args.items()])
if os.path.exists(f'{notebook_folder}/{filename}'):
print(f'To overwrite file {notebook_folder}/{filename}')
else:
print(f'To create file {notebook_folder}/{filename}')
if new_file:
nbformat.write(nb, f'{notebook_folder}/{filename}')
if submit: # sometimes I just want to create files
if re.search('ccr.buffalo.edu$', socket.gethostname()):
command = f'sbatch {slurm_script} {notebook_folder}/{filename} {filename}'
subprocess.run(command, shell=True)
print(command)
else:
command = ['jupyter nbconvert', '--ExecutePreprocessor.timeout=360000',
'--ExecutePreprocessor.allow_errors=True', '--to notebook', '--execute']
command.append(f'{notebook_folder}/{filename} --output {filename}')
command = ' '.join(command)
start_time = time.time()
tmp = subprocess.run(command, shell=True)
end_time = time.time()
print(f'Time spent: {end_time-start_time:.2f}')
return filename_prefix
data_folder = '../../pan-can-atlas/data/processed'
if not os.path.exists(data_folder):
data_folder = 'F:/TCGA/Pan-Cancer-Atlas/data/processed'
with open(f'{data_folder}/sel_patient_clinical.pkl', 'rb') as f:
data = pickle.load(f)
disease_types = data['disease_types']
disease_type_dict = data['disease_type_dict']
pfi = data['pfi']
disease_stats = {}
for idx, name in disease_type_dict.items():
cnt = list(collections.Counter(pfi[disease_types==idx]).values())
if cnt[0] > 100 and cnt[1] > 100:
disease_stats[idx] = f'{name}: {cnt}'
print(name, idx, cnt)
# additional_vars=[],#['age_at_initial_pathologic_diagnosis', 'gender']
# additional_var_types=[],#['continuous', 'discrete']
# additional_var_ranges=[],
additional_vars = ['age_at_initial_pathologic_diagnosis', 'gender', 'ajcc_pathologic_tumor_stage']
additional_var_types = ['continuous', 'discrete', 'discrete']
additional_var_ranges = [[0, 100], ['MALE', 'FEMALE'],
['I/II NOS', 'IS', 'Stage 0', 'Stage I', 'Stage IA', 'Stage IB',
'Stage II', 'Stage IIA', 'Stage IIB', 'Stage IIC', 'Stage III',
'Stage IIIA', 'Stage IIIB', 'Stage IIIC', 'Stage IV', 'Stage IVA',
'Stage IVB', 'Stage IVC', 'Stage X']]
for i in ['all']:#[0, 1, 6, 8, 10, 11, 16, 17]:
for j in range(10):
for dtype in [['gene', 'mirna', 'rppa', 'methy']]:
submit_job(model_type='nn', dense=False, residual=False, hidden_dim=[100,100],
train_portion=0.7, val_portion=0.1, test_portion=0.2,
num_sets=10, num_folds=10, sel_set_idx=j,
num_train_types=-1,
num_val_types=-1,
num_test_types=-1,
cv_type='instance-shuffle',
sel_disease_types=i,
min_num_samples_per_type_cls=[100, 0],
predefined_sample_set_file='auto-search',
target_variable='DFI',
target_variable_type='discrete',
target_variable_range=[0,1],
data_type=dtype,
additional_vars=additional_vars,
additional_var_types=additional_var_types,
additional_var_ranges=additional_var_ranges,
normal_transform_feature=True,
randomize_labels=False,
lr=5e-4,
weight_decay=1e-4,
num_epochs=100,
reduce_every=500,
show_results_in_notebook=True,
idx_folder='results/data_split_idx', # no longer used
notebook_folder='.',
template_file='exp_template-mv-nn-v3.ipynb',
slurm_script='../run-slurm',
new_file=False, submit=False,
cell_idx=2, gpu_id=1)
def load_results(disease_type_str = '0', #0-1-6-8-10-11-16-17
model_name = 'ml',
sel_set_idx = 0,
data_type_str = 'gene-mirna-rppa-methy',
data_split_str = '70-10-20',
hidden_dim_str = '100-100',
filefolder = 'results',
target_variable = 'pfi',
return_variable='metric_all',
filename=None, plot_acc=True, plot_loss=True):
if filename is None:
filename = (f'{filefolder}/{disease_type_str}_{data_type_str}_set{sel_set_idx}'
f'_{data_split_str}_{target_variable}_{hidden_dim_str}_{model_name}.pkl')
with open(filename, 'rb') as f:
data = pickle.load(f)
if return_variable in data:
return np.array(data[return_variable])
metric = np.array(data['metric_all'])
confusion_mat = np.array(data['confusion_mat_all'])
model_names, split_names, metric_names = (data['model_names'], data['split_names'],
data['metric_names'])
# sanity check
assert metric.shape == (len(model_names), len(split_names), len(metric_names))
assert confusion_mat.shape[:2] == (len(model_names), len(split_names))
loss_his = data['loss_his_all']
acc_his = np.array(data['acc_his_all'])
title = disease_type_str if len(disease_type_str)>2 else disease_stats[int(disease_type_str)]
if plot_acc and len(acc_his)>0:
for i, n in enumerate(split_names):
plot_history(acc_his[:, i].T, title=f'{title} {n} acc',
indices=None, colors='rgbkmc', markers='ov+*,<',
labels=model_names, linestyles=['']*6, markersize=3)
for i, n in enumerate(model_names):
plot_history(acc_his[i].T, title=f'{title} {n} acc',
indices=None, colors='rgbkmc', markers='ov+*,<',
labels=split_names, linestyles=['']*6, markersize=3)
if plot_loss and len(loss_his)>0:
for i, n in enumerate(model_names):
history = np.array(loss_his[i])
if history.ndim == 2:
plot_history(history.T, title=f'{title} {n} loss', indices=None, colors='rgbkmc',
markers='ov+*,<',
labels=split_names, linestyles=['']*6, markersize=3)
elif history.ndim == 3:
for j in range(history.shape[2]):
plot_history(history[:,:,j].T, title=f'{title} {n} loss{j}', indices=None,
colors='rgbkmc', markers='ov+*,<',
labels=split_names, linestyles=['']*6, markersize=3)
else:
raise ValueError(f'{filename} {n} loss has unexpected shape')
if return_variable == 'all':
return metric, confusion_mat, model_names, split_names, metric_names, acc_his, loss_his
load_results(return_variable='metric_names',
filename=(f'results/PFI_instance-shuffle_gene-methy-mirna-rppa_all'
f'_100-0_0.7-0.1-0.2_10sets_0_100-100_nn.pkl'))
```
| github_jupyter |
# Visualization of DensePose-COCO dataset
In this notebook, we visualize the DensePose-COCO annotations on the images.
The densepose COCO dataset annotations are provided within the coco annotation framework and can be handled directly using the pycocotools.
<br>
<div align="center">
<img src="http://densepose.org/img/coords.png" width="400px" /><br>
_Visualization of the partitioning of the surface and demonstration of "correspondence to a single point on a part"._
</div>
### DensePose fields in annotations:
#### Collected Masks
* **'dp_masks' :** RLE encoded dense masks. All part masks are of size 256x256 and maps to 14 labels. Please note that these are not linked to the 3D template. These are semantically meaningful parts collected from annotators, we use these to sample annotation points.
#### Collected Points
* **'dp_x'**, **'dp_y' :** The spatial coordinates of collected points on the image. The coordinates are scaled such that the bounding box size is 256x256.
* **'dp_I' :** The patch index that indicates which of the 24 surface patches the point is on.
* **'dp_U'**, **'dp_V' :** Coordinates in the UV space. Each surface patch has a separate 2D parameterization.
In the following, we reshape the collected masks and points
```
from pycocotools.coco import COCO
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pycocotools.mask as mask_util
from random import randint
coco_folder = '../detectron/datasets/data/coco/'
dp_coco = COCO( coco_folder + '/annotations/densepose_coco_2014_minival.json')
```
Select a random image, read it and load the annotations that correspond to this image.
```
# Get img id's for the minival dataset.
im_ids = dp_coco.getImgIds()
# Select a random image id.
Selected_im = im_ids[randint(0, len(im_ids))] # Choose im no 57 to replicate
# Load the image
im = dp_coco.loadImgs(Selected_im)[0]
# Load Anns for the selected image.
ann_ids = dp_coco.getAnnIds( imgIds=im['id'] )
anns = dp_coco.loadAnns(ann_ids)
# Now read and b
im_name = os.path.join( coco_folder + 'val2014', im['file_name'] )
I=cv2.imread(im_name)
plt.imshow(I[:,:,::-1]); plt.axis('off'); plt.show()
```
## Visualization of Collected Masks
Let's visualize the collected masks on the image.
These masks are used:
* to sample points to collect dense correspondences.
* as an auxillary loss in DensePose-RCNN.
* to obtain dense FG/BG maps.
A function to get dense masks from the decoded masks.
```
def GetDensePoseMask(Polys):
MaskGen = np.zeros([256,256])
for i in range(1,15):
if(Polys[i-1]):
current_mask = mask_util.decode(Polys[i-1])
MaskGen[current_mask>0] = i
return MaskGen
```
Go over all anns and visualize them one by one.
```
I_vis=I.copy()/2 # Dim the image.
for ann in anns:
bbr = np.array(ann['bbox']).astype(int) # the box.
if( 'dp_masks' in ann.keys()): # If we have densepose annotation for this ann,
Mask = GetDensePoseMask(ann['dp_masks'])
################
x1,y1,x2,y2 = bbr[0],bbr[1],bbr[0]+bbr[2],bbr[1]+bbr[3]
x2 = min( [ x2,I.shape[1] ] ); y2 = min( [ y2,I.shape[0] ] )
################
MaskIm = cv2.resize( Mask, (int(x2-x1),int(y2-y1)) ,interpolation=cv2.INTER_NEAREST)
MaskBool = np.tile((MaskIm==0)[:,:,np.newaxis],[1,1,3])
# Replace the visualized mask image with I_vis.
Mask_vis = cv2.applyColorMap( (MaskIm*15).astype(np.uint8) , cv2.COLORMAP_PARULA)[:,:,:]
Mask_vis[MaskBool]=I_vis[y1:y2,x1:x2,:][MaskBool]
I_vis[y1:y2,x1:x2,:] = I_vis[y1:y2,x1:x2,:]*0.3 + Mask_vis*0.7
plt.imshow(I_vis[:,:,::-1]); plt.axis('off'); plt.show()
```
## Visualization of Collected points
Let's visualize the collected points on the image.
For each collected point we have the surface patch index, and UV coordinates.
The following snippet creates plots colored by I U and V coordinates respectively.
```
# Show images for each subplot.
fig = plt.figure(figsize=[15,5])
plt.subplot(1,3,1)
plt.imshow(I[:,:,::-1]/2);plt.axis('off');plt.title('Patch Indices')
plt.subplot(1,3,2)
plt.imshow(I[:,:,::-1]/2);plt.axis('off');plt.title('U coordinates')
plt.subplot(1,3,3)
plt.imshow(I[:,:,::-1]/2);plt.axis('off');plt.title('V coordinates')
## For each ann, scatter plot the collected points.
for ann in anns:
bbr = np.round(ann['bbox'])
if( 'dp_masks' in ann.keys()):
Point_x = np.array(ann['dp_x'])/ 255. * bbr[2] # Strech the points to current box.
Point_y = np.array(ann['dp_y'])/ 255. * bbr[3] # Strech the points to current box.
#
Point_I = np.array(ann['dp_I'])
Point_U = np.array(ann['dp_U'])
Point_V = np.array(ann['dp_V'])
#
x1,y1,x2,y2 = bbr[0],bbr[1],bbr[0]+bbr[2],bbr[1]+bbr[3]
x2 = min( [ x2,I.shape[1] ] ); y2 = min( [ y2,I.shape[0] ] )
###############
Point_x = Point_x + x1 ; Point_y = Point_y + y1
plt.subplot(1,3,1)
plt.scatter(Point_x,Point_y,22,Point_I)
plt.subplot(1,3,2)
plt.scatter(Point_x,Point_y,22,Point_U)
plt.subplot(1,3,3)
plt.scatter(Point_x,Point_y,22,Point_V)
plt.show()
```
| github_jupyter |
Deep Learning
=============
Assignment 1
------------
The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later.
This notebook uses the [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) dataset to be used with python experiments. This dataset is designed to look like the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset, while looking a little more like real data: it's a harder task, and the data is a lot less 'clean' than MNIST.
```
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import imageio
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
from IPython.display import display, Image
from sklearn.linear_model import LogisticRegression
from six.moves.urllib.request import urlretrieve
from six.moves import cPickle as pickle
# Config the matplotlib backend as plotting inline in IPython
%matplotlib inline
```
First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The labels are limited to 'A' through 'J' (10 classes). The training set has about 500k and the testset 19000 labeled examples. Given these sizes, it should be possible to train models quickly on any machine.
```
url = 'https://commondatastorage.googleapis.com/books1000/'
last_percent_reported = None
data_root = '.' # Change me to store data elsewhere
def download_progress_hook(count, blockSize, totalSize):
"""A hook to report the progress of a download. This is mostly intended for users with
slow internet connections. Reports every 5% change in download progress.
"""
global last_percent_reported
percent = int(count * blockSize * 100 / totalSize)
if last_percent_reported != percent:
if percent % 5 == 0:
sys.stdout.write("%s%%" % percent)
sys.stdout.flush()
else:
sys.stdout.write(".")
sys.stdout.flush()
last_percent_reported = percent
def maybe_download(filename, expected_bytes, force=False):
"""Download a file if not present, and make sure it's the right size."""
dest_filename = os.path.join(data_root, filename)
if force or not os.path.exists(dest_filename):
print('Attempting to download:', filename)
filename, _ = urlretrieve(url + filename, dest_filename, reporthook=download_progress_hook)
print('\nDownload Complete!')
statinfo = os.stat(dest_filename)
if statinfo.st_size == expected_bytes:
print('Found and verified', dest_filename)
else:
raise Exception(
'Failed to verify ' + dest_filename + '. Can you get to it with a browser?')
return dest_filename
train_filename = maybe_download('notMNIST_large.tar.gz', 247336696)
test_filename = maybe_download('notMNIST_small.tar.gz', 8458043)
```
Extract the dataset from the compressed .tar.gz file.
This should give you a set of directories, labeled A through J.
```
num_classes = 10
np.random.seed(133)
def maybe_extract(filename, force=False):
root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz
if os.path.isdir(root) and not force:
# You may override by setting force=True.
print('%s already present - Skipping extraction of %s.' % (root, filename))
else:
print('Extracting data for %s. This may take a while. Please wait.' % root)
tar = tarfile.open(filename)
sys.stdout.flush()
tar.extractall(data_root)
tar.close()
data_folders = [
os.path.join(root, d) for d in sorted(os.listdir(root))
if os.path.isdir(os.path.join(root, d))]
if len(data_folders) != num_classes:
raise Exception(
'Expected %d folders, one per class. Found %d instead.' % (
num_classes, len(data_folders)))
print(data_folders)
return data_folders
train_folders = maybe_extract(train_filename)
test_folders = maybe_extract(test_filename)
```
---
Problem 1
---------
Let's take a peek at some of the data to make sure it looks sensible. Each exemplar should be an image of a character A through J rendered in a different font. Display a sample of the images that we just downloaded. Hint: you can use the package IPython.display.
---
Now let's load the data in a more manageable format. Since, depending on your computer setup you might not be able to fit it all in memory, we'll load each class into a separate dataset, store them on disk and curate them independently. Later we'll merge them into a single dataset of manageable size.
We'll convert the entire dataset into a 3D array (image index, x, y) of floating point values, normalized to have approximately zero mean and standard deviation ~0.5 to make training easier down the road.
A few images might not be readable, we'll just skip them.
```
image_size = 28 # Pixel width and height.
pixel_depth = 255.0 # Number of levels per pixel.
def load_letter(folder, min_num_images):
"""Load the data for a single letter label."""
image_files = os.listdir(folder)
dataset = np.ndarray(shape=(len(image_files), image_size, image_size),
dtype=np.float32)
print(folder)
num_images = 0
for image in image_files:
image_file = os.path.join(folder, image)
try:
image_data = (imageio.imread(image_file).astype(float) -
pixel_depth / 2) / pixel_depth
if image_data.shape != (image_size, image_size):
raise Exception('Unexpected image shape: %s' % str(image_data.shape))
dataset[num_images, :, :] = image_data
num_images = num_images + 1
except (IOError, ValueError) as e:
print('Could not read:', image_file, ':', e, '- it\'s ok, skipping.')
dataset = dataset[0:num_images, :, :]
if num_images < min_num_images:
raise Exception('Many fewer images than expected: %d < %d' %
(num_images, min_num_images))
print('Full dataset tensor:', dataset.shape)
print('Mean:', np.mean(dataset))
print('Standard deviation:', np.std(dataset))
return dataset
def maybe_pickle(data_folders, min_num_images_per_class, force=False):
dataset_names = []
for folder in data_folders:
set_filename = folder + '.pickle'
dataset_names.append(set_filename)
if os.path.exists(set_filename) and not force:
# You may override by setting force=True.
print('%s already present - Skipping pickling.' % set_filename)
else:
print('Pickling %s.' % set_filename)
dataset = load_letter(folder, min_num_images_per_class)
try:
with open(set_filename, 'wb') as f:
pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL)
except Exception as e:
print('Unable to save data to', set_filename, ':', e)
return dataset_names
train_datasets = maybe_pickle(train_folders, 45000)
test_datasets = maybe_pickle(test_folders, 1800)
```
---
Problem 2
---------
Let's verify that the data still looks good. Displaying a sample of the labels and images from the ndarray. Hint: you can use matplotlib.pyplot.
---
---
Problem 3
---------
Another check: we expect the data to be balanced across classes. Verify that.
---
Merge and prune the training data as needed. Depending on your computer setup, you might not be able to fit it all in memory, and you can tune `train_size` as needed. The labels will be stored into a separate array of integers 0 through 9.
Also create a validation dataset for hyperparameter tuning.
```
def make_arrays(nb_rows, img_size):
if nb_rows:
dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32)
labels = np.ndarray(nb_rows, dtype=np.int32)
else:
dataset, labels = None, None
return dataset, labels
def merge_datasets(pickle_files, train_size, valid_size=0):
num_classes = len(pickle_files)
valid_dataset, valid_labels = make_arrays(valid_size, image_size)
train_dataset, train_labels = make_arrays(train_size, image_size)
vsize_per_class = valid_size // num_classes
tsize_per_class = train_size // num_classes
start_v, start_t = 0, 0
end_v, end_t = vsize_per_class, tsize_per_class
end_l = vsize_per_class+tsize_per_class
for label, pickle_file in enumerate(pickle_files):
try:
with open(pickle_file, 'rb') as f:
letter_set = pickle.load(f)
# let's shuffle the letters to have random validation and training set
np.random.shuffle(letter_set)
if valid_dataset is not None:
valid_letter = letter_set[:vsize_per_class, :, :]
valid_dataset[start_v:end_v, :, :] = valid_letter
valid_labels[start_v:end_v] = label
start_v += vsize_per_class
end_v += vsize_per_class
train_letter = letter_set[vsize_per_class:end_l, :, :]
train_dataset[start_t:end_t, :, :] = train_letter
train_labels[start_t:end_t] = label
start_t += tsize_per_class
end_t += tsize_per_class
except Exception as e:
print('Unable to process data from', pickle_file, ':', e)
raise
return valid_dataset, valid_labels, train_dataset, train_labels
train_size = 200000
valid_size = 10000
test_size = 10000
valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets(
train_datasets, train_size, valid_size)
_, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size)
print('Training:', train_dataset.shape, train_labels.shape)
print('Validation:', valid_dataset.shape, valid_labels.shape)
print('Testing:', test_dataset.shape, test_labels.shape)
```
Next, we'll randomize the data. It's important to have the labels well shuffled for the training and test distributions to match.
```
def randomize(dataset, labels):
permutation = np.random.permutation(labels.shape[0])
shuffled_dataset = dataset[permutation,:,:]
shuffled_labels = labels[permutation]
return shuffled_dataset, shuffled_labels
train_dataset, train_labels = randomize(train_dataset, train_labels)
test_dataset, test_labels = randomize(test_dataset, test_labels)
valid_dataset, valid_labels = randomize(valid_dataset, valid_labels)
```
---
Problem 4
---------
Convince yourself that the data is still good after shuffling!
---
Finally, let's save the data for later reuse:
```
pickle_file = os.path.join(data_root, 'notMNIST.pickle')
try:
f = open(pickle_file, 'wb')
save = {
'train_dataset': train_dataset,
'train_labels': train_labels,
'valid_dataset': valid_dataset,
'valid_labels': valid_labels,
'test_dataset': test_dataset,
'test_labels': test_labels,
}
pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)
f.close()
except Exception as e:
print('Unable to save data to', pickle_file, ':', e)
raise
statinfo = os.stat(pickle_file)
print('Compressed pickle size:', statinfo.st_size)
```
---
Problem 5
---------
By construction, this dataset might contain a lot of overlapping samples, including training data that's also contained in the validation and test set! Overlap between training and test can skew the results if you expect to use your model in an environment where there is never an overlap, but are actually ok if you expect to see training samples recur when you use it.
Measure how much overlap there is between training, validation and test samples.
Optional questions:
- What about near duplicates between datasets? (images that are almost identical)
- Create a sanitized validation and test set, and compare your accuracy on those in subsequent assignments.
---
---
Problem 6
---------
Let's get an idea of what an off-the-shelf classifier can give you on this data. It's always good to check that there is something to learn, and that it's a problem that is not so trivial that a canned solution solves it.
Train a simple model on this data using 50, 100, 1000 and 5000 training samples. Hint: you can use the LogisticRegression model from sklearn.linear_model.
Optional question: train an off-the-shelf model on all the data!
---
| github_jupyter |
# f-Strings
Some notes on the f-string method of string formatting that was introduced in Python 3.6.
f-strings are the recommended way of building strings (like file names/paths) that contain Python variables.
They are more readable than previous string interpolation methods, or string concatenation,
and they are faster!
## References
[Python 3's f-Strings: An Improved String Formatting Syntax](https://realpython.com/python-f-strings/) -
A concise intro, with brief summaries of the %-formatting and `str.format()` methods that came before f-strings
[Format Specification Examples](https://docs.python.org/3/library/string.html#formatexamples) -
"Format specification" is the name for the bits of code that control how numeric variables are converted to strings
(e.g. how many decimal places, leading zeros, space-padding before and after, justification, etc.).
The format specification mini-language for the `str.format()` method is also used in f-strings.
[Format Specification Mini-Language](https://docs.python.org/3/library/string.html#formatspec) -
These are the official docs with all of the details.
[Python String Formatting Cheat Sheet](https://cheatography.com/mutanclan/cheat-sheets/python-string-formatting/) -
A concise summary of the mini-language.
A link to a really good tabulation of the mini-language combined with examples of use would be really nice to have.
If you know of such a page, please add it!!
## Building a `dict` of File Paths/Names
This is based on my best recollection of Rachael's question in the 4-May-2020 MOAD meeting.
```
results_dir = "/data/rmueller/MIDOSS/AKNS-particles"
particle_counts = (1000, 2000, 3000)
akns_files = {} # empty dict to accumulate file paths in
for n_particles in particle_counts:
akns_files[n_particles] = f"{results_dir}/Lagrangian_AKNS-particles_{n_particles}.nc"
```
Iterate over file paths:
```
for path in akns_files.values():
print(path)
```
Iterate over particle counnts and file paths:
```
for n_particles, path in akns_files.items():
print(n_particles, path)
```
If you want to get even more Pythonic, the `for` loop can be written as a dictionary comprehension:
```
results_dir = "/data/rmueller/MIDOSS/AKNS-particles"
particle_counts = (1000, 2000, 3000)
akns_files = {
n_particles: f"{results_dir}/Lagrangian_AKNS-particles_{n_particles}.nc"
for n_particles in particle_counts
}
```
## Format Specification Examples
Please add your favourites!
Integers with leading zeros:
```
for num in range(3):
print(f"{i:03d}")
```
Control number of decimal places of floats:
```
import random
for i in range(3):
rnd = random.random()
print(rnd, f"{rnd:0.3f}")
```
Scientific notation:
```
import random
for i in range(3):
rnd = random.random()
print(rnd, f"{rnd:0.4e}")
```
Thousands separators:
```
for num in (1000, 20000, 3000000):
print(f"{num:,}")
```
| github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
import torch
def calc_weight(x, alpha=-0.2):
return torch.exp(alpha * torch.abs(x))
# Visualizing different weights
alpha = [-0.1, -0.2, -0.3, -0.4, -0.5, -0.8, -1]
N = lambda x, a: np.exp(a*x)
x = np.arange(0, 10, 0.01)
for i in range(len(alpha)):
plt.plot(x, N(x, alpha[i]), label="a={}".format(alpha[i]))
plt.title("Normal Weights")
plt.xlabel('dx')
plt.ylabel('weight')
plt.legend()
plt.grid()
plt.savefig("normal_weights.png", dpi=400)
def calc_normal(xi, x0, x1, x2, x3):
x_n = torch.stack([x0, x1, x2, x3])
delta_x = x_n - xi
dist = torch.norm(delta_x, dim=1)
weights = calc_weight(dist)
normals = []
for i in range(len(delta_x)):
if i < len(delta_x) - 1:
N_i = torch.cross(weights[i] * delta_x[i], weights[i+1] * delta_x[i+1])
else:
N_i = torch.cross(weights[i] * delta_x[i], weights[0] * delta_x[0])
normals.append(N_i)
normals = torch.stack(normals)
N = 1/len(normals) * torch.sum(normals, dim=0)
N /= torch.norm(N)
return N
# Test 1: normal calculation
xi = torch.tensor([0, 0, 0], dtype=torch.float)
X = [[1, 0, 0],
[0, 1, 0],
[-1, 0, 0],
[0, -1, 0]]
X = torch.tensor(X, dtype=float)
# ground truth normal
N_gt = torch.tensor([0, 0, 1], dtype=float)
N_hat = calc_normal(xi, X[0], X[1], X[2], X[3])
delta_N = N_gt - N_hat
print("calculated normal: ", N_hat)
print("diff: ", delta_N)
# Test 2: normal calculation
xi = torch.tensor([1, -2, 0], dtype=torch.float)
X = [[3, 1, 4],
[0, -1, 2],
[-1, -5, -4],
[2, -3, -2]]
X = torch.tensor(X, dtype=float)
# ground truth normal
N_gt = torch.tensor([0.2074, -0.8296, 0.5185], dtype=float)
N_hat = calc_normal(xi, X[0], X[1], X[2], X[3])
delta_N = N_gt - N_hat
print("calculated normal: ", N_hat)
print("diff: ", delta_N)
import torch.nn.functional as F
def calc_normal_img(img):
"""
img is cylindrical projection of a lidar frame, having at least three x, y, z channels.
image channels are torch ordered, e.g. := [N, C, H, W]
we also assumes that the x,y,z coordinate are the first 3 channels, also N should be eq. 1
"""
h, w = img.shape[2:]
N = torch.zeros((3, h, w))
im_padded = F.pad(img[:, 0:3, :, :], (1, 1, 1, 1), mode='replicate')
# we do not need the batch dim.
im_padded = im_padded[0]
h, w = im_padded.shape[1:]
for i in range(1, h-1):
for j in range(1, w-1):
xi = im_padded[0:3, i ,j]
x0, x1, x2, x3 = im_padded[0:3, i-1 ,j], im_padded[0:3, i ,j-1], im_padded[0:3, i+1 ,j], im_padded[0:3, i ,j+1]
N[:, i-1, j-1] = calc_normal(xi, x0, x1, x2, x3)
return N
import matplotlib
from matplotlib import pyplot as plt
img = torch.rand((1, 3, 10, 10))
N = calc_normal_img(img)
img = img[0, :, :, :]
# plot image
plt.figure()
plt.imshow(img.permute(1, 2, 0))
# plot normals
plt.figure()
plt.imshow(N.permute(1, 2, 0))
```
def project
| github_jupyter |
```
import gdal
import urllib.request
import xarray as xr
import numpy as np
import time
from datetime import datetime, date, time, timedelta
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import urllib
import requests
import json
```
## Read in the USV daily files and your instance code from a text file
```
#read in USV data
#file_dir = 'F:/data/cruise_data/saildrone/2019_arctic/daily_files/*.nc'
#ds_usv = xr.open_mfdataset(file_dir,data_vars='minimal')
#ds_usv.load()
#not useing this right now but consider putting instance here
def get_key(file_name):
myvars = {}
with open(file_name) as myfile:
for line in myfile:
name, var = line.partition("=")[::2]
myvars[name.strip()] = str(var).rstrip()
return myvars
file_key = "C:/Users/gentemann/Google Drive/f_drive/secret_keys/sentinelhub_bingkun.txt"
my_vars = get_key(file_key)
file_key = "C:/Users/gentemann/Google Drive/f_drive/secret_keys/saildrone.txt"
saildrone_key = get_key(file_key)
```
## Use restful API to get USV locations
```
#endtime = datetime.today().strftime('%Y-%m-%d')
endtime = (datetime.today() + timedelta(days=1)).strftime('%Y-%m-%d')
starttime = (datetime.today() + timedelta(days=-5)).strftime('%Y-%m-%d')
#all_usv = ['1041','1033','1034','1035','1036','1037']
all_usv = ['1034','1035','1036','1037']
#get token
payload={'key': saildrone_key['key'], 'secret':saildrone_key['secret']}
headers={'Content-Type':'application/json', 'Accept':'application/json'}
url = 'https://developer-mission.saildrone.com/v1/auth'
res = requests.post(url, json=payload, headers=headers)
json_data = json.loads(res.text)
names=[]
ilen = 500 #len(usv_data['data'])
usv_lats = np.empty((ilen,4))*np.nan
usv_lons = np.empty((ilen,4))*np.nan
usv_time = np.empty((ilen,4))*np.nan
for iusv in range(4):
str_usv = all_usv[iusv]
url = 'https://developer-mission.saildrone.com/v1/timeseries/'+str_usv+'?data_set=vehicle&interval=5&start_date='+starttime+'&end_date='+endtime+'&order_by=desc&limit=500&offset=0'
payload = {}
headers = {'Accept':'application/json','authorization':json_data['token']}
res = requests.get(url, json=payload, headers=headers)
usv_data = json.loads(res.text)
#print(usv_data.data)
for i in range(ilen):
usv_lons[i,iusv]=usv_data['data'][i]['gps_lng']
usv_lats[i,iusv]=usv_data['data'][i]['gps_lat']
usv_time[i,iusv]=usv_data['data'][i]['gps_time']
names.append(str_usv)
xlons = xr.DataArray(usv_lons,coords={'time':usv_time[:,0],'trajectory':names},dims=('time','trajectory'))
xlats = xr.DataArray(usv_lats,coords={'time':usv_time[:,0],'trajectory':names},dims=('time','trajectory'))
ds_usv = xr.Dataset({'lon': xlons,'lat':xlats})
ds_usv = xr.open_dataset('Desktop')
#plot the usv tracks
for iusv in range(4):
plt.plot(ds_usv.lon[:,iusv],ds_usv.lat[:,iusv],label=ds_usv.trajectory[iusv].data)
plt.legend()
#endtime = datetime.today().strftime('%Y-%m-%d')
endtime = (datetime.today() + timedelta(days=1)).strftime('%Y-%m-%d')
starttime = (datetime.today() + timedelta(days=-5)).strftime('%Y-%m-%d')
#use usv data to calculate bounding box
for iusv in range(4):
subset = ds_usv.isel(trajectory=iusv)
subset = subset.where(np.isfinite(subset.lon),drop=True)
lonmin,lonmax = str(subset.lon[0].data-1),str(subset.lon[0].data+1)
latmin,latmax = str(subset.lat[0].data-1),str(subset.lat[0].data+1)
#print(lonmin,lonmax,latmin,latmax)
# url = 'https://services.sentinel-hub.com/ogc/wms/'+my_vars["instance"]+'?SERVICE=WMS&REQUEST=GetMap&SHOWLOGO=true&MAXCC=100&TIME='+starttime+'%2F'+endtime+'&CRS=EPSG%3A4326&FORMAT=image%2Ftiff%3Bdepth%3D8&BBOX='+latmax+'%2C'+lonmax+'%2C'+latmin+'%2C'+lonmin+'&evalscriptoverrides=&LAYERS=1_TRUE_COLOR&WIDTH=4076&HEIGHT=1989&NICENAME=S1.tiff&COVERAGE'
url = 'https://services.sentinel-hub.com/ogc/wms/'+my_vars["instance"]+'?SERVICE=WMS&REQUEST=GetMap&SHOWLOGO=true&MAXCC=100&TIME='+starttime+'%2F'+endtime+'&CRS=EPSG%3A4326&FORMAT=image%2Ftiff%3Bdepth%3D8&BBOX='+latmax+'%2C'+lonmax+'%2C'+latmin+'%2C'+lonmin+'&evalscriptoverrides=&LAYERS=1_TRUE_COLOR&WIDTH=4076&HEIGHT=1989&NICENAME=S1.tiff&COVERAGE'
# url = 'https://eocloud.sentinel-hub.com/v1/wms/'+my_vars["instance"]+'?SERVICE=WMS&REQUEST=GetMap&SHOWLOGO=true&MAXCC=100&TIME=2019-06-26%2F2019-06-26&CRS=EPSG%3A3857&FORMAT=image%2Ftiff%3Bdepth%3D32f&BBOX=-19164303%2C10971589%2C-16835703%2C12069589&evalscriptoverrides=&LAYERS=1_TRUE_COLOR&WIDTH=3881&HEIGHT=1830&NICENAME=Sentinel-3+OLCI+from+2019-06-26.tiff&COVERAGE'
# url = 'https://eocloud.sentinel-hub.com/v1/wms/1180d546-51af-442e-9a06-d490007ab3a5?SERVICE=WMS&REQUEST=GetMap&SHOWLOGO=true&MAXCC=100&TIME=2019-06-23%2F2019-06-26&CRS=EPSG%3A3857&FORMAT=image%2Fpng&BBOX=-17934019%2C11128804%2C-17666552%2C11944360&evalscriptoverrides=&LAYERS=1_TRUE_COLOR&WIDTH=2935&HEIGHT=1401&NICENAME=S1.png&TRANSPARENT=0&BGCOLOR=00000000'
print(url)
urllib.request.urlretrieve(url,'S11.tiff')
#Open S1 ice file
driver=gdal.GetDriverByName('GTiff')
driver.Register()
ds = gdal.Open('S11.tiff')
if ds is None:
print('Could not open the Copernicus Sentinel-1 ice data')
geotransform = ds.GetGeoTransform()
cols = ds.RasterXSize
rows = ds.RasterYSize
xmin=geotransform[0]
ymax=geotransform[3]
xmax=xmin+cols*geotransform[1]
ymin=ymax+rows*geotransform[5]
# xmin=geotransform[0]
# ymax=geotransform[3]
# xmax=xmin+cols*geotransform[1]
# ymin=ymax+rows*geotransform[5]
centerx=(xmin+xmax)/2
centery=(ymin+ymax)/2
#Raster convert to array in numpy
bands = ds.RasterCount
band=ds.GetRasterBand(1)
dataimage= band.ReadAsArray(0,0,cols,rows)
print(xmin,xmax,ymin,ymax)
xx=xmin+np.arange(dataimage.shape[1])/dataimage.shape[1]*(xmax-xmin)
yy=ymin+np.arange(dataimage.shape[0])/dataimage.shape[0]*(ymax-ymin)
#print(xx.shape,yy.shape)
#print(xx[0],xx[-1],yy[0],yy[-1])
fig = plt.figure(figsize=(8, 8), dpi=400)
plt.pcolormesh(xx,yy,dataimage[-1:0:-1,:])# ,vmin=10,vmax=200)
plt.xlim(xmin,xmax)
plt.ylim(ymin,ymax)
for itrag in range(0,ds_usv.trajectory.size):
subset = ds_usv.isel(trajectory=itrag)
subset = subset.where(np.isfinite(subset.lon),drop=True)
plt.plot(subset.lon,subset.lat,label=str(ds_usv.trajectory[itrag].data))
plt.grid(color='w')
plt.legend(loc=2)
#plt.colorbar()
fig_fname = 'C:/Users/gentemann/Google Drive/public/Saildrone/arctic_zoom_'+str(ds_usv.trajectory[iusv].data)+'_'+str(endtime)+'.png'
plt.savefig(fig_fname, transparent=False, format='png',dpi=400)
#to put into xr
#ds = xr.DataArray(dataimage.T,name='s2image',coords={'lon':xx,'lat':yy},dims=('lon','lat'))
```
| github_jupyter |
# Predicting Wine Quality
Regression is the task of fitting a model to data. If things go well, the model might provide useful predictions in response to new data. This notebook shows how linear programming and least absolute deviation (LAD) regression can be used to create a linear model for predicting wine quality based on physical and chemical properties. The example uses a well known data set from the machine learning community.
```
# Install Pyomo and solvers for Google Colab
import sys
if "google.colab" in sys.modules:
!wget -N -q https://raw.githubusercontent.com/jckantor/MO-book/main/tools/install_on_colab.py
%run install_on_colab.py
```
## Downloading the data set
Physical, chemical, and sensory quality properties were collected for a large number of red and white wines produced in the Portugal then donated to the UCI machine learning repository (Cortez, Paulo, Cerdeira, A., Almeida, F., Matos, T. & Reis, J.. (2009). Wine Quality. UCI Machine Learning Repository.) The following cell reads the data for red wines directly from the UCI machine learning repository.
Cortez, P., Cerdeira, A., Almeida, F., Matos, T., & Reis, J. (2009). Modeling wine preferences by data mining from physicochemical properties. Decision support systems, 47(4), 547-553. https://doi.org/10.1016/j.dss.2009.05.016
```
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
wines = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv", sep=";")
display(wines)
```
## Model Objective: Mean Absolute Deviation (MAD)
Given a n repeated observations of a response variable $y_i$ (in this wine quality), the **mean absolute deviation** (MAD) of $y_i$ from the mean value $\bar{y}$ is
$$\text{MAD}\,(y) = \frac{1}{n} \sum_{i=1}^n | y_i - \bar{y}|$$
The goal of the regression is find coefficients $m_j$ and $b$ to minimize
$$
\begin{align*}
\text{MAD}\,(\hat{y}) & = \min \frac{1}{n} \sum_{i=1}^n | y_i - \hat{y}_i| \\
\\
\text{s. t.}\quad \hat{y}_i & = \sum_{j=1}^J x_{i, j} m_j + b & \forall i = 1, \dots, n\
\end{align*}
$$
where $x_{i, j}$ are values of 'explanatory' variables. A successful model would demonstrate a substantial reduction from $\text{MAD}\,(y)$ to $\text{MAD}\,(\hat{y})$. The value of $\text{MAD}\,(y)$ sets a benchmark for the regression.
```
def MAD(df):
return (df - df.mean()).abs().mean()
print("MAD = ", MAD(wines["quality"]))
fig, ax = plt.subplots(figsize=(12, 4))
ax = wines["quality"].plot(alpha=0.6, title="wine quality")
ax.axhline(wines["quality"].mean(), color='r', ls='--', lw=3)
mad = MAD(wines["quality"])
ax.axhline(wines["quality"].mean() + mad, color='g', lw=3)
ax.axhline(wines["quality"].mean() - mad, color='g', lw=3)
ax.legend(["y", "mean", "mad"])
ax.set_xlabel("observation")
```
## A preliminary look at the data
The data consists of 1,599 measurements of eleven physical and chemical characteristics plus an integer measure of sensory quality recorded on a scale from 3 to 8. Histograms provides insight into the values and variability of the data set.
```
fig, axes = plt.subplots(3, 4, figsize=(12, 8), sharey=True)
for ax, column in zip(axes.flatten(), wines.columns):
wines[column].hist(ax=ax, bins=30)
ax.axvline(wines[column].mean(), color='r', label="mean")
ax.set_title(column)
ax.legend()
plt.tight_layout()
```
## Which features influence reported wine quality?
The art of regression is to identify the features that have explanatory value for a response of interest. This is where a person with deep knowledge of an application area, in this case an experienced onenologist will have a head start compared to the naive data scientist. In the absence of the experience, we proceed by examining the correlation among the variables in the data set.
```
wines.corr()["quality"].plot(kind="bar", grid=True)
wines[["volatile acidity", "density", "alcohol", "quality"]].corr()
```
Collectively, these figures suggest `alcohol` is a strong correlate of `quality`, and several additional factors as candidates for explanatory variables..
## LAD line fitting to identify features
An alternative approach is perform a series of single feature LAD regressions to determine which features have the largest impact on reducing the mean absolute deviations in the residuals.
$$
\begin{align*}
\min \frac{1}{I} \sum_{i\in I} \left| y_i - a x_i - b \right|
\end{align*}
$$
This computation has been presented in a prior notebook.
```
import pyomo.environ as pyo
def lad_fit_1(df, y_col, x_col):
m = pyo.ConcreteModel("L1 Regression Model")
m.I = pyo.RangeSet(len(df))
@m.Param(m.I)
def y(m, i):
return df.loc[i-1, y_col]
@m.Param(m.I)
def X(m, i):
return df.loc[i-1, x_col]
# regression
m.a = pyo.Var()
m.b = pyo.Var(domain=pyo.Reals)
m.e_pos = pyo.Var(m.I, domain=pyo.NonNegativeReals)
m.e_neg = pyo.Var(m.I, domain=pyo.NonNegativeReals)
@m.Expression(m.I)
def prediction(m, i):
return m.a * m.X[i] + m.b
@m.Constraint(m.I)
def prediction_error(m, i):
return m.e_pos[i] - m.e_neg[i] == m.prediction[i] - m .y[i]
@m.Objective(sense=pyo.minimize)
def mean_absolute_deviation(m):
return sum(m.e_pos[i] + m.e_neg[i] for i in m.I)/len(m.I)
pyo.SolverFactory('cbc').solve(m)
return m
m = lad_fit_1(wines, "quality", "alcohol")
print(m.mean_absolute_deviation())
```
This calculation is performed for all variables to determine which variables are the best candidates to explain deviations in wine quality.
```
mad = (wines["alcohol"] - wines["alcohol"].mean()).abs().mean()
vars = {i: lad_fit_1(wines, "quality", i).mean_absolute_deviation() for i in wines.columns}
fig, ax = plt.subplots()
pd.Series(vars).plot(kind="bar", ax=ax, grid=True)
ax.axhline(mad, color='r', lw=3)
ax.set_title('mean absolute deviation following regression')
wines["prediction"] = [m.prediction[i]() for i in m.I]
wines["quality"].hist(label="data")
wines.plot(x="quality", y="prediction", kind="scatter")
```
## Multivariable Regression
```
import pyomo.environ as pyo
def l1_fit_2(df, y_col, x_cols):
m = pyo.ConcreteModel("L1 Regression Model")
m.I = pyo.RangeSet(len(df))
m.J = pyo.Set(initialize=x_cols)
@m.Param(m.I)
def y(m, i):
return df.loc[i-1, y_col]
@m.Param(m.I, m.J)
def X(m, i, j):
return df.loc[i-1, j]
# regression
m.a = pyo.Var(m.J)
m.b = pyo.Var(domain=pyo.Reals)
m.e_pos = pyo.Var(m.I, domain=pyo.NonNegativeReals)
m.e_neg = pyo.Var(m.I, domain=pyo.NonNegativeReals)
@m.Expression(m.I)
def prediction(m, i):
return sum(m.a[j] * m.X[i, j] for j in m.J) + m.b
@m.Constraint(m.I)
def prediction_error(m, i):
return m.e_pos[i] - m.e_neg[i] == m.prediction[i] - m.y[i]
@m.Objective(sense=pyo.minimize)
def mean_absolute_deviation(m):
return sum(m.e_pos[i] + m.e_neg[i] for i in m.I)/len(m.I)
pyo.SolverFactory('cbc').solve(m)
return m
m = l1_fit_2(wines, "quality",
["alcohol", "volatile acidity", "citric acid", "sulphates", \
"total sulfur dioxide", "density", "fixed acidity"])
print(m.mean_absolute_deviation())
for j in m.J:
print(f"{j} {m.a[j]()}")
wines["prediction"] = [m.prediction[i]() for i in m.I]
wines["quality"].hist(label="data")
wines.plot(x="quality", y="prediction", kind="scatter")
```
## How do these models perform?
The linear regression model clearly has some capability to explain the observed deviations in wine quality. Tabulating the results of the regression using the MAD statistic we find
| Regressors | MAD |
| :--- | ---: |
| none | 0.683 |
| alcohol only | 0.541 |
| all | 0.500 |
Are these models good enough to replace human judgment of wine quality? The reader can be the judge.
| github_jupyter |
# PhysioNet/Computing in Cardiology Challenge 2020
## Classification of 12-lead ECGs
### 2. Create Training Dataset
# Setup Noteboook
```
# Import 3rd party libraries
import os
import sys
import json
import random
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
# Import local Libraries
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd()))))))
from kardioml import DATA_PATH
# Configure Notebook
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%load_ext autoreload
%autoreload 2
```
# Split Physionet 2020 Training Data
## Create Training Lookup File
```
# Set sample frequencies
sample_frequencies = [350]
# Set datasets
datasets = ['A', 'B', 'D', 'E']
# Create list
data = list()
# Loop through sample frequencies
for fs in sample_frequencies:
# Loop through datasets
for dataset in datasets:
# Get filenames
filenames = [filename.split('.')[0] for filename in os.listdir(os.path.join(DATA_PATH, dataset, str(fs)))
if 'json' in filename]
# Loop through filenames
for filename in filenames:
# Import meta data
meta_data = json.load(open(os.path.join(DATA_PATH, dataset, str(fs), '{}.json'.format(filename))))
# Save label
if meta_data['labels_training']:
data.append({'filename': filename, 'labels': meta_data['labels_training'], 'dataset': dataset, 'fs': fs,
'labels_merged': meta_data['labels_training_merged'],
'path': os.path.join(DATA_PATH, dataset, str(fs), filename)})
# Create DataFrame
data = pd.DataFrame(data)
# View DataFrame
data.head()
# Loop through sample frequencies
for fs in sample_frequencies:
# Filter by sample frequency
df = data[data['fs'] == fs].reset_index()
# Split dataset into train/evaluate
rmskf = MultilabelStratifiedKFold(n_splits=2, random_state=0)
for cv_fold, (train_index, val_index) in enumerate(rmskf.split(np.stack(df['labels_merged'].values),
np.stack(df['labels_merged'].values))):
pass
# Lookup file
training_lookup = {'train': df.loc[train_index, 'path'].tolist(), 'val': df.loc[val_index, 'path'].tolist()}
# Save file
os.makedirs(os.path.join(DATA_PATH, 'training', 'deepecg', 'single_split', str(fs)), exist_ok=True)
with open(os.path.join(DATA_PATH, 'training', 'deepecg', 'single_split', str(fs), 'training_lookup.json'), 'w') as file:
json.dump(training_lookup, file, sort_keys=False, indent=4)
```
| github_jupyter |
# Harvest South Australian naturalization records in the National Archives of Australia
This notebook was used to harvest item data from the following series in April 2019:
* [A7419](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A7419) – Nominal index for pre-1904 South Australian naturalizations
* [A729](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A729) – Books of enrolled certificates of naturalization, issued 1848-1858, enrolled 1850-1889
* [A730](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A730) – Naturalized Aliens Journals
* [A731](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A731) – (1) 'Index to Aliens', name index book to certificates of naturalization, issued 1848-1858, enrolled 1850-1888 (2) List of aliens registered
* [A734](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A734) – Journal and index, naturalized aliens
* [A821](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A821) – Memorials of naturalization, with unenrolled or uncollected certificates
* [A732](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A732) – Journal and index, naturalized aliens
* [A735](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A735) – Oaths of Allegiance
* [A822](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A822) – Memorials and certificates of naturalization (unenrolled or uncollected), for South Australia under Act 20 of 21 Victoria
* [A823](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A823) – Enrolled Certificates of Naturalization and Memorials
* [A825](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A825) – Memorials of Naturalization, unregistered (1865)
* [A826](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A826) – Uncollected Certificates of Naturalization
* [A711](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A711) – Memorials of naturalization
* [A733](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A733) – Volumes of enrolled letters of naturalization
* [A805](http://recordsearch.naa.gov.au/scripts/AutoSearch.asp?Number=A805) – Cancelled Certificates of Naturalisation, South Australia
This code is now out-of-date due to the deprecation of some of the packages used. If you want to undertake your own harvest of these or other series in the NAA, go the the [RecordSearch section of the GLAM Workbench](https://glam-workbench.net/recordsearch/) for current versions of the harvesting code.
The harvested data is available as individual `tinydb` JSON files in the `data/south_australia` directory, or as a [single combined CSV file](naa_south_australia_combined.csv).
See [this notebook](naa_south_australia.ipynb) for an overview of the harvested data.
```
import time
import os
import math
import string
import requests
import pandas as pd
from requests import ConnectionError
from recordsearch_tools.utilities import retry
from recordsearch_tools.client import RSSearchClient, RSSeriesClient
from tinydb import TinyDB, Query
try:
from io import BytesIO
except ImportError:
from StringIO import StringIO
os.makedirs('data/south-australia', exist_ok=True)
series = [
'A7419',
'A729',
'A730',
'A731',
'A734',
'A821',
'A732',
'A735',
'A822',
'A823',
'A825',
'A826',
'A711',
'A733',
'A805'
]
class SeriesHarvester():
def __init__(self, series, control=None):
self.series = series
self.control = control
self.total_pages = None
self.pages_complete = 0
self.client = RSSearchClient()
self.prepare_harvest()
self.db = TinyDB('data/south-australia/db-{}.json'.format(self.series.replace('/', '-')))
self.items = self.db.table('items')
self.images = self.db.table('images')
def get_total(self):
return self.client.total_results
def prepare_harvest(self):
if self.control:
self.client.search(series=self.series, control=self.control)
else:
self.client.search(series=self.series)
total_results = self.client.total_results
print('{} items'.format(total_results))
self.total_pages = math.floor(int(total_results) / self.client.results_per_page) + 1
print(self.total_pages)
@retry(ConnectionError, tries=20, delay=10, backoff=1)
def start_harvest(self, page=None):
Record = Query()
if not page:
page = self.pages_complete + 1
while self.pages_complete < self.total_pages:
if self.control:
response = self.client.search(series=self.series, page=page, control=self.control, sort='9')
else:
response = self.client.search(series=self.series, page=page, sort='9')
for result in response['results']:
self.items.upsert(result, Record.identifier == result['identifier'])
self.pages_complete += 1
page += 1
print('{} pages complete'.format(self.pages_complete))
time.sleep(1)
def harvest_series(series):
h = SeriesHarvester(series=series)
h.start_harvest()
for s in series:
harvest_series(s)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/davidnoone/PHYS332_FluidExamples/blob/main/02_DiffusionStokes.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Vorticity prediction and velocity (1d case)
We will work in a cartesian coordinate system, x, y, z, with velocity u, v, w.
We have seen that a remarkably elegant version of the Navier-Stokes equations can be derived for an incompressible case.
$$
\dot \Omega = \frac{\eta}{\rho} \nabla^2 \Omega
$$
Where the total deriatve on the left should be exanded into the Eulerian form that would include non-linear advection.
Further, we can make the problem 1 dimensional by integrating over the y and z direction. We will assume the z direction is bounded, and the y direction is infinitely long. Under these conditions, the incompressible condition in 1d means that the velocity u must be constant. For simplicty we will assume it is zero, without loss of generality. The w velocity is similarly zero. The velocity v need not be. These assumtions however, remove the need for non-linar advection, and we can write
$$
\frac{\partial \zeta}{\partial t} = \frac{\eta}{\rho} \frac{\partial^2 \zeta}{\partial x^2}
$$
where $\zeta$ is the vorticity in the direction f the z coordinate.
$$
\zeta = \frac{\partial v}{\partial y} - \frac{\partial u}{\partial x}
$$
You have a case in which the initial forticity is given by the function
$$
\zeta(x,t=0) = A_1 sin(x - c_1) + A_2 sin(2x - c_2)
$$
With amplitudes $A_1 = 2$ and $A_2 = 1$.
## Work tasks
1. Create a graph of vorticity
2. Create function to approximate second derivative
3. Create a function to integrate in time
4. Produce time evolution to test analytic result.
*Learning goals*:
* Finite difference estimayes of gradents and second derivatives
* Develop method for numerically solving diffusion equation
* Time dependent flow
* Use of forward (Euler) time stepping
* Checking numerical and analytic results
```
import math
import numpy as np
import matplotlib.pyplot as plt
```
The main component of this problem is developing an equation to calculate the second derivative. We wish to evaluate the second grid on a discrete grid between 0 and 2$\pi$, with steps $\Delta x$ indicated by index $i = 0, N-1$. (Note python has arrays startning at index 0
Using a finite difference method, we can obtain scheme with second order accuracy as:
$$
\frac{\partial^2 f}{\partial x^2} \approx
\frac{f_{i+1} - 2 f_{i} + f_{i-1}}{(\Delta x)^2}
$$
Create a function that performs this opperation. Recall we are working with periodic boundary conditions so we may "wrap arround" such that $f_{-1} = f_{N-1}$ and $f_{N} = f_{1}$. You may choose to do this with python array indices, or take a look at the numpy finction [numpy.roll()](https://numpy.org/doc/stable/reference/generated/numpy.roll.html).
```
# Create a coordinate, which is periodix
npts = 20
xvals = np.linspace(0,2*math.pi,npts)
dx = 2*math.pi/npts
rho = 1.
eta = 1.
# Define the initial vorticity
#A1 =
#A2 =
#c1 =
#c1 =
#vort[] = [your code here]
```
Make a plot showing your initial vorticity: vorticity as a function of X
```
#
```
We will need a function to compute the second derivative using finite differences. Let's do that here:
```
def second_derivative(vort, dx):
dfsq = n.zeros_like(vort)
# dfsq = [your code here]
return dfsq
```
Let's define a function to perform some number of time steps
```
def integrate(nforward, dtime):
for n in range(nforward):
# evaluate the second derivative
dfsq = 0.25*(np.roll(f,+1) - 2.* f + np.roll(f,-1))/(dx*dx)
# formulate the tendency
dfdt = eta*dfdq
# step forward
f = f + dtime*dfdt
```
```
# step forward by 10 steps, then plot again
forward_step(10,dtime)
# step forward more steps, and plot again
forward_step(10,dtime)
```
# The gernal case
In the case above, an analytic solution exists, and we can check out results. Notice that buy design the function as a sum of sine waves could be generalized:
$$
\zeta(x,t=0) = \sum_{n} A_n sin(x - c_n)
$$
or more formally, a Fourier series. Since a fourier series can describe any arbitrary function, our method can evaluate any function, not just sines and cosines!
Try your clculation again, but start by defining a random function!
```
# random numbers!
vort[] = np.random.rand(npts)
```
Explain the result in the context of your findings above. Do your conclusions hold up?!
## Bonus!
The vorticity is related only to the velocity v. Develop a numerical method to calulate the velocity, v.
*Task*: Create a time series graph of kinetic energy as a function of time. Does the diffusion of vorticity change the kinetic energy?
```
def calc_velocity(vort, dx):
return velocity
```
| github_jupyter |
```
import sagemaker
from sagemaker import get_execution_role
print(sagemaker.__version__)
role = get_execution_role()
session = sagemaker.Session()
bucket = session.default_bucket()
prefix = 'pascalvoc'
s3_output_location = 's3://{}/{}/output'.format(bucket, prefix)
print(s3_output_location)
# Update these settings with your own subnets and security group
file_system_id = 'fs-fe36ef34'
subnets = ['subnet-63715206', 'subnet-cbf5bdbc', 'subnet-59395b00']
security_group_ids = ['sg-0aa0a1c297a49e911']
from sagemaker.inputs import FileSystemInput
efs_train_data = FileSystemInput(file_system_id=file_system_id,
file_system_type='EFS',
directory_path='/input/train')
efs_validation_data = FileSystemInput(file_system_id=file_system_id,
file_system_type='EFS',
directory_path='/input/validation')
data_channels = {'train': efs_train_data, 'validation': efs_validation_data }
import boto3
from sagemaker import image_uris
region = boto3.Session().region_name
container = image_uris.retrieve('object-detection', region)
print(container)
role = get_execution_role()
od = sagemaker.estimator.Estimator(container,
role,
instance_count=1,
instance_type='ml.p3.2xlarge',
output_path=s3_output_location,
subnets=subnets,
security_group_ids=security_group_ids)
od.set_hyperparameters(base_network='resnet-50',
use_pretrained_model=1,
num_classes=20,
epochs=1,
num_training_samples=16551,
mini_batch_size=90)
od.fit(inputs=data_channels)
od_predictor = od.deploy(initial_instance_count = 1, instance_type = 'ml.c5.2xlarge')
!wget -O test.jpg https://upload.wikimedia.org/wikipedia/commons/6/67/Chin_Village.jpg
import boto3, json
import numpy as np
runtime = boto3.Session().client(service_name='runtime.sagemaker')
with open('test.jpg', 'rb') as f:
payload = f.read()
payload = bytearray(payload)
response = runtime.invoke_endpoint(EndpointName=od_predictor.endpoint_name,
ContentType='image/jpeg',
Body=payload)
response = response['Body'].read()
response = json.loads(response)
print(response)
def visualize_detection(img_file, dets, classes=[], thresh=0.6):
"""
visualize detections in one image
Parameters:
----------
img : numpy.array
image, in bgr format
dets : numpy.array
ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...])
each row is one object
classes : tuple or list of str
class names
thresh : float
score threshold
"""
import random
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread(img_file)
plt.imshow(img)
height = img.shape[0]
width = img.shape[1]
colors = dict()
for det in dets:
(klass, score, x0, y0, x1, y1) = det
if score < thresh:
continue
cls_id = int(klass)
if cls_id not in colors:
colors[cls_id] = (random.random(), random.random(), random.random())
xmin = int(x0 * width)
ymin = int(y0 * height)
xmax = int(x1 * width)
ymax = int(y1 * height)
rect = plt.Rectangle((xmin, ymin), xmax - xmin,
ymax - ymin, fill=False,
edgecolor=colors[cls_id],
linewidth=3.5)
plt.gca().add_patch(rect)
class_name = str(cls_id)
if classes and len(classes) > cls_id:
class_name = classes[cls_id]
plt.gca().text(xmin, ymin - 2,
'{:s} {:.3f}'.format(class_name, score),
bbox=dict(facecolor=colors[cls_id], alpha=0.5),
fontsize=12, color='white')
plt.show()
%matplotlib inline
object_categories = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat',
'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person',
'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
# Setting a threshold 0.20 will only plot detection results that have a confidence score greater than 0.20.
threshold = 0.30
# Visualize the detections.
visualize_detection('test.jpg', response['prediction'], object_categories, threshold)
od_predictor.delete_endpoint()
```
| github_jupyter |
```
# version 1.5
source("https://raw.githubusercontent.com/eogasawara/mylibrary/master/myBasic.R")
source("https://raw.githubusercontent.com/eogasawara/mylibrary/master/myPreprocessing.R")
source("https://raw.githubusercontent.com/eogasawara/mylibrary/master/myClassification.R")
```
## Classification
```
iris <- datasets::iris
head(iris)
#extracting the levels for the dataset
slevels <- levels(iris$Species)
slevels
#for performance issues, you can use matrix instead of data.frame (uncomment next line to test)
#iris <- cbind(as.matrix(iris[,1:4]), Species=iris$Species)
```
## Building samples (training and testing)
```
# preparing dataset for random sampling
set.seed(1)
sr <- sample_random()
sr <- train_test(sr, iris)
iris_train = sr$train
iris_test = sr$test
tbl <- rbind(table(iris[,"Species"]),
table(iris_train[,"Species"]),
table(iris_test[,"Species"]))
rownames(tbl) <- c("dataset", "training", "test")
head(tbl)
```
## General function for testing classification methods
```
train_test <- function(model, iris_train, iris_test) {
print(class(model)[1])
model <- fit(model, iris_train)
train_prediction <- predict(model, iris_train)
iris_train_predictand = decodeClassLabels(iris_train[,"Species"])
train_eval <- evaluation.classification(iris_train_predictand, train_prediction)
print(train_eval$metrics)
plot(roc_curve(train_eval))
test_prediction <- predict(model, iris_test)
iris_test_predictand = decodeClassLabels(iris_test[,"Species"])
test_eval <- evaluation.classification(iris_test_predictand, test_prediction)
print(test_eval$metrics)
plot(roc_curve(test_eval))
}
```
## Majority class baseline prediction (Zero Rule)
Model creating and level of adjustment during training
```
train_test(classification_majority("Species", slevels), iris_train, iris_test)
```
## Decision Tree
Training the model, presenting the level of adjustment, quality of prediction, and confusion matrix.
```
train_test(classification_dtree("Species", slevels), iris_train, iris_test)
```
## Naive Bayes
```
train_test(classification_nb("Species", slevels),
iris_train, iris_test)
```
## Random Forest
```
# do not set mtry and ntree for hyperparameter optimization
# you can also set a range for them
train_test(classification_rf("Species", slevels, mtry=3, ntree=5),
iris_train, iris_test)
```
## Neural Networks - MLP using nnet
```
# do not set decay and set a range for neurons for hyperparameter optimization
# you can also set a range for them
train_test(classification_mlp("Species", slevels, size=3,decay=0.03),
iris_train, iris_test)
```
## Creating a SVM with RBF kernel
```
#do not set epsilon, cost, and kernel for hyperparameter optimization
# you can also set a range for them
train_test(classification_svm("Species", slevels, epsilon=0.0,cost=20.000),
iris_train, iris_test)
```
## knn prediction
```
# do not set k for hyperparameter optimization
# you can also set a range for it
train_test(classification_knn("Species", slevels, k=1), iris_train, iris_test)
```
## Convolutional neural networks (CNN)
```
# do not set neurons and epochs for hyperparameter optimization
# you can also set a range for them
train_test(classification_cnn("Species", slevels, neurons=16,epochs=150),
iris_train, iris_test)
```
## Convolutional neural networks (CNN)
Influence of normalization - min max
```
norm_minmax <- fit(minmax(), iris_train)
iris_train_minmax <- transform(norm_minmax, iris_train)
iris_test_minmax <- transform(norm_minmax, iris_test)
train_test(classification_cnn("Species", slevels, neurons=16,epochs=150),
iris_train_minmax, iris_test_minmax)
```
## Convolutional neural networks (CNN)
Influence of normalization - zscore
```
norm_zscore <- fit(zscore(nmean=0.5, nsd=0.5/2.698), iris_train)
iris_train_zscore <- transform(norm_zscore, iris_train)
iris_test_zscore <- transform(norm_zscore, iris_test)
train_test(classification_cnn("Species", slevels, neurons=16,epochs=150),
iris_train_zscore, iris_test_zscore)
```
| github_jupyter |
# Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The DCGAN architecture was first explored last year and has seen impressive results in generating new images, you can read the [original paper here](https://arxiv.org/pdf/1511.06434.pdf).
You'll be training DCGAN on the [Street View House Numbers](http://ufldl.stanford.edu/housenumbers/) (SVHN) dataset. These are color images of house numbers collected from Google street view. SVHN images are in color and much more variable than MNIST.

So, we'll need a deeper and more powerful network. This is accomplished through using convolutional layers in the discriminator and generator. It's also necessary to use batch normalization to get the convolutional networks to train. The only real changes compared to what [you saw previously](https://github.com/udacity/deep-learning/tree/master/gan_mnist) are in the generator and discriminator, otherwise the rest of the implementation is the same.
```
%matplotlib inline
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
import tensorflow as tf
!mkdir data
```
## Getting the data
Here you can download the SVHN dataset. Run the cell above and it'll download to your machine.
```
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
data_dir = 'data/'
if not isdir(data_dir):
raise Exception("Data directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size)
self.last_block = block_num
if not isfile(data_dir + "train_32x32.mat"):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc='SVHN Training Set') as pbar:
urlretrieve(
'http://ufldl.stanford.edu/housenumbers/train_32x32.mat',
data_dir + 'train_32x32.mat',
pbar.hook)
if not isfile(data_dir + "test_32x32.mat"):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc='SVHN Training Set') as pbar:
urlretrieve(
'http://ufldl.stanford.edu/housenumbers/test_32x32.mat',
data_dir + 'test_32x32.mat',
pbar.hook)
```
These SVHN files are `.mat` files typically used with Matlab. However, we can load them in with `scipy.io.loadmat` which we imported above.
```
trainset = loadmat(data_dir + 'train_32x32.mat')
testset = loadmat(data_dir + 'test_32x32.mat')
```
Here I'm showing a small sample of the images. Each of these is 32x32 with 3 color channels (RGB). These are the real images we'll pass to the discriminator and what the generator will eventually fake.
```
idx = np.random.randint(0, trainset['X'].shape[3], size=36)
fig, axes = plt.subplots(6, 6, sharex=True, sharey=True, figsize=(5,5),)
for ii, ax in zip(idx, axes.flatten()):
ax.imshow(trainset['X'][:,:,:,ii], aspect='equal')
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.subplots_adjust(wspace=0, hspace=0)
```
Here we need to do a bit of preprocessing and getting the images into a form where we can pass batches to the network. First off, we need to rescale the images to a range of -1 to 1, since the output of our generator is also in that range. We also have a set of test and validation images which could be used if we're trying to identify the numbers in the images.
```
def scale(x, feature_range=(-1, 1)):
# scale to (0, 1)
x = ((x - x.min())/(255 - x.min()))
# scale to feature_range
min, max = feature_range
x = x * (max - min) + min
return x
class Dataset:
def __init__(self, train, test, val_frac=0.5, shuffle=False, scale_func=None):
split_idx = int(len(test['y'])*(1 - val_frac))
self.test_x, self.valid_x = test['X'][:,:,:,:split_idx], test['X'][:,:,:,split_idx:]
self.test_y, self.valid_y = test['y'][:split_idx], test['y'][split_idx:]
self.train_x, self.train_y = train['X'], train['y']
self.train_x = np.rollaxis(self.train_x, 3)
self.valid_x = np.rollaxis(self.valid_x, 3)
self.test_x = np.rollaxis(self.test_x, 3)
if scale_func is None:
self.scaler = scale
else:
self.scaler = scale_func
self.shuffle = shuffle
def batches(self, batch_size):
if self.shuffle:
idx = np.arange(len(dataset.train_x))
np.random.shuffle(idx)
self.train_x = self.train_x[idx]
self.train_y = self.train_y[idx]
n_batches = len(self.train_y)//batch_size
for ii in range(0, len(self.train_y), batch_size):
x = self.train_x[ii:ii+batch_size]
y = self.train_y[ii:ii+batch_size]
yield self.scaler(x), self.scaler(y)
```
## Network Inputs
Here, just creating some placeholders like normal.
```
def model_inputs(real_dim, z_dim):
inputs_real = tf.placeholder(tf.float32, (None, *real_dim), name='input_real')
inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')
return inputs_real, inputs_z
```
## Generator
Here you'll build the generator network. The input will be our noise vector `z` as before. Also as before, the output will be a $tanh$ output, but this time with size 32x32 which is the size of our SVHN images.
What's new here is we'll use convolutional layers to create our new images. The first layer is a fully connected layer which is reshaped into a deep and narrow layer, something like 4x4x1024 as in the original DCGAN paper. Then we use batch normalization and a leaky ReLU activation. Next is a transposed convolution where typically you'd halve the depth and double the width and height of the previous layer. Again, we use batch normalization and leaky ReLU. For each of these layers, the general scheme is convolution > batch norm > leaky ReLU.
You keep stacking layers up like this until you get the final transposed convolution layer with shape 32x32x3. Below is the archicture used in the original DCGAN paper:

Note that the final layer here is 64x64x3, while for our SVHN dataset, we only want it to be 32x32x3.
>**Exercise:** Build the transposed convolutional network for the generator in the function below. Be sure to use leaky ReLUs on all the layers except for the last tanh layer, as well as batch normalization on all the transposed convolutional layers except the last one.
```
def generator(z, output_dim, reuse=False, alpha=0.2, training=True):
with tf.variable_scope('generator', reuse=reuse):
# First fully connected layer
x
# Output layer, 32x32x3
logits =
out = tf.tanh(logits)
return out
```
## Discriminator
Here you'll build the discriminator. This is basically just a convolutional classifier like you've build before. The input to the discriminator are 32x32x3 tensors/images. You'll want a few convolutional layers, then a fully connected layer for the output. As before, we want a sigmoid output, and you'll need to return the logits as well. For the depths of the convolutional layers I suggest starting with 16, 32, 64 filters in the first layer, then double the depth as you add layers. Note that in the DCGAN paper, they did all the downsampling using only strided convolutional layers with no maxpool layers.
You'll also want to use batch normalization with `tf.layers.batch_normalization` on each layer except the first convolutional and output layers. Again, each layer should look something like convolution > batch norm > leaky ReLU.
Note: in this project, your batch normalization layers will always use batch statistics. (That is, always set `training` to `True`.) That's because we are only interested in using the discriminator to help train the generator. However, if you wanted to use the discriminator for inference later, then you would need to set the `training` parameter appropriately.
>**Exercise:** Build the convolutional network for the discriminator. The input is a 32x32x3 images, the output is a sigmoid plus the logits. Again, use Leaky ReLU activations and batch normalization on all the layers except the first.
```
def discriminator(x, reuse=False, alpha=0.2):
with tf.variable_scope('discriminator', reuse=reuse):
# Input layer is 32x32x3
x =
logits =
out =
return out, logits
```
## Model Loss
Calculating the loss like before, nothing new here.
```
def model_loss(input_real, input_z, output_dim, alpha=0.2):
"""
Get the loss for the discriminator and generator
:param input_real: Images from the real dataset
:param input_z: Z input
:param out_channel_dim: The number of channels in the output image
:return: A tuple of (discriminator loss, generator loss)
"""
g_model = generator(input_z, output_dim, alpha=alpha)
d_model_real, d_logits_real = discriminator(input_real, alpha=alpha)
d_model_fake, d_logits_fake = discriminator(g_model, reuse=True, alpha=alpha)
d_loss_real = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_model_real)))
d_loss_fake = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_model_fake)))
g_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_model_fake)))
d_loss = d_loss_real + d_loss_fake
return d_loss, g_loss
```
## Optimizers
Not much new here, but notice how the train operations are wrapped in a `with tf.control_dependencies` block so the batch normalization layers can update their population statistics.
```
def model_opt(d_loss, g_loss, learning_rate, beta1):
"""
Get optimization operations
:param d_loss: Discriminator loss Tensor
:param g_loss: Generator loss Tensor
:param learning_rate: Learning Rate Placeholder
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:return: A tuple of (discriminator training operation, generator training operation)
"""
# Get weights and bias to update
t_vars = tf.trainable_variables()
d_vars = [var for var in t_vars if var.name.startswith('discriminator')]
g_vars = [var for var in t_vars if var.name.startswith('generator')]
# Optimize
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
d_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(d_loss, var_list=d_vars)
g_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(g_loss, var_list=g_vars)
return d_train_opt, g_train_opt
```
## Building the model
Here we can use the functions we defined about to build the model as a class. This will make it easier to move the network around in our code since the nodes and operations in the graph are packaged in one object.
```
class GAN:
def __init__(self, real_size, z_size, learning_rate, alpha=0.2, beta1=0.5):
tf.reset_default_graph()
self.input_real, self.input_z = model_inputs(real_size, z_size)
self.d_loss, self.g_loss = model_loss(self.input_real, self.input_z,
real_size[2], alpha=0.2)
self.d_opt, self.g_opt = model_opt(self.d_loss, self.g_loss, learning_rate, 0.5)
```
Here is a function for displaying generated images.
```
def view_samples(epoch, samples, nrows, ncols, figsize=(5,5)):
fig, axes = plt.subplots(figsize=figsize, nrows=nrows, ncols=ncols,
sharey=True, sharex=True)
for ax, img in zip(axes.flatten(), samples[epoch]):
ax.axis('off')
img = ((img - img.min())*255 / (img.max() - img.min())).astype(np.uint8)
ax.set_adjustable('box-forced')
im = ax.imshow(img, aspect='equal')
plt.subplots_adjust(wspace=0, hspace=0)
return fig, axes
```
And another function we can use to train our network. Notice when we call `generator` to create the samples to display, we set `training` to `False`. That's so the batch normalization layers will use the population statistics rather than the batch statistics. Also notice that we set the `net.input_real` placeholder when we run the generator's optimizer. The generator doesn't actually use it, but we'd get an errror without it because of the `tf.control_dependencies` block we created in `model_opt`.
```
def train(net, dataset, epochs, batch_size, print_every=10, show_every=100, figsize=(5,5)):
saver = tf.train.Saver()
sample_z = np.random.uniform(-1, 1, size=(72, z_size))
samples, losses = [], []
steps = 0
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for e in range(epochs):
for x, y in dataset.batches(batch_size):
steps += 1
# Sample random noise for G
batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size))
# Run optimizers
_ = sess.run(net.d_opt, feed_dict={net.input_real: x, net.input_z: batch_z})
_ = sess.run(net.g_opt, feed_dict={net.input_z: batch_z, net.input_real: x})
if steps % print_every == 0:
# At the end of each epoch, get the losses and print them out
train_loss_d = net.d_loss.eval({net.input_z: batch_z, net.input_real: x})
train_loss_g = net.g_loss.eval({net.input_z: batch_z})
print("Epoch {}/{}...".format(e+1, epochs),
"Discriminator Loss: {:.4f}...".format(train_loss_d),
"Generator Loss: {:.4f}".format(train_loss_g))
# Save losses to view after training
losses.append((train_loss_d, train_loss_g))
if steps % show_every == 0:
gen_samples = sess.run(
generator(net.input_z, 3, reuse=True, training=False),
feed_dict={net.input_z: sample_z})
samples.append(gen_samples)
_ = view_samples(-1, samples, 6, 12, figsize=figsize)
plt.show()
saver.save(sess, './checkpoints/generator.ckpt')
with open('samples.pkl', 'wb') as f:
pkl.dump(samples, f)
return losses, samples
```
## Hyperparameters
GANs are very senstive to hyperparameters. A lot of experimentation goes into finding the best hyperparameters such that the generator and discriminator don't overpower each other. Try out your own hyperparameters or read [the DCGAN paper](https://arxiv.org/pdf/1511.06434.pdf) to see what worked for them.
>**Exercise:** Find hyperparameters to train this GAN. The values found in the DCGAN paper work well, or you can experiment on your own. In general, you want the discriminator loss to be around 0.3, this means it is correctly classifying images as fake or real about 50% of the time.
```
real_size = (32,32,3)
z_size = 100
learning_rate = 0.001
batch_size = 64
epochs = 1
alpha = 0.01
beta1 = 0.9
# Create the network
net = GAN(real_size, z_size, learning_rate, alpha=alpha, beta1=beta1)
# Load the data and train the network here
dataset = Dataset(trainset, testset)
losses, samples = train(net, dataset, epochs, batch_size, figsize=(10,5))
fig, ax = plt.subplots()
losses = np.array(losses)
plt.plot(losses.T[0], label='Discriminator', alpha=0.5)
plt.plot(losses.T[1], label='Generator', alpha=0.5)
plt.title("Training Losses")
plt.legend()
_ = view_samples(-1, samples, 6, 12, figsize=(10,5))
```
| github_jupyter |
# Considering our data
Our initial goal was to apply a ML approach to accurately predict the likelihood of a wildfire occuring. The data we used was first balanced so we had an equal amount of data for both occasions with and without fires. This data was stored in CSV format. Using the Python library Pandas we can analyse the structure of this CSV.
```
import pandas as pd
df = pd.io.parsers.read_csv(
'Data/NewBalanced.csv',
)
print(df.shape)
print('\n')
print(df.head(5))
print('\n')
print(df.tail(1))
```
This file has 23 features and 10,341 data points. Clearly not all of these features are useful for training a model. For example we have date and location. By applying principal component analysis (https://en.wikipedia.org/wiki/Principal_component_analysis) to our data we decided that the 7 features: 'avgTemp', 'avgWind', '14dayAvgTemp', '14dayAvgHum' and '14DayAvgRain' were most conducive to values in the 'Fire' column for whom a 1 corresponds to their being a fire and a 0 to no fire. Next came model selection. Due to the relatively small amount of data we had relative to the number of useful features we opted to go with a Support Vector Machine based model.
# Support Vector Machines
A Support Vector Machine (or SVM for short) is a supervised ML method that can be used for classification of data. Each data item is plotted in n-dimensional space (where n corresponds to the number of features) and then classification is performed by finding a hyperplane that differentiates the classes of the data well. It does so by finding vectors (data points) belonging to each class and basing the position of the hyperplane upon the position of these vectors. These vectors are known as support vectors hence the name.

SVM's work particuarly well when the order of the feature-space is large (as in our case) because as its size increases its more likely that the classes will form distinct clusters allowing for a better fitting hyperplane. In addition having a relatively small amount of data isn't game over as presuming the classes form relatively tight data clusters hyperplanes fitted to larger datasets will still be in a similar place to smaller datasets. It is for these reasons we opted to go with a SVM model to make our predictions. Obviously we are assuming that our relatively small dataset is representative of what datap in the class generally looks like and training on a larger dataset likely wouldnt hurt. This is something we would like to improve our model by doing if provided with the resources.
# A SVM in the context of Wildfires
In the context of our data the classes we are training to classify are given by the 'Fire' column in the CSV file (0 for no fire and 1 for fire). We shall consider only the features we deemed important through PCA when training our model. Construction of the dataFrame and splitting of data looks like this:
```
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
df = pd.io.parsers.read_csv(
'Data/NewBalanced.csv',
header=None,
skiprows = [0],
usecols=[5,10,15,17,18,19,20,22]
)
X = df.values[:,:7]
y = df.values[:,7]
#split the data into training and testing data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=12345)
```
Next we have to standardise the data. Standardisation is an integral part of preprocessing for an SVM. It ensures all features exist on the same scale.
```
from sklearn import preprocessing
std_scale = preprocessing.StandardScaler().fit(X_train) #allows data to be standardised under the same scale
X_train_std = std_scale.transform(X_train)
X_test_std = std_scale.transform(X_test)
```
Implementing an SVM from scratch would be a tedious and tricky process. Luckily Scikit-Learn has already done so by creating a python wrapper for the C++ library LibSVM. LibSVM is a very efficient library for running SVM related tasks.
```
from sklearn.svm import SVC
clf = SVC(C=1.0, cache_size=200, class_weight='balanced', coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=True, random_state=None, shrinking=True,
tol=0.001, verbose=False)
clf.fit(X_train,y_train)
```
Of the input parameters above, the most important are C, class_weight, gamma and kernel. The purpose of C is to decide the trade off between fitting the model to the training set and maintaining a smooth hyperplane. class_weight simply denotes the structure of the training data provided relative to its classes. Our data is balanced hence we have used that here. gamma corresponds to how much influence a single training point has over the fitting of the hyperplane. In this example we have let sklearn select gamma automatically. Finally the kernel is the function that is responsible for finding the mathematical relationship between the independent feature vectors and corresponding classes. In our case we have selected 'rbf' or 'radial based field'. This kernel allows fitting of a non linear hyperplane to the data. This is useful as the relationship between our features (i.e. avgtemp, avghumid etc) and our classes (Fire, No fire) may not necessarily be linear.
The above code equates to training the model. Predictions can now be made with the following code snippet
```
clf.predict(X_test)
```
In addition an accuracy score can be calculated similarily:
```
print('Accuracy is: {}%'.format(clf.score(X_test, y_test, sample_weight=None)*100))
```
This accuracy can be tweaked by changing hyper-parameters used to train the model as well as altering the data that is trained upon by means of changing the seed when splitting the data. Our final model obtains an accuracy of x%.
## What about probability though?
When designing a model for a scenario such as a wildfire it would be far more useful to have probability values associated with the classe outcomes predicted. Unfortunately this is not an out of the box functionality of SVM's. Luckily however, it can be achieved by applying a procedure known as Platt scaling (https://en.wikipedia.org/wiki/Platt_scaling). Essentially this approach applies a probability distribution to predicted classes by means of the sigmoid function. In doing so it allows us to associate probabilities of data points being in certain classes. LibSVM, thus by proxy Scikit-Learn has an efficient implementation of this procedure which means it is only a single line to do so:
```
clf.predict_proba(X_test)
```
# Making predictions
Predictions can be made using this model by first retrieving the prediction data values from a CSV, standardising them under the same scale used for the training and then running Scikit-Learn's predict() function as shown earlier. For example:
```
foredf = pd.io.parsers.read_csv(
'Data/svminput.csv',
header=None,
skiprows = [0],
usecols=[1,2,3,4,5,6,8,9,10,11]
)
X_forecast = foredf.values[:,3:]
X_forecast_std = std_scale.transform(X_forecast)
fore_pred = clf.predict(X_forecast_std)
```
We then opted to append the predictions array above to a pandas dataFrame and compile that data frame as a new CSV 'svmoutput.csv'
```
forearray = foredf.values.tolist()
i = 0
for element in forearray:
element.append(fore_pred[i])
#element.append(fore_prob[i][1])
i +=1
df = pd.DataFrame(forearray)
df.to_csv('Data/svmoutput.csv')
```
As you can imagine the generated CSV has the same format as the input CSV with the only exception being the appended prediction column added to the end.
```
df = pd.io.parsers.read_csv(
'Data/svmoutput.csv',
)
print(df.shape)
print('\n')
print(df.head(10))
```
# Our code in practice
The ideas and code snippets above are the basis for our code. We have opted to use an object orientated approach as this lends us several advantages such as clarity and generalisability. Below is an example of a script that utilises our code to process, standardise, train then test a model. It outputs a prediction for every value in the test dataset along with its probability (calculated through Platt scaling) and the correct value. Finally it outputs the overall accuracy the model achieved when making predictions upon the dataset.
```
'''
Author: Flinn Dolman
@License: MIT
An example script that leverages our code to train a model and make predictions based upon it. Predictions
are printed to stdout and then the model used to make the predictions is saved.
'''
from SVM import SVM
from Standardiser import Standardiser
def Main():
forecast_loc = 'Data/svminput.csv'
standard_data = Standardiser()
standard_data.initialise()
clf = SVM()
clf.initialise(standard_data.get_std_X_train(),standard_data.get_std_X_test(),standard_data.get_y_train(),standard_data.get_y_test())
print('\nThese are the predictions: {}\n'.format(clf.predictions()))
predictions, probs = clf.predictions()
y_test = standard_data.get_y_test()
for i in range(0,len(predictions)-1):
print('Prediction: {}, with probability: {}, correct value: {}'.format(predictions[i],probs[i], y_test[i]))
print('Accuracy is: {}%'.format(clf.accuracy()*100))
fore_Pred, fore_Prob = clf.forecast_Pred(standard_data.loadForecast(forecast_loc))
standard_data.make_CSV(fore_Pred,fore_Prob,'Data/svmoutputnew.csv')
clf.saveModel()
if __name__ =="__main__":
Main()
```
The structure of our code means that all this script is really responsible for is initialisation of objects and the formatting of the predictions, probabilities and correct values.
| github_jupyter |
<a href="https://colab.research.google.com/github/HarshZ26/Object-Detection/blob/master/Raccoon_ML.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!ls
! git clone "https://github.com/datitran/raccoon_dataset.git"
%matplotlib inline
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
import csv
import matplotlib.pyplot as plt
import torch
import torch.utils.data
import torchvision
import numpy as np
from PIL import Image
import torchvision.transforms as transforms
from random import randrange
import torch.nn as nn
import torch.nn.functional as F
import imutils
import cv2
def xml_to_csv(path):
xml_list = []
for xml_file in glob.glob(path + '/*.xml'):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('object'):
value = (root.find('filename').text,
int(root.find('size')[0].text),
int(root.find('size')[1].text),
member[0].text,
int(member[4][0].text),
int(member[4][1].text),
int(member[4][2].text),
int(member[4][3].text)
)
xml_list.append(value)
column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
xml_df = pd.DataFrame(xml_list, columns=column_name)
return xml_df
def main():
image_path = '/content/raccoon_dataset/annotations'
xml_df = xml_to_csv(image_path)
xml_df.to_csv('raccoon_labels.csv', index=None)
print(xml_df)
print('Successfully converted xml to csv.')
main()
# opening the CSV file
with open('/content/raccoon_labels.csv', mode ='r')as file:
# reading the CSV file
csvFile = csv.reader(file)
# displaying the contents of the CSV file
for lines in csvFile:
print(lines)
class myOwnDataset(torch.utils.data.Dataset):
def __init__(self, root_img, root_label, transforms=None,id = None):
self.root_img = root_img
self.root_label = root_label
# the list of filename
self.transforms = transforms
self.file = open(root_label)
self.reader = csv.reader(self.file)
temp_lis1 = list(self.reader)
self.lis = temp_lis1[1:] + temp_lis1[1:90]
self.id = id
# the list of label
def __getitem__(self, index):
# obtain filenames from list
image_filename = self.lis[index][0]
# Load data and label
image = Image.open(os.path.join(self.root_img, image_filename),'r')
# print(type(image))
width,height,cls,xmin,ymin,xmax,ymax = self.lis[index][1:]
if self.id==1:
if index >170:
cls=0
im1 = image.crop((0,0,64,64))
else:
cls = 1
im1 = image.crop((int(xmin),int(ymin), int(xmax), int(ymax)))
if self.id==0:
if index >44:
cls=0
im1 = image.crop((0,0,64,64))
else:
cls = 1
im1 = image.crop((int(xmin),int(ymin), int(xmax), int(ymax)))
temp_var1 ,temp_var2 = image.size
im1 = im1.resize((256, 256))
mulx = 256/temp_var1
muly = 256/temp_var2
box = [[round(int(xmin)*mulx),round(int(ymin)*muly), round(int(xmax)*mulx), round(int(ymax)*muly)]]
# Bounding boxes for objects
# In pytorch, the input should be [xmin, ymin, xmax, ymax]
cls = torch.tensor(int(cls), dtype=torch.int64)
box = torch.tensor(box).squeeze()
# Size of bbox (Rectangular)
if self.transforms is not None:
image = self.transforms(im1)
return image,cls,box
def __len__(self):
return len(self.lis)
def get_transform():
custom_transforms = []
custom_transforms.append(torchvision.transforms.ToTensor())
return torchvision.transforms.Compose(custom_transforms)
# to remove grayscale images from directory and updating the labels
path_img = '/content/raccoon_dataset/images'
path_label = '/content/raccoon_dataset/data/train_labels.csv'
df = pd.read_csv("/content/raccoon_dataset/data/train_labels.csv")
# updating the column value/data
print(df.loc[df['filename']=='raccoon-161.jpg'])
print(df.loc[df['filename']=='raccoon-150.jpg'])
print(df.loc[df['filename']=='raccoon-152.jpg'])
df.drop(index = 124,inplace = True)
df.drop(index = 135,inplace = True)
df.drop(index = 172,inplace = True)
df.to_csv("AllDetails.csv", index=False)
# writing into the file
# path to your own data and csv file
train_data_dir = '/content/raccoon_dataset/images'
train_label = '/content/AllDetails.csv'
test_data_dir = '/content/raccoon_dataset/images'
test_label = '/content/raccoon_dataset/data/test_labels.csv'
batchsize = 32
# create own Dataset
train_dataset = myOwnDataset(root_img = train_data_dir,root_label = train_label ,
transforms = get_transform(),id = 1
)
test_dataset = myOwnDataset(root_img = test_data_dir,root_label = test_label ,
transforms = get_transform(),id = 0
)
def collate_fn(batch):
data = [item[0] for item in batch]
target = [item[1] for item in batch]
box = [item[2] for item in batch]
target = torch.LongTensor(target)
box = torch.stack(box,dim=0)
data = torch.stack(data,dim=0)
return [data, target,box]
# own DataLoader
train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=batchsize,
shuffle=True,
collate_fn = collate_fn)
test_loader = torch.utils.data.DataLoader(test_dataset,
batch_size=batchsize,
shuffle=True,
collate_fn = collate_fn)
train_features, train_labels,train_box= next(iter(test_loader))
print(f"Feature batch shape: {train_features.size()}")
print(f"Labels batch shape: {len(train_labels)}")
print('box',train_box.size())
img = train_features[0].squeeze()
img1 = train_features[0].squeeze()
img = torchvision.transforms.functional.convert_image_dtype(image= img,dtype=torch.uint8)
img = img.numpy()
im2display = img.transpose((1,2,0))
plt.imshow(im2display, interpolation='nearest')
# def imshow(img):
# npimg = img.numpy()
# plt.imshow(np.transpose(npimg, (1, 2, 0)))
# plt.show()
# #Get some random training images
# dataiter = iter(train_loader)
# images, labels,box = dataiter.next()
# #Show images
# imshow(torchvision.utils.make_grid(images))
num_epochs = 20
num_classes = 2
batch_size = 32
learning_rate = 0.001
class ConvNet(nn.Module):
def __init__ (self):
super(ConvNet,self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3,32, kernel_size =11, stride=1, padding =2),
nn.ReLU(),
nn.MaxPool2d(kernel_size =4,stride = 2),
nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),
nn.ReLU(),
nn.MaxPool2d(kernel_size=4, stride=2),
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=2),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2))
self.classifier = nn.Sequential(
nn.Conv2d(256,128, kernel_size=15, stride=1, padding=0),
nn.ReLU(),
nn.Conv2d(128,64,kernel_size = 1,stride = 1,padding = 0),
nn.ReLU(),
nn.Conv2d(64,num_classes,kernel_size = 1,stride = 1,padding = 0)
)
self.regressor = nn.Sequential(
nn.Conv2d(256,128, kernel_size=15, stride=1, padding=0, bias=False),
nn.ReLU(),
nn.Conv2d(128,64,kernel_size = 1,stride = 1,padding = 0, bias=False),
nn.ReLU(),
nn.Conv2d(64,4,kernel_size = 1,stride = 1,padding = 0,bias=False)
)
def forward(self,x):
out = self.features(x)
out1 = self.classifier(out)
out2 = self.regressor(out)
return out1,out2
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = ConvNet().to(device)
criterion1 = nn.CrossEntropyLoss()
criterion2 = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(),lr = learning_rate)
model.train()
#train featurizer and classifier
total_step = len(train_loader)
correct_epoch = []
loss_lis1 = []
acc_lis = []
for epoch in range(num_epochs):
num_correct = 0
num_total = 0
for i,(images,labels,box) in enumerate(train_loader):
images, labels,box = images.to(device), labels.to(device), box.to(device)
#Run the forward pass
outputs,_= model(images)
outputs = outputs.reshape(outputs.size(0),-1)
#print("labels",labels)
#print(outputs.size(),labels)
loss = criterion1(outputs,labels)
loss_lis1.append(loss.item())
#Backprop
optimizer.zero_grad()
loss.backward()
optimizer.step()
#track accuracy
total = labels.size(0)
_ , predicted = torch.max(outputs.data,1)
correct = (predicted ==labels).sum().item()
acc_lis.append(correct/total)
num_correct += correct
num_total += total
if (i+1)%4 == 0:
print('Epoch [{}/{}],Step [{}/{}], Loss {: .4f}, Accuracy: {:.2f}%'
.format(epoch + 1, num_epochs, i + 1, total_step, loss.item(),
(correct / total) * 100))
correct_epoch.append((num_correct/num_total)*100)
# testing the trained classifier
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels,_ in test_loader:
images, labels = images.to(device), labels.to(device)
outputs,_ = model(images)
outputs = outputs.reshape(outputs.size(0),-1)
print(outputs[0])
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy of the model test images: {} %'.format((correct / total) * 100))
print('correct: '+str(correct)+'\t'+ 'total:'+str(total))
print(correct_epoch)
plt.plot(loss_lis1)
plt.show()
plt.plot(acc_lis)
plt.show()
# another dataset to train regressor
class myOwnDataset(torch.utils.data.Dataset):
def __init__(self, root_img, root_label, transforms=None):
self.root_img = root_img
self.root_label = root_label
# the list of filename
self.transforms = transforms
self.file = open(root_label)
self.reader = csv.reader(self.file)
temp_lis1 = list(self.reader)
self.lis = temp_lis1[1:]
# the list of label
def __getitem__(self, index):
# obtain filenames from list
image_filename = self.lis[index][0]
# Load data and label
image = Image.open(os.path.join(self.root_img, image_filename),'r')
# print(type(image))
width,height,cls,xmin,ymin,xmax,ymax = self.lis[index][1:]
cls = 1
temp_var1 ,temp_var2 = image.size
im1 = image.resize((256, 256))
mulx = 256/temp_var1
muly = 256/temp_var2
box = [[round(int(xmin)*mulx),round(int(ymin)*muly), round(int(xmax)*mulx), round(int(ymax)*muly)]]
box = torch.tensor(box).squeeze()
# Bounding boxes for objects
# In pytorch, the input should be [xmin, ymin, xmax, ymax]
cls = torch.tensor(int(cls), dtype=torch.int64)
if self.transforms is not None:
image = self.transforms(im1)
return image,cls,box
def __len__(self):
return len(self.lis)
valid_data_dir = '/content/raccoon_dataset/images'
valid_label = '/content/AllDetails.csv'
batchsize = 32
# create own Dataset
valid_dataset = myOwnDataset(root_img = valid_data_dir,root_label = valid_label,
transforms = get_transform()
)
def collate_fn(batch):
data = [item[0] for item in batch]
target = [item[1] for item in batch]
box = [item[2] for item in batch]
target = torch.LongTensor(target)
box = torch.stack(box,dim=0)
data = torch.stack(data,dim=0)
return [data, target,box]
# own DataLoader
valid_loader = torch.utils.data.DataLoader(valid_dataset,
batch_size=batchsize,
shuffle=True,
collate_fn = collate_fn)
valid_features, valid_labels,bbox= next(iter(valid_loader))
print(f"Feature batch shape: {valid_features.size()}")
print('box',bbox[0])
# print(f"Labels batch shape: {len(train_labels)}")
img = valid_features[0].squeeze()
img2 = valid_features
print(img2.size())
img1 = valid_features
# img1 = torchvision.transforms.functional.convert_image_dtype(image= img2,dtype=torch.uint8)
img1 = img1.numpy()
img = torchvision.transforms.functional.convert_image_dtype(image= img,dtype=torch.uint8)
img = img.numpy()
im2display = img.transpose((1,2,0))
plt.imshow(im2display, interpolation='nearest')
print(valid_labels)
# freezing featurizer and classifier parameters
learning_rate = 0.005
params = model.state_dict()
key = list(params.keys())
model.features[0].weight.requires_grad = False
model.features[0].bias.requires_grad = False
model.features[3].weight.requires_grad = False
model.features[3].bias.requires_grad = False
model.features[6].weight.requires_grad = False
model.features[6].bias.requires_grad = False
model.features[9].weight.requires_grad = False
model.features[9].bias.requires_grad = False
model.classifier[0].weight.requires_grad = False
model.classifier[0].bias.requires_grad = False
model.classifier[2].weight.requires_grad = False
model.classifier[2].bias.requires_grad = False
model.classifier[4].weight.requires_grad = False
model.classifier[4].bias.requires_grad = False
# model.features.requires_grad = True
# model.classifier.requires_grad = True
for name, param in model.named_parameters():
if param.requires_grad:print(name)
optimizer2 = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()),lr = learning_rate)
model.train()
#train regressor
total_step = len(valid_loader)
num_epochs = 100
correct_epoch = []
loss_lis2 = []
for epoch in range(num_epochs):
num_correct = 0
num_total = 0
for i,(images,_,box) in enumerate(valid_loader):
images,box = images.to(device),box.to(device,dtype=torch.float32)
#Run the forward pass
_,outputs= model(images)
outputs = outputs.reshape(outputs.size(0),-1)
#print("labels",labels)
#print(outputs.size(),labels)
loss = criterion2(outputs,box)
loss_lis2.append(loss.item())
#Backprop
optimizer2.zero_grad()
loss.backward()
optimizer2.step()
if (i+1)%4 == 0:
print('Epoch [{}/{}],Step [{}/{}], Loss {: .4f}'.format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))
# testing regressor
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images,_,box in test_loader:
images ,box= images.to(device), box.to(device)
_,outputs = model(images)
outputs = outputs.reshape(outputs.size(0),-1)
print(outputs[0],box[0])
plt.plot(loss_lis2)
plt.show()
# for large images
class myOwnDataset(torch.utils.data.Dataset):
def __init__(self, root_img, root_label, transforms=None):
self.root_img = root_img
self.root_label = root_label
# the list of filename
self.transforms = transforms
self.file = open(root_label)
self.reader = csv.reader(self.file)
temp_lis1 = list(self.reader)
self.lis = temp_lis1[1:]
# the list of label
def __getitem__(self, index):
# obtain filenames from list
image_filename = self.lis[index][0]
# Load data and label
image = Image.open(os.path.join(self.root_img, image_filename),'r')
# print(type(image))
width,height,cls,xmin,ymin,xmax,ymax = self.lis[index][1:]
cls = 1
temp_var1 ,temp_var2 = image.size
im1 = image.resize((512, 512))
mulx = 512/temp_var1
muly = 512/temp_var2
box = [[round(int(xmin)*mulx),round(int(ymin)*muly), round(int(xmax)*mulx), round(int(ymax)*muly)]]
box = torch.tensor(box).squeeze()
# number of objects in the image
# Bounding boxes for objects
cls = torch.tensor(int(cls), dtype=torch.int64)
if self.transforms is not None:
image = self.transforms(im1)
return image,cls,box
def __len__(self):
return len(self.lis)
valid_data_dir = '/content/raccoon_dataset/images'
valid_label = '/content/raccoon_dataset/data/test_labels.csv'
batchsize = 1
# create own Dataset
valid_dataset = myOwnDataset(root_img = valid_data_dir,root_label = valid_label,
transforms = get_transform()
)
def collate_fn(batch):
data = [item[0] for item in batch]
target = [item[1] for item in batch]
box = [item[2] for item in batch]
target = torch.LongTensor(target)
box = torch.stack(box,dim=0)
data = torch.stack(data,dim=0)
return [data, target,box]
# own DataLoader
valid_loader = torch.utils.data.DataLoader(valid_dataset,
batch_size=batchsize,
shuffle=True,
collate_fn = collate_fn)
def pyramid(image,scale,miniSize = (256,256)):
yield image
while True:
w = int(image.shape[1]/scale)
image = imutils.resize(image,width = w)
if image.shape[0] < miniSize[1] or image.shape[1] < miniSize[0]:
break
yield image
def sliding_window(image,stepSize,windowSize):
t_img = image.transpose((2,0,1))
test_img = np.expand_dims(t_img, axis=0)
test_img = torch.tensor(test_img)
return mod(test_img)
# yield (x,y,image[y:y+ windowSize[1],x:x + windowSize[0]])
def mod(ig):
model.eval()
with torch.no_grad():
ig = ig.to(device)
outputs,bux = model(ig)
print('result',outputs.size())
probabilities = torch.nn.functional.softmax(outputs[0], dim=0)
bux = bux.cpu()
bux = bux.numpy()
result = probabilities.cpu()
result = result.numpy()
print(np.shape(result),np.shape(bux[0]))
return result,bux[0]
valid_features, valid_labels,bbox= next(iter(valid_loader))
print(f"Feature batch shape: {valid_features.size()}")
print('box',bbox[0])
# print(f"Labels batch shape: {len(train_labels)}")
img = valid_features[0].squeeze()
img2 = valid_features
print(img2.size())
img1 = valid_features
# img1 = torchvision.transforms.functional.convert_image_dtype(image= img2,dtype=torch.uint8)
img1 = img1.numpy()
img = torchvision.transforms.functional.convert_image_dtype(image= img,dtype=torch.uint8)
img = img.numpy()
im2display = img.transpose((1,2,0))
plt.imshow(im2display, interpolation='nearest')
print(valid_labels)
print(np.shape(img1))
image = img1[0].transpose((1,2,0))
print(np.shape(image))
print(bbox)
winH = 256
winW = 256
cord_lis = []
font = cv2.FONT_HERSHEY_SIMPLEX
imgs = image.copy()
m = 1
for resized in pyramid(image, scale=1.2):
blocks,cords = sliding_window(resized,1,(256,256))
lengt = np.shape(blocks)[1]
for y in range(lengt):
for x in range(lengt):
if blocks[1][x][y]>0.999976 and m>1.5 :
tx =8*x*m
ty = 8*y*m
cord_lis.append((round(cords[0][x][y]*m + tx),round(cords[1][x][y]*m+ ty),round(cords[2][x][y]*m + tx),round(cords[3][x][y]*m+ ty)))
# cv2.rectangle(imgs, (8*x, 8*y), (8*x + winW, 8*y + winH), (255, 0, 0), 2)
# cv2.putText(imgs, "Raccoon", (8*x,8*y), font, 1, (255,0,0), 3, cv2.LINE_AA)
m = m*1.2
# storing coordinates into list and plotting them at end
cv2.rectangle(imgs, (bbox[0][0], bbox[0][1]), (bbox[0][2], bbox[0][3]), (0, 255, 0), 2)
for item in cord_lis:
cv2.rectangle(imgs, (item[0], item[1]), (item[2], item[3]), (255, 0, 0), 3)
plt.imshow(imgs)
plt.show()
# t_img = image[y:y+winH,x:x+winW]
# # t_img = t_img.transpose((2,0,1))
# # print("test",np.shape(t_img))
# test_img = np.expand_dims(t_img, axis=0)
# # print("test",np.shape(test_img))
# test_img = torch.tensor(test_img)
# tet = Image.fromarray(t_img,'RGB')
# result = foo(tet)
# result = result.cpu()
# result = result.numpy()
# # with open("imagenet_classes.txt", "r") as f:
# # categories = [s.strip() for s in f.readlines()]
# # Show top categories per image
# font = cv2.FONT_HERSHEY_SIMPLEX
# txt = cls_lis[np.argmax(result)]
# cv2.rectangle(clone, (x, y), (x + winW, y + winH), (255, 0, 0), 2)
# cv2.rectangle(clone, (bbox[0][0], bbox[0][1]), (bbox[0][2], bbox[0][3]), (0, 255, 0), 2)
# cv2.putText(clone, txt, (x,y), font, 1, (255,0,0), 3, cv2.LINE_AA)
# plt.imshow(clone)
# plt.show()
# plt.clf()
```
| github_jupyter |
# Using DataYoink's Pretrained Mask
This demo is inteded for users who have images of battery discharge curves from which they want to extract points. This can be accomplished easily by following the steps below in a jupyter notebook.
## Step 1: Import all requred packages
The import statements below may need to be modified based on where the requred .py files appear in your directory
```
from pyfiles_for_demos.coordconverter import datayoink_to_excel, get_axis_info
from pyfiles_for_demos.img_rescale import img_rescale
from pyfiles_for_demos.predict import predict_discharge_curve
from pyfiles_for_demos.predict import show_output_img_and_mask
from pyfiles_for_demos.pointclassifier import pointclassifier
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
matplotlib.rcParams.update({'font.size': 26})
%matplotlib inline
%matplotlib notebook
import ipywidgets as wdg
from ipywidgets import ToggleButtons
import pandas as pd
import numpy as np
import math
import xlsxwriter
```
## Step 2: Load and resize Image
Store the path to the figure you want to make prediction on in the variable *image_PNG*. REsize the image to the desired image height and width by specifying the variables *image_height* and *image_width*. This can be used to downsize an image for faster prediction. The pretrained mm is trained by 400(height) by 600(width) images. Resizing your image to this scale might improve the prediction accuracy.
```
image_PNG = "Test_bw.png"
image_height = 400
image_width = 600
rescaled_img = img_rescale(image_PNG, image_height, image_width)
```
## Step 3: Provide information about the image
###### Once you run the cell below, in the plot area, use your mouse to click on the following:
* 1.) Origin
* 2.) X-axis max (this should match the location of the ```x max value``` entered below)
* 3.) Y-axis max (this should match the location of the ```y max value``` entered below)
###### Notes:
* These points are used to establish scaling between pixels and coordinate locations on the graph area and will affect the accuracy of the values saved in the final excel file
* Be careful not to accidentally add extra clicks, in the case you do, re-run the cell
* Below the plot, there is a textbox named "event:" where, everytime you click on the image, a event is captured at the position where you clicked your mouse on the image, verify there is only 3 points selected (scroll down before you start clicking)
* Use the horizontal scroll bar below the image if part of your plot is cut-off
```
# Initialize array of x and y pixels
x = []
y = []
# Load in a discharge curve
img = mpimg.imread("Test_bw.png")
fig = plt.figure(figsize=(15,10))
plt.imshow(img)
plt.axis('off')
# Create and display textarea widget
txt = wdg.Textarea(
value='',
placeholder='',
description='event:',
disabled=False)
display(txt)
print("please select")
# Function to record mouse click events
def onclick(event):
txt.value = str(event) # Dynamically update the text box above
# Create an hard reference to the callback not to be cleared by the garbage collector
x.append(event.xdata)
y.append(event.ydata)
ka = fig.canvas.mpl_connect('button_press_event', onclick)
```
###### Results of selected points:
```
xpixels = [round(num, -1) for num in x]
ypixels = [round(num, -1) for num in y]
print("the x coordinates are", xpixels)
print("the y coordinates are", ypixels)
userpoints = np.column_stack( (xpixels, ypixels) )
origin, xpixelmax, ypixelmax = pointclassifier(userpoints)
```
###### Next, define the range of the x and y axes by answering prompts:
The image is recreated below for reference. Answer in the units provided in the graph.
```
fig = plt.figure(figsize=(10, 5))
plt.imshow(img)
plt.axis('off')
xcoordinatemin = float(input("Enter the x min value on the x-axis:"))
xcoordinatemax = float(input("Enter the x max value on the x-axis:"))
ycoordinatemin = float(input("Enter the y min value on the y-axis:"))
ycoordinatemax = float(input("Enter the y max value on the y-axis:"))
assert type(xcoordinatemin) == float, 'User input for the min X value on the x-axis is not the correct datatype'
assert type(xcoordinatemin) == float, 'User input for the max X value on the y-axis is not the correct datatype'
assert xcoordinatemin < xcoordinatemax, 'The min X value on the x-axis is greater than the max X value on the x-axis'
assert type(ycoordinatemin) == float, 'User input for the min Y value on the y-axis is not the correct datatype'
assert type(ycoordinatemin) == float, 'User input for the max Y value on the y-axis is not the correct datatype'
assert ycoordinatemin < ycoordinatemax, 'The min Y value on the y-axis is greater than the max Y value on the y-axis'
print("the range of the x-axis is", "(", xcoordinatemin, ",", xcoordinatemax, ")")
print("the range of the y-axis is", "(", ycoordinatemin, ",", ycoordinatemax, ")")
```
###### Specify the maximum number of points you would like to see along the x axis:
```
max_points = int(input("Enter the max number of points desired for the x-axis:"))
assert type(max_points) == int, 'User input for the number of points should be an integer'
assert max_points > 5, 'Choose more points'
```
###### Use the options below to select units along the x and y axes that match those in the graph
```
xunits = ToggleButtons(options=['mAh/g', 'mAh', 'mAh/cm^2', 'μAh/g', 'μAh/cm^2', 'Ah/(g * V)'])
yunits = ToggleButtons(options=['Cycle Number', 'Voltage (V)'])
xunits
yunits
units = [xunits.value,yunits.value]
print("You have selected your x-axis units as:", xunits.value, "\nYou have selected your y-axis units as:", yunits.value)
```
## Step 4: Run detectron2 using the pretrained model
Download the [pretrained nn] and the [configuration file] and place them in a folder named "output" in the current directory.
- No Arguments need to be modified n the cell below
- A new folder named "scaled_input_image" will be created in the current directory to stored the rescaeld .png input image
```
pretrained_pkl = "./output/BEST_config.pkl"
outputs = predict_discharge_curve(pretrained_pkl,rescaled_img)
show_output_img_and_mask("scaled_input_image/scaled_"+image_PNG, outputs)
```
## Step 5. Use DataYoink to save coordinates to excel
The arguments for the following functions (except the filename, see below) do not need to be modified, they refer to variables already created by the above code.
#### Filenames:
You may specify the base filename (in the datayoink_to_excel function) if desired. If only one image is run at a time, the resulting excel file will have the name ```filename```. If multiple are run at once (available in future versions), the files will have the names ```filename_1```, ```filename_2```, and so on.
```
axis_info_dict = get_axis_info(xcoordinatemin, xcoordinatemax, xpixelmax,
ycoordinatemin, ycoordinatemax, ypixelmax,
origin, max_points, units)
datayoink_to_excel(outputs, axis_info_dict, filename='datayoink_result')
```
| github_jupyter |
```
import pandas as pd
import datetime as dt
```
# testing it
## Review of Python's `datetime` Module
```
someday = dt.date(2010, 1, 20)
someday.year
someday.month
someday.day
str(someday)
str(dt.datetime(2010, 1, 10, 17, 13, 57))
sometime = dt.datetime(2010, 1, 10, 17, 13, 57)
sometime.year
sometime.month
sometime.day
sometime.hour
sometime.minute
sometime.second
```
## The `pandas Timestamp` Object
```
pd.Timestamp("2015-03-31")
pd.Timestamp("2015/03/31")
pd.Timestamp("2013, 11, 04")
pd.Timestamp("1/1/2015")
pd.Timestamp("19/12/2015")
pd.Timestamp("12/19/2015")
pd.Timestamp("4/3/2000")
pd.Timestamp("2021-03-08 08:35:15")
pd.Timestamp("2021-03-08 6:13:29 PM")
pd.Timestamp(dt.date(2015, 1, 1))
pd.Timestamp(dt.datetime(2000, 2, 3, 21, 35, 22))
```
## The `pandas DateTimeIndex` Object
```
dates = ["2016/01/02", "2016/04/12", "2009/09/07"]
pd.DatetimeIndex(dates)
dates = [dt.date(2016, 1, 10), dt.date(1994, 6, 13), dt.date(2003, 12, 29)]
dtIndex = pd.DatetimeIndex(dates)
values = [100, 200, 300]
pd.Series(data = values, index = dtIndex)
```
## The `pd.to_datetime()` Method
```
pd.to_datetime("2001-04-19")
pd.to_datetime(dt.date(2015, 1, 1))
pd.to_datetime(dt.datetime(2015, 1, 1, 14, 35, 20))
pd.to_datetime(["2015-01-03", "2014/02/08", "2016", "July 4th, 1996"])
times = pd.Series(["2015-01-03", "2014/02/08", "2016", "July 4th, 1996"])
times
pd.to_datetime(times)
dates = pd.Series(["July 4th, 1996", "10/04/1991", "Hello", "2015-02-31"])
dates
pd.to_datetime(dates, errors = "coerce")
pd.to_datetime([1349720105, 1349806505, 1349892905, 1349979305, 1350065705], unit = "s")
pd.Period("2016-01-08", freq = "10D")
dates = ["2016-01-01", "2016-02-01", "2016-03-01"]
pd.Series([1, 2, 3], index = pd.PeriodIndex(dates, freq = "2M"))
pd.Period("2016-01-08", freq = "W")
pd.Period("2016-01-08", freq = "W-SUN")
pd.Period("2016-01-08", freq = "W-WED")
pd.Period("2015-12-10", freq = "10D")
dates = ["2016-01-01", "2016-02-01", "2016-02-01"]
pd.PeriodIndex(dates, freq = "W-MON")
weeks = pd.PeriodIndex(dates, freq = "W-MON")
pd.Series([999, 500, 325], index = weeks, name = "Weekly Revenue")
```
## Create Range of Dates with the `pd.date_range()` Method, Part 1
```
times = pd.date_range(start = "2016-01-01", end = "2016-01-10", freq = "D")
type(times)
type(times[0])
pd.date_range(start = "2016-01-01", end = "2050-01-01", freq = "A")
```
## Create Range of Dates with the `pd.date_range()` Method, Part 2
```
pd.date_range(start = "2012-09-09", periods = 50, freq = "6H")
```
## Create Range of Dates with the `pd.date_range()` Method, Part 3
```
pd.date_range(end = "1999-12-31", periods = 100, freq = "7H")
```
## The `.dt` Accessor
```
bunch_of_dates = pd.date_range(start = "2000-01-01", end = "2010-12-31", freq = "24D")
s = pd.Series(bunch_of_dates)
s.head(3)
mask = s.dt.is_month_end
s[mask]
```
## Import Financial Data Set with `pandas_datareader` Library
## `Timedeltas` in a Dataset
| github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
# Tensorboard Integration with Run History
1. Run a Tensorflow job locally and view its TB output live.
2. The same, for a DSVM.
3. And once more, with an AmlCompute cluster.
4. Finally, we'll collect all of these historical runs together into a single Tensorboard graph.
## Prerequisites
* Understand the [architecture and terms](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture) introduced by Azure Machine Learning
* Go through the [00.configuration.ipynb](https://github.com/Azure/MachineLearningNotebooks/blob/master/00.configuration.ipynb) notebook to:
* install the AML SDK
* create a workspace and its configuration file (`config.json`)
```
# Check core SDK version number
import azureml.core
print("SDK version:", azureml.core.VERSION)
```
Install the Azure ML TensorBoard package.
```
!pip install azureml-contrib-tensorboard
```
## Diagnostics
Opt-in diagnostics for better experience, quality, and security of future releases.
```
from azureml.telemetry import set_diagnostics_collection
set_diagnostics_collection(send_diagnostics=True)
```
## Initialize Workspace
Initialize a workspace object from persisted configuration.
```
from azureml.core import Workspace
ws = Workspace.from_config()
print('Workspace name: ' + ws.name,
'Azure region: ' + ws.location,
'Subscription id: ' + ws.subscription_id,
'Resource group: ' + ws.resource_group, sep = '\n')
```
## Set experiment name and create project
Choose a name for your run history container in the workspace, and create a folder for the project.
```
from os import path, makedirs
experiment_name = 'tensorboard-demo'
# experiment folder
exp_dir = './sample_projects/' + experiment_name
if not path.exists(exp_dir):
makedirs(exp_dir)
# runs we started in this session, for the finale
runs = []
```
## Download Tensorflow Tensorboard demo code
Tensorflow's repository has an MNIST demo with extensive Tensorboard instrumentation. We'll use it here for our purposes.
Note that we don't need to make any code changes at all - the code works without modification from the Tensorflow repository.
```
import requests
import os
import tempfile
tf_code = requests.get("https://raw.githubusercontent.com/tensorflow/tensorflow/r1.8/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py")
with open(os.path.join(exp_dir, "mnist_with_summaries.py"), "w") as file:
file.write(tf_code.text)
```
## Configure and run locally
We'll start by running this locally. While it might not initially seem that useful to use this for a local run - why not just run TB against the files generated locally? - even in this case there is some value to using this feature. Your local run will be registered in the run history, and your Tensorboard logs will be uploaded to the artifact store associated with this run. Later, you'll be able to restore the logs from any run, regardless of where it happened.
Note that for this run, you will need to install Tensorflow on your local machine by yourself. Further, the Tensorboard module (that is, the one included with Tensorflow) must be accessible to this notebook's kernel, as the local machine is what runs Tensorboard.
```
from azureml.core.runconfig import RunConfiguration
# Create a run configuration.
run_config = RunConfiguration()
run_config.environment.python.user_managed_dependencies = True
# You can choose a specific Python environment by pointing to a Python path
#run_config.environment.python.interpreter_path = '/home/ninghai/miniconda3/envs/sdk2/bin/python'
from azureml.core import Experiment, Run
from azureml.core.script_run_config import ScriptRunConfig
import tensorflow as tf
logs_dir = os.path.join(os.curdir, "logs")
data_dir = os.path.abspath(os.path.join(os.curdir, "mnist_data"))
if not path.exists(data_dir):
makedirs(data_dir)
os.environ["TEST_TMPDIR"] = data_dir
# Writing logs to ./logs results in their being uploaded to Artifact Service,
# and thus, made accessible to our Tensorboard instance.
arguments_list = ["--log_dir", logs_dir]
# Create an experiment
exp = Experiment(ws, experiment_name)
# If you would like the run to go for longer, add --max_steps 5000 to the arguments list:
# arguments_list += ["--max_steps", "5000"]
script = ScriptRunConfig(exp_dir,
script="mnist_with_summaries.py",
run_config=run_config,
arguments=arguments_list)
run = exp.submit(script)
# You can also wait for the run to complete
# run.wait_for_completion(show_output=True)
runs.append(run)
```
## Start Tensorboard
Now, while the run is in progress, we just need to start Tensorboard with the run as its target, and it will begin streaming logs.
```
from azureml.contrib.tensorboard import Tensorboard
# The Tensorboard constructor takes an array of runs, so be sure and pass it in as a single-element array here
tb = Tensorboard([run])
# If successful, start() returns a string with the URI of the instance.
tb.start()
```
## Stop Tensorboard
When you're done, make sure to call the `stop()` method of the Tensorboard object, or it will stay running even after your job completes.
```
tb.stop()
```
## Now, with a DSVM
Tensorboard uploading works with all compute targets. Here we demonstrate it from a DSVM.
Note that the Tensorboard instance itself will be run by the notebook kernel. Again, this means this notebook's kernel must have access to the Tensorboard module.
If you are unfamiliar with DSVM configuration, check [04. Train in a remote VM](04.train-on-remote-vm.ipynb) for a more detailed breakdown.
**Note**: To streamline the compute that Azure Machine Learning creates, we are making updates to support creating only single to multi-node `AmlCompute`. The `DSVMCompute` class will be deprecated in a later release, but the DSVM can be created using the below single line command and then attached(like any VM) using the sample code below. Also note, that we only support Linux VMs for remote execution from AML and the commands below will spin a Linux VM only.
```shell
# create a DSVM in your resource group
# note you need to be at least a contributor to the resource group in order to execute this command successfully.
(myenv) $ az vm create --resource-group <resource_group_name> --name <some_vm_name> --image microsoft-dsvm:linux-data-science-vm-ubuntu:linuxdsvmubuntu:latest --admin-username <username> --admin-password <password> --generate-ssh-keys --authentication-type password
```
You can also use [this url](https://portal.azure.com/#create/microsoft-dsvm.linux-data-science-vm-ubuntulinuxdsvmubuntu) to create the VM using the Azure Portal.
```
from azureml.core.compute import RemoteCompute
from azureml.core.compute_target import ComputeTargetException
import os
username = os.getenv('AZUREML_DSVM_USERNAME', default='<my_username>')
address = os.getenv('AZUREML_DSVM_ADDRESS', default='<ip_address_or_fqdn>')
compute_target_name = 'cpudsvm'
# if you want to connect using SSH key instead of username/password you can provide parameters private_key_file and private_key_passphrase
try:
attached_dsvm_compute = RemoteCompute(workspace=ws, name=compute_target_name)
print('found existing:', attached_dsvm_compute.name)
except ComputeTargetException:
attached_dsvm_compute = RemoteCompute.attach(workspace=ws,
name=compute_target_name,
username=username,
address=address,
ssh_port=22,
private_key_file='./.ssh/id_rsa')
attached_dsvm_compute.wait_for_completion(show_output=True)
```
## Submit run using TensorFlow estimator
Instead of manually configuring the DSVM environment, we can use the TensorFlow estimator and everything is set up automatically.
```
from azureml.train.dnn import TensorFlow
script_params = {"--log_dir": "./logs"}
# If you want the run to go longer, set --max-steps to a higher number.
# script_params["--max_steps"] = "5000"
tf_estimator = TensorFlow(source_directory=exp_dir,
compute_target=attached_dsvm_compute,
entry_script='mnist_with_summaries.py',
script_params=script_params)
run = exp.submit(tf_estimator)
runs.append(run)
```
## Start Tensorboard with this run
Just like before.
```
# The Tensorboard constructor takes an array of runs, so be sure and pass it in as a single-element array here
tb = Tensorboard([run])
# If successful, start() returns a string with the URI of the instance.
tb.start()
```
## Stop Tensorboard
When you're done, make sure to call the `stop()` method of the Tensorboard object, or it will stay running even after your job completes.
```
tb.stop()
```
## Once more, with an AmlCompute cluster
Just to prove we can, let's create an AmlCompute CPU cluster, and run our demo there, as well.
```
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# choose a name for your cluster
cluster_name = "cpucluster"
try:
compute_target = ComputeTarget(workspace=ws, name=cluster_name)
print('Found existing compute target.')
except ComputeTargetException:
print('Creating a new compute target...')
compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',
max_nodes=4)
# create the cluster
compute_target = ComputeTarget.create(ws, cluster_name, compute_config)
compute_target.wait_for_completion(show_output=True, min_node_count=1, timeout_in_minutes=20)
# Use the 'status' property to get a detailed status for the current cluster.
print(compute_target.status.serialize())
```
## Submit run using TensorFlow estimator
Again, we can use the TensorFlow estimator and everything is set up automatically.
```
script_params = {"--log_dir": "./logs"}
# If you want the run to go longer, set --max-steps to a higher number.
# script_params["--max_steps"] = "5000"
tf_estimator = TensorFlow(source_directory=exp_dir,
compute_target=compute_target,
entry_script='mnist_with_summaries.py',
script_params=script_params)
run = exp.submit(tf_estimator)
runs.append(run)
```
## Start Tensorboard with this run
Once more...
```
# The Tensorboard constructor takes an array of runs, so be sure and pass it in as a single-element array here
tb = Tensorboard([run])
# If successful, start() returns a string with the URI of the instance.
tb.start()
```
## Stop Tensorboard
When you're done, make sure to call the `stop()` method of the Tensorboard object, or it will stay running even after your job completes.
```
tb.stop()
```
## Finale
If you've paid close attention, you'll have noticed that we've been saving the run objects in an array as we went along. We can start a Tensorboard instance that combines all of these run objects into a single process. This way, you can compare historical runs. You can even do this with live runs; if you made some of those previous runs longer via the `--max_steps` parameter, they might still be running, and you'll see them live in this instance as well.
```
# The Tensorboard constructor takes an array of runs...
# and it turns out that we have been building one of those all along.
tb = Tensorboard(runs)
# If successful, start() returns a string with the URI of the instance.
tb.start()
```
## Stop Tensorboard
As you might already know, make sure to call the `stop()` method of the Tensorboard object, or it will stay running (until you kill the kernel associated with this notebook, at least).
```
tb.stop()
```
| github_jupyter |
```
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split as split
from tensorflow.keras.layers import SimpleRNN, Input, Dense
from tensorflow.keras.models import Model
from deap import base, creator, tools, algorithms
from scipy.stats import bernoulli
from bitstring import BitArray
np.random.seed(998)
#read data from csv
data = pd.read_csv('../Dataset/train.csv')
#use column wp2
data = np.reshape(np.array(data['wp2']), (len(data['wp2']), 1))
data = data[0:1500]
def format_dataset(data, w_size):
#initialize as empty array
X, Y = np.empty((0, w_size)), np.empty(0)
#depending on the window size the data is separated in 2 arrays containing each of the sizes
for i in range(len(data)-w_size-1):
X = np.vstack([X,data[i:(i+w_size),0]])
Y = np.append(Y, data[i+w_size,0])
X = np.reshape(X,(len(X),w_size,1))
Y = np.reshape(Y,(len(Y), 1))
return X, Y
#use GA to identify the optimal window size for the array
def training_hyperparameters(ga_optimization):
#decode GA solution to integer window size and number of units
w_size_bit = BitArray(ga_optimization[0:6])
n_units_bit = BitArray(ga_optimization[6:])
w_size = w_size_bit.uint
n_units = n_units_bit.uint
print('\nWindow Size: ', w_size, '\nNumber of units: ',n_units)
#return fitness score of 100 if the size or the units are 0
if w_size == 0 or n_units == 0:
return 100
#segment train data on the window size splitting it into 90 train, 10 validation
X,Y = format_dataset(data, w_size)
X_train, X_validate, Y_train, Y_validate = split(X, Y, test_size= 0.10, random_state= 998)
#train RNNSimple model and predict validation set
input_features = Input(shape=(w_size,1))
x = SimpleRNN(n_units,input_shape=(w_size,1))(input_features)
output = Dense(1, activation='linear')(x)
rnnmodel = Model(inputs=input_features, outputs = output)
rnnmodel.compile(optimizer='adam', loss = 'mean_squared_error')
rnnmodel.fit(X_train, Y_train, epochs=5, batch_size=4, shuffle = True)
Y_predict = rnnmodel.predict(X_validate)
# calculate RMSE score as fitness score for GA
RMSE = np.sqrt(mean_squared_error(Y_validate, Y_predict))
print('Validation RMSE: ', RMSE, '\n')
return RMSE,
population_size = 4
generations = 5
gene = 10
creator.create('FitnessMax', base.Fitness, weights= (-1.0,))
creator.create('Individual', list, fitness = creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register('bernoulli', bernoulli.rvs, 0.5)
toolbox.register('chromosome', tools.initRepeat, creator.Individual, toolbox.bernoulli, n = gene)
toolbox.register('population', tools.initRepeat, list, toolbox.chromosome)
toolbox.register('mate', tools.cxTwoPoint)
toolbox.register('mutate', tools.mutFlipBit, indpb = 0.6)
toolbox.register('select', tools.selRandom)
toolbox.register('evaluate', training_hyperparameters)
population = toolbox.population(n = population_size)
algo = algorithms.eaSimple(population,toolbox,cxpb=0.4, mutpb=0.1, ngen=generations, verbose=False)
optimal_chromosome = tools.selBest(population, k = 1)
optimal_w_size = None
optimal_n_units = None
for op in optimal_chromosome:
w_size_bit = BitArray(op[0:6])
n_units_bit = BitArray(op[6:])
optimal_w_size = w_size_bit.uint
optimal_n_units = n_units_bit.uint
print('\nOptimal window size:', optimal_w_size, '\n Optimal number of units:', optimal_n_units)
```
| github_jupyter |
```
# Goal: to make a volcano plot of differentially-bound
# BRD4 peaks in stem-like and differentiated-like K562 cells
import anndata as ad
import copy
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pybedtools import BedTool
import scanpy.api as sc
import scipy.stats as stats
from statsmodels.stats import multitest
# Initial setup
sc.settings.verbosity = 3 # verbosity: errors (0), warnings (1), info (2), hints (3)
sc.set_figure_params(dpi = 150,
dpi_save = 300,
vector_friendly = True,
transparent = True,
format = "pdf")
sc.logging.print_versions()
out_dir = "../output_and_analysis/reanalysis/"
# Read files
peaks = BedTool(out_dir + "K562-HyPB_scCC_final_p9.bed")
stem_hops = BedTool(out_dir + "K562-HyPB_scCC_final_stem.ccf")
diff_hops = BedTool(out_dir + "K562-HyPB_scCC_final_diff.ccf")
# Calculate intersections
data = peaks.intersect(stem_hops, c = True).intersect(diff_hops, c = True).to_dataframe()
data.columns = ["chrom", "start", "end", "stem_hops", "diff_hops"]
data["total_hops"] = data["stem_hops"] + data["diff_hops"]
# Create a file of peaks where there are at least 20 hops between stem and diff
new_peaks = data[data["total_hops"] > 20][["chrom", "start", "end"]]
new_peaks.to_csv(out_dir + "K562-HyPB_scCC_final_p9_gt20.bed", sep='\t', index=False, header=None)
# Repeat analysis with new peaks, using 5% FDR and writing intermediate files
peaks_gt20 = BedTool(out_dir + "K562-HyPB_scCC_final_p9_gt20.bed")
stem_hops = BedTool(out_dir + "K562-HyPB_scCC_final_stem.ccf")
diff_hops = BedTool(out_dir + "K562-HyPB_scCC_final_diff.ccf")
# Calculate intersections
data_gt20 = peaks_gt20.intersect(stem_hops, c = True).intersect(diff_hops, c = True).to_dataframe()
data_gt20.columns = ["chrom", "start", "end", "stem_hops", "diff_hops"]
# Normalize observed insertions by library size after adding pseudocount of 1
data_gt20["norm_stem_hops"] = (data_gt20["stem_hops"] + 1) / ((len(stem_hops) + 1) / 10**6)
data_gt20["norm_diff_hops"] = (data_gt20["diff_hops"] + 1) / ((len(diff_hops) + 1) / 10**6)
# Calculate normalized log2FC
data_gt20["norm_log2FC"] = np.log2(data_gt20["norm_diff_hops"] / data_gt20["norm_stem_hops"])
# Summary statistics
np.mean(data_gt20["norm_log2FC"]), np.var(data_gt20["norm_log2FC"])
# Open intermediate files from peak calling
stem_gt20_intermediate = pd.read_csv(out_dir + "K562-HyPB_scCC_final_stem_a10_fdr_gt20_intermediate.csv")
diff_gt20_intermediate = pd.read_csv(out_dir + "K562-HyPB_scCC_final_diff_a10_fdr_gt20_intermediate.csv")
# Add the p-value and rejected columns from the intermediate files to data
data_gt20["stem pValue"] = stem_gt20_intermediate["pValue"]
data_gt20["diff pValue"] = diff_gt20_intermediate["pValue"]
data_gt20["rejected"] = stem_gt20_intermediate["rejected"] | diff_gt20_intermediate["rejected"]
# Find the minimum p-value between both comparisons
data_gt20["pValue"] = data_gt20[["stem pValue", "diff pValue"]].min(axis = 1)
null_gt20 = data_gt20[data_gt20["rejected"] == False]
rejected_gt20 = data_gt20[data_gt20["rejected"]]
stem_rejected_gt20 = rejected_gt20[rejected_gt20["norm_log2FC"] < 0]
diff_rejected_gt20 = rejected_gt20[rejected_gt20["norm_log2FC"] > 0]
plt.axvline(x = 0, color = 'k', linewidth = 1)
plt.plot(null_gt20["norm_log2FC"], -np.log10(null_gt20["pValue"]), 'o', color = "#BBBBBB", markersize = 3)
plt.plot(stem_rejected_gt20["norm_log2FC"], -np.log10(stem_rejected_gt20["pValue"]), 'o', color = "#C03539", markersize = 3)
plt.plot(diff_rejected_gt20["norm_log2FC"], -np.log10(diff_rejected_gt20["pValue"]), 'o', color = "#2D77B5", markersize = 3)
plt.xlabel("log2 FC in binding")
plt.ylabel("-log10 unadj. p-value")
plt.grid(b = True, which = "major", linestyle = '--')
plt.ylim(bottom = 0)
plt.savefig(out_dir + "K562-HyPB_scCC_final_volcano.pdf", transparent=True, bbox_inches="tight")
print(len(data_gt20[data_gt20["norm_log2FC"] < 0]), len(data_gt20[data_gt20["norm_log2FC"] > 0]))
stats.binom.sf(len(data_gt20[data_gt20["norm_log2FC"] < 0]), len(data_gt20[data_gt20["norm_log2FC"] < 0]) + len(data_gt20[data_gt20["norm_log2FC"] > 0]), 0.5)
# Get all candidate hits
data_gt20[data_gt20["rejected"]]
data_gt20[data_gt20["rejected"]].to_csv(out_dir + "K562-HyPB_scCC_final_a10_fdr_stem_diff.csv", sep=',', index=False, header=None)
# Visualize gene expression differences between stem and diff cells
out_stem = "../../GTAC_273N-scCC-InVitro-cDNA/output_and_analysis/reanalysis/K562-HyPB"
k_file = out_stem + ".h5ad"
k_data = sc.read(k_file)
# k_data.obs["state"]
stem_barcodes = [_.strip() for _ in open("../../GTAC_273N-scCC-InVitro-cDNA/output_and_analysis/reanalysis/K562-HyPB_stem_barcodes.csv")]
diff_barcodes = [_.strip() for _ in open("../../GTAC_273N-scCC-InVitro-cDNA/output_and_analysis/reanalysis/K562-HyPB_diff_barcodes.csv")]
stem_data = k_data[stem_barcodes]
stem_data.obs["Category"] = "Stem"
diff_data = k_data[diff_barcodes]
diff_data.obs["Category"] = "Diff"
categorical = ad.AnnData.concatenate(stem_data, diff_data, index_unique = None)
# Violin plot for a given gene
gene = "PVT1"
sc.pl.violin(categorical, gene, groupby = "state", palette = {"Stem-like": "#C03539", "Differentiated": "#2D77B5"}, alpha = 0.5)
stats.ks_2samp(stem_data[:, [gene]].X, diff_data[:, [gene]].X)
# Violin plot for a given gene
gene = "VMP1"
sc.pl.violin(categorical, gene, groupby = "state", palette = {"Stem-like": "#C03539", "Differentiated": "#2D77B5"}, alpha = 0.5)
stats.ks_2samp(stem_data[:, [gene]].X, diff_data[:, [gene]].X)
```
| github_jupyter |
# End-to-End Multiclass Image Classification Example
1. [Introduction](#Introduction)
2. [Prerequisites and Preprocessing](#Prequisites-and-Preprocessing)
1. [Permissions and environment variables](#Permissions-and-environment-variables)
2. [Prepare the data](#Prepare-the-data)
3. [Training the model](#Training-the-model)
1. [Training parameters](#Training-parameters)
2. [Start the training](#Start-the-training)
4. [Compile](#Compile)
5. [Inference](#Inference)
## Introduction
Welcome to our end-to-end example of distributed image classification algorithm. In this demo, we will use the Amazon sagemaker image classification algorithm to train on the [caltech-256 dataset](http://www.vision.caltech.edu/Image_Datasets/Caltech256/).
To get started, we need to set up the environment with a few prerequisite steps, for permissions, configurations, and so on.
## Prequisites and Preprocessing
### Permissions and environment variables
Here we set up the linkage and authentication to AWS services. There are three parts to this:
* The roles used to give learning and hosting access to your data. This will automatically be obtained from the role used to start the notebook
* The S3 bucket that you want to use for training and model data
* The Amazon sagemaker image classification docker image which need not be changed
```
%%time
import sagemaker
from sagemaker import get_execution_role
role = get_execution_role()
print(role)
sess = sagemaker.Session()
bucket=sess.default_bucket()
prefix = 'ic-fulltraining'
from sagemaker.amazon.amazon_estimator import get_image_uri
training_image = get_image_uri(sess.boto_region_name, 'image-classification', repo_version="latest")
print (training_image)
```
### Data preparation
Download the data and transfer to S3 for use in training. In this demo, we are using [Caltech-256](http://www.vision.caltech.edu/Image_Datasets/Caltech256/) dataset, which contains 30608 images of 256 objects. For the training and validation data, we follow the splitting scheme in this MXNet [example](https://github.com/apache/incubator-mxnet/blob/master/example/image-classification/data/caltech256.sh). In particular, it randomly selects 60 images per class for training, and uses the remaining data for validation. The algorithm takes `RecordIO` file as input. The user can also provide the image files as input, which will be converted into `RecordIO` format using MXNet's [im2rec](https://mxnet.incubator.apache.org/how_to/recordio.html?highlight=im2rec) tool. It takes around 50 seconds to converted the entire Caltech-256 dataset (~1.2GB) on a p2.xlarge instance. However, for this demo, we will use record io format.
```
import os
import urllib.request
import boto3
def download(url):
filename = url.split("/")[-1]
if not os.path.exists(filename):
urllib.request.urlretrieve(url, filename)
def upload_to_s3(channel, file):
s3 = boto3.resource('s3')
data = open(file, "rb")
key = channel + '/' + file
s3.Bucket(bucket).put_object(Key=key, Body=data)
# caltech-256
download('http://data.mxnet.io/data/caltech-256/caltech-256-60-train.rec')
download('http://data.mxnet.io/data/caltech-256/caltech-256-60-val.rec')
# Four channels: train, validation, train_lst, and validation_lst
s3train = 's3://{}/{}/train/'.format(bucket, prefix)
s3validation = 's3://{}/{}/validation/'.format(bucket, prefix)
# upload the lst files to train and validation channels
!aws s3 cp caltech-256-60-train.rec $s3train --quiet
!aws s3 cp caltech-256-60-val.rec $s3validation --quiet
```
Once we have the data available in the correct format for training, the next step is to actually train the model using the data. After setting training parameters, we kick off training, and poll for status until training is completed.
## Training the model
Now that we are done with all the setup that is needed, we are ready to train our object detector. To begin, let us create a ``sageMaker.estimator.Estimator`` object. This estimator will launch the training job.
### Training parameters
There are two kinds of parameters that need to be set for training. The first one are the parameters for the training job. These include:
* **Training instance count**: This is the number of instances on which to run the training. When the number of instances is greater than one, then the image classification algorithm will run in distributed settings.
* **Training instance type**: This indicates the type of machine on which to run the training. Typically, we use GPU instances for these training
* **Output path**: This the s3 folder in which the training output is stored
```
s3_output_location = 's3://{}/{}/output'.format(bucket, prefix)
ic = sagemaker.estimator.Estimator(training_image,
role,
train_instance_count=1,
train_instance_type='ml.p2.xlarge',
train_volume_size = 50,
train_max_run = 360000,
input_mode= 'File',
output_path=s3_output_location,
sagemaker_session=sess)
```
Apart from the above set of parameters, there are hyperparameters that are specific to the algorithm. These are:
* **num_layers**: The number of layers (depth) for the network. We use 18 in this samples but other values such as 50, 152 can be used.
* **image_shape**: The input image dimensions,'num_channels, height, width', for the network. It should be no larger than the actual image size. The number of channels should be same as the actual image.
* **num_classes**: This is the number of output classes for the new dataset. Imagenet was trained with 1000 output classes but the number of output classes can be changed for fine-tuning. For caltech, we use 257 because it has 256 object categories + 1 clutter class.
* **num_training_samples**: This is the total number of training samples. It is set to 15240 for caltech dataset with the current split.
* **mini_batch_size**: The number of training samples used for each mini batch. In distributed training, the number of training samples used per batch will be N * mini_batch_size where N is the number of hosts on which training is run.
* **epochs**: Number of training epochs.
* **learning_rate**: Learning rate for training.
* **top_k**: Report the top-k accuracy during training.
* **precision_dtype**: Training datatype precision (default: float32). If set to 'float16', the training will be done in mixed_precision mode and will be faster than float32 mode
```
ic.set_hyperparameters(num_layers=18,
image_shape = "3,224,224",
num_classes=257,
num_training_samples=15420,
mini_batch_size=128,
epochs=5,
learning_rate=0.01,
top_k=2,
precision_dtype='float32')
```
## Input data specification
Set the data type and channels used for training
```
train_data = sagemaker.session.s3_input(s3train, distribution='FullyReplicated',
content_type='application/x-recordio', s3_data_type='S3Prefix')
validation_data = sagemaker.session.s3_input(s3validation, distribution='FullyReplicated',
content_type='application/x-recordio', s3_data_type='S3Prefix')
data_channels = {'train': train_data, 'validation': validation_data}
```
## Start the training
Start training by calling the fit method in the estimator
```
ic.fit(inputs=data_channels, logs=True)
```
# Compile
***
[Amazon SageMaker Neo](https://aws.amazon.com/sagemaker/neo/) optimizes models to run up to twice as fast, with no loss in accuracy. When calling `compile_model()` function, we specify the target instance family (m4) as well as the S3 bucket to which the compiled model would be stored.
```
optimized_ic = ic
if ic.create_model().check_neo_region(boto3.Session().region_name) is False:
print('Neo is not currently supported in', boto3.Session().region_name)
else:
output_path = '/'.join(ic.output_path.split('/')[:-1])
optimized_ic = ic.compile_model(target_instance_family='ml_m4',
input_shape={'data': [1, 3, 224, 224]}, # Batch size 1, 3 channels, 224x224 Images.
output_path=output_path,
framework='mxnet', framework_version='1.2.1')
optimized_ic.image = get_image_uri(sess.boto_region_name, 'image-classification-neo', repo_version="latest")
optimized_ic.name = 'deployed-image-classification'
```
# Inference
***
A trained model does nothing on its own. We now want to use the model to perform inference. For this example, that means predicting the topic mixture representing a given document. You can deploy the created model by using the deploy method in the estimator
```
ic_classifier = optimized_ic.deploy(initial_instance_count = 1,
instance_type = 'ml.m4.xlarge')
```
### Download test image
```
!wget -O /tmp/test.jpg http://www.vision.caltech.edu/Image_Datasets/Caltech256/images/008.bathtub/008_0007.jpg
file_name = '/tmp/test.jpg'
# test image
from IPython.display import Image
Image(file_name)
```
### Evaluation
Evaluate the image through the network for inteference. The network outputs class probabilities and typically, one selects the class with the maximum probability as the final class output.
**Note:** The output class detected by the network may not be accurate in this example. To limit the time taken and cost of training, we have trained the model only for 5 epochs. If the network is trained for more epochs (say 20), then the output class will be more accurate.
```
import json
import numpy as np
with open(file_name, 'rb') as f:
payload = f.read()
payload = bytearray(payload)
ic_classifier.content_type = 'application/x-image'
result = json.loads(ic_classifier.predict(payload))
# the result will output the probabilities for all classes
# find the class with maximum probability and print the class index
index = np.argmax(result)
object_categories = ['ak47', 'american-flag', 'backpack', 'baseball-bat', 'baseball-glove', 'basketball-hoop', 'bat', 'bathtub', 'bear', 'beer-mug', 'billiards', 'binoculars', 'birdbath', 'blimp', 'bonsai-101', 'boom-box', 'bowling-ball', 'bowling-pin', 'boxing-glove', 'brain-101', 'breadmaker', 'buddha-101', 'bulldozer', 'butterfly', 'cactus', 'cake', 'calculator', 'camel', 'cannon', 'canoe', 'car-tire', 'cartman', 'cd', 'centipede', 'cereal-box', 'chandelier-101', 'chess-board', 'chimp', 'chopsticks', 'cockroach', 'coffee-mug', 'coffin', 'coin', 'comet', 'computer-keyboard', 'computer-monitor', 'computer-mouse', 'conch', 'cormorant', 'covered-wagon', 'cowboy-hat', 'crab-101', 'desk-globe', 'diamond-ring', 'dice', 'dog', 'dolphin-101', 'doorknob', 'drinking-straw', 'duck', 'dumb-bell', 'eiffel-tower', 'electric-guitar-101', 'elephant-101', 'elk', 'ewer-101', 'eyeglasses', 'fern', 'fighter-jet', 'fire-extinguisher', 'fire-hydrant', 'fire-truck', 'fireworks', 'flashlight', 'floppy-disk', 'football-helmet', 'french-horn', 'fried-egg', 'frisbee', 'frog', 'frying-pan', 'galaxy', 'gas-pump', 'giraffe', 'goat', 'golden-gate-bridge', 'goldfish', 'golf-ball', 'goose', 'gorilla', 'grand-piano-101', 'grapes', 'grasshopper', 'guitar-pick', 'hamburger', 'hammock', 'harmonica', 'harp', 'harpsichord', 'hawksbill-101', 'head-phones', 'helicopter-101', 'hibiscus', 'homer-simpson', 'horse', 'horseshoe-crab', 'hot-air-balloon', 'hot-dog', 'hot-tub', 'hourglass', 'house-fly', 'human-skeleton', 'hummingbird', 'ibis-101', 'ice-cream-cone', 'iguana', 'ipod', 'iris', 'jesus-christ', 'joy-stick', 'kangaroo-101', 'kayak', 'ketch-101', 'killer-whale', 'knife', 'ladder', 'laptop-101', 'lathe', 'leopards-101', 'license-plate', 'lightbulb', 'light-house', 'lightning', 'llama-101', 'mailbox', 'mandolin', 'mars', 'mattress', 'megaphone', 'menorah-101', 'microscope', 'microwave', 'minaret', 'minotaur', 'motorbikes-101', 'mountain-bike', 'mushroom', 'mussels', 'necktie', 'octopus', 'ostrich', 'owl', 'palm-pilot', 'palm-tree', 'paperclip', 'paper-shredder', 'pci-card', 'penguin', 'people', 'pez-dispenser', 'photocopier', 'picnic-table', 'playing-card', 'porcupine', 'pram', 'praying-mantis', 'pyramid', 'raccoon', 'radio-telescope', 'rainbow', 'refrigerator', 'revolver-101', 'rifle', 'rotary-phone', 'roulette-wheel', 'saddle', 'saturn', 'school-bus', 'scorpion-101', 'screwdriver', 'segway', 'self-propelled-lawn-mower', 'sextant', 'sheet-music', 'skateboard', 'skunk', 'skyscraper', 'smokestack', 'snail', 'snake', 'sneaker', 'snowmobile', 'soccer-ball', 'socks', 'soda-can', 'spaghetti', 'speed-boat', 'spider', 'spoon', 'stained-glass', 'starfish-101', 'steering-wheel', 'stirrups', 'sunflower-101', 'superman', 'sushi', 'swan', 'swiss-army-knife', 'sword', 'syringe', 'tambourine', 'teapot', 'teddy-bear', 'teepee', 'telephone-box', 'tennis-ball', 'tennis-court', 'tennis-racket', 'theodolite', 'toaster', 'tomato', 'tombstone', 'top-hat', 'touring-bike', 'tower-pisa', 'traffic-light', 'treadmill', 'triceratops', 'tricycle', 'trilobite-101', 'tripod', 't-shirt', 'tuning-fork', 'tweezer', 'umbrella-101', 'unicorn', 'vcr', 'video-projector', 'washing-machine', 'watch-101', 'waterfall', 'watermelon', 'welding-mask', 'wheelbarrow', 'windmill', 'wine-bottle', 'xylophone', 'yarmulke', 'yo-yo', 'zebra', 'airplanes-101', 'car-side-101', 'faces-easy-101', 'greyhound', 'tennis-shoes', 'toad', 'clutter']
print("Result: label - " + object_categories[index] + ", probability - " + str(result[index]))
```
### Clean up
When we're done with the endpoint, we can just delete it and the backing instances will be released. Uncomment and run the following cell to delete the endpoint and model
```
ic_classifier.delete_endpoint()
```
| github_jupyter |
```
import xarray as xr
import netCDF4 as nc
import plotly
import chart_studio.plotly as py
import plotly.offline as py_off
import numpy as np
from scipy.io import netcdf
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
pio.renderers.default = 'iframe'
import cartopy.feature as cf
import dash
import dash_core_components
import matplotlib
from __future__ import print_function
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import matplotlib.animation as anim
import cartopy
from IPython.display import HTML
from PIL import Image
def get_plotly_data(file,field,level=None):
ds = xr.open_dataset(xr.backends.NetCDF4DataStore(nc.Dataset(file)))
df = ds[['lon','lat',f'{field}']].to_dataframe()
if level is not None:
levels = df.index.get_level_values('pfull')
level = levels[np.argmin(np.abs(levels-level))]
df = df[df.index.get_level_values('pfull') == level]
step = 1.0
to_bin = lambda x: np.floor(x / step) * step
df["lat"] = df.index.get_level_values('lat').map(to_bin)
df["lon"] = df.index.get_level_values('lon').map(to_bin)
df.reset_index(drop=True, inplace=True)
groups = df.groupby(["lat", "lon"])
df_flat = df.drop_duplicates(subset=['lat', 'lon'])
df = df_flat[np.isfinite(df_flat[f'{field}'])]
df = df[(df.lat <= 90.0) &
(df.lat >= -90.0) &
(df.lon <= 360.0) &
(df.lon >= 0)]
df['lon'] = df['lon'].apply(lambda x: x if x <= 180.0 else x-360.0)
return df,ds
def get_fig_data(file,field,level=None):
df,ds = get_plotly_data(file,field,level=level)
x_coords = []
y_coords = []
traces = []
for coord_seq in cf.COASTLINE.geometries():
x_coords.extend([k[0] for k in coord_seq.coords] + [np.nan])
y_coords.extend([k[1] for k in coord_seq.coords] + [np.nan])
## in your app callback for dash
trace = go.Scatter(x = x_coords,
y = y_coords,
mode = 'lines',
line=go.Line(color="black"))
traces.append(trace)
contours = go.Contour(z=df[f'{field}'],
x=df['lon'],
y=df['lat'],
colorscale="RdBu",
zauto=False, # custom contour levels
zmin=min(df[f'{field}']), # first contour level
zmax=max(df[f'{field}']) # last contour level => colorscale is centered about 0
)
data = go.Data([contours]+traces)
title = u"{0} field ({1}) <br>".format(ds[f'{field}'].long_name,ds[f'{field}'].units)
anno_text = "Data from ISCA simulation"
#of \
#<a href='http://www.esrl.noaa.gov/psd/data/composites/day/'>\
#NOAA Earth System Research Laboratory</a>"
axis_style = dict(zeroline=False,
showline=False,
showgrid=False,
ticks='',
showticklabels=False)
layout = go.Layout(title=title,
showlegend=False,
hovermode="closest", # highlight closest point on hover
xaxis=go.XAxis(axis_style,
range=[min(df['lon']),
max(df['lon'])]), # restrict y-axis to range of lon
yaxis=go.YAxis(axis_style,
range=[min(df['lat']),
max(df['lat'])]),
annotations=go.Annotations([go.Annotation(text=anno_text,
xref='paper',
yref='paper',
x=0,y=1,
yanchor='bottom',
showarrow=False)]),
autosize=False,
width=1000,
height=600)
#layout = Layout(
#paper_bgcolor='rgba(0,0,0,0)',
#plot_bgcolor='rgba(0,0,0,0)'
#)
return data,layout
def plot_field(file,field,level=None):
data,layout = get_fig_data(file,field,level=level)
fig = go.Figure(data=data,layout=layout)
fig.show()
def get_animation(files,field,level=None):
frames = []
axis_style = dict(zeroline=False,
showline=False,
showgrid=False,
ticks='',
showticklabels=False)
layout = go.Layout(title='',
showlegend=False,
hovermode="closest", # highlight closest point on hover
xaxis=go.XAxis(axis_style,
range=[min(get_data(files[0],field,level)[0]['lon']),
max(get_data(files[0],field,level)[0]['lon'])]), # restrict y-axis to range of lon
yaxis=go.YAxis(axis_style,
range=[min(get_data(files[0],field,level)[0]['lat']),
max(get_data(files[0],field,level)[0]['lat'])]),
annotations=go.Annotations([go.Annotation(text='',
xref='paper',
yref='paper',
x=0,y=1,
yanchor='bottom',
showarrow=False)]),
autosize=False,
width=1000,
height=600,
updatemenus=[dict(
type="buttons",
buttons=[dict(label="Play",
method="animate",
args = [None, {"frame": {"duration": 1000,
"redraw": True},
"fromcurrent": True,
"transition": {"duration": 0,"easing": "quadratic-in-out"}}])])])
for f in files:
frames.append(go.Frame(data=get_fig_data(f,field,level)[0]))
fig = go.Figure(
data=get_fig_data(files[0],field,level)[0],
layout=layout,
frames=frames
)
fig.show()
```
| github_jupyter |
1 - Como se pode acessar o atributo da seguinte classe?
```python
class MyClass:
def __init__(self):
self.my_attr = "Acessado"
```
- a. MyClass()["my_attr"]
- b. MyClass()[my_attr]
- *c. MyClass().my_attr
- d. MyClass()(my_attr)
2 - O que o método '__getitem__' implementado na seguinte classe faz?
```python
class MyClass:
def __init__(self):
self.my_attr = "Acessado"
def __getitem__(self,name):
return getattr(self,name)
```
- *a. Permite acesso aos atributos por string com o operador [] (exemplo: class_istance["attr"]).
- b. Permite mudar os nomes dos atributos por string com o operador [] (exemplo: class_istance["old_attr", "new_attr"]).
- c. Permite acesso aos atributos por string com o operador {} (exemplo: class_istance{"attr"}).
- d. Trata o caso de acesso de atributos inexistentes.
3 - A respeito das diferenças entre atributos de classes e atributos de instâncias, quais alternativas estão corretas?
- V. Um dos casos de uso de atributos de classe é o armazenamento de constantes.
- V. Normalmente, não é aconselhado atributos de classes mutáveis.
- F. Um atributo da instância pode ser acessado pela classe.
- V. Uma instância pode acessar seus atributos e os atributos de classe.
4 - Preencha as lacunas para inicializar corretamente
```python
class Pessoa:
def __init__(self, name, age):
self.name = name
self.age = age
class CientistaDados(Pessoa):
def __init__(self, name, age, specialization):
{{GAP}}.__init__({{GAP}}, {{GAP}})
self.specialization = specialization
```
alternativas: [name, super, age];
aceitas:[
[super],
[name],
[age]
]
5 - Imagine que seu chefe pediu para você fazer a modelagem de dados de uma automobiliária. Você, como programador experiente decide começar a modelagem fazendo uma classe Veículos, que representa motos, carros e caminhões. Quais são os atributos que melhor representam essa classe?
- a. quilometragem, tamaho_guidao, largura
- b. capacidade_armazenamento, capacidade_pessoas, tem_arcondicionado
- c. tamaho_guidao, quantidade_rodas, altura
- *d. quantidade_rodas, potencia, capacidade_pessoas.
6 - Sobre atributos privados em python, quais alternativas estão corretas?
- V. Não é possível fazer atributos privados em python.
- F. Pode-se importar private da biblioteca padrão functools para tornar atributos privados.
- F. Todos atributos são privados por padrão e é necessário criar getters e setters para manipula-los.
- V. Indica-se que um atributo é privado com um ou dois underscore ('_') antes do nome da variável.
7 - Para que utilizamos a palavra reservada self no contexto de classes em python?
- a. A palavra self é uma convenção entre programadores, não sendo necessária quando trabalha-se com classes.
- *b. Essa palavra é utilizada para indicar uma instância da classe.
- c. Essa palavra é utilizada para indicar a classe a qual a instância pertence.
- d. A palavra self indica que a classe pode criar mais de uma instância.
8 - Você estava muito cansado do trablho e resolveu tirar férias em uma praia. Entretanto, você é apaixonado por programação e animais, e rapidamente a seguinte pergunta passou pela sua cabeça. Será que eu consigo criar uma classe para modelar os Animais? Qual alternativa representa os atributos mais interessantes para sua classe?
- a. andar, comer, voar.
- b. altura, voar, sexo.
- c. cor, nome, sexo.
- *d. reino, familia, especie.
9 - Qual a diferença entre o atributo __name e o atributo _age no seguinte código?
```python
class Pessoa:
def __init__(self, name, age):
self._age = age
self.__name = name
```
- *a. Um único underscore indica ao programador que a variável é privada. Entretanto quando utiliza-se dois underscore o nome do atributo muda, isto é, dessa forma não consiguimos acessar o atributo utilizando somente o nome, como exemplo Pessoa(name, age).__name), dessa forma aumentando o nível de segurança da variável.
- b. O atributo _age é privado e __name não é privado, ou seja, pode ser acessado.
- c. Não existe diferença para o interpretador do python, isto é somente uma convenção entre os programadores python, onde um underscore indica que a variável pode ser alterada em runtime, enquanto que dois underscore indicam que a variável pode ser alterada durante o runtime do programa.
- d. O atributo __name é privado e _age não é privado, ou seja, pode ser acessado.
10 - Qual é o objetivo do atributo question no seguinte código?
```python
class Bus:
question = set()
def __init__(self, passengers):
self.passengers = passengers
for passenger in passengers:
Bus.question.add(passenger)
```
- *a. O objetivo desse atributo é armazenar todos os passageiros que já andaram em pelo menos um ônibus.
- b. O objetivo desse atributo é manter uma cópia dos passageiros de um ônibus especifico.
- c. O objetivo desse atributo é gravar os passageiros em uma estrutura de dados diferente para rápido acesso.
- d. Este código não roda, pois o atributo está errado, falta a palavra self precedendo o nome do atributo, assim como passengers.
### **Questão maligna**
```
class Bus:
def __init__(self, passengers = []):
self.passengers = passengers.copy()
def add_passenger(self, passenger):
self.passengers.extend(passenger)
def __repr__(self):
return ", ".join(map(str,self.passengers))
bus1_lst = ["Joao", "Ferreira", "Amanda"]
bus2_lst = ["Pedro", "Fernanda", "Lucas"]
bus3_lst = ["Leticia", "Wagner", "Bruno"]
bus1 = Bus(bus1_lst)
print(bus1)
bus1.passengers.pop()
print(bus1)
bus2 = Bus()
bus2.add_passenger(bus2_lst)
bus2
print(bus2)
bus2.passengers.pop()
print(bus2)
bus3 = Bus()
bus3
bus3.add_passenger(bus3_lst)
bus3
bus2
```
| github_jupyter |
```
!pip install kaggle
!pip install pytorch_lightning
!pip install transformers
!pip install python-box
!pip install wandb
import numpy as np
import pandas as pd
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torch.utils.data import random_split
import pytorch_lightning as pl
from pytorch_lightning.utilities.seed import seed_everything
from pytorch_lightning.loggers import WandbLogger
from tqdm import tqdm
import shutil
import gc
import scipy
import transformers
from transformers import AutoTokenizer
from sklearn.model_selection import StratifiedKFold, KFold, GroupKFold
# import sys
# sys.path.append("../input/iterstat/iterative-stratification-master")
# sys.path.append("../input/python-box/Box-master")
# from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
# import pulp
from tqdm import tqdm
tqdm.pandas()
import matplotlib.pyplot as plt
import random as rn
import os
import logging
from box import Box
from sklearn.metrics import roc_auc_score, accuracy_score
import wandb
from wandb.keras import WandbCallback
try:
from kaggle_secrets import UserSecretsClient
except:
pass
import sklearn
sklearn.__version__
train_mode = True
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
# Then move kaggle.json into the folder where the API expects to find it.
!mkdir -p ~/.kaggle/ && mv kaggle.json ~/.kaggle/ && chmod 600 ~/.kaggle/kaggle.json
!kaggle competitions download -c jigsaw-toxic-severity-rating
config = {
"seed": 42,
"epoch": 3,
"max_length": 128,
"project": 'jigsaw-toxic',
"entity": 's-ohashi',
"exp_name": "028_exp",
"batch_size": 64,
"bert_model": transformers.RobertaModel.from_pretrained(
"roberta-base",
# attention_probs_dropout_prob=0.,
# hidden_dropout_prob=0.,
),
"bert_tokenizer": transformers.RobertaTokenizer.from_pretrained(
"roberta-base",
do_lower_case=True
),
"fast_dev_run": False,
"criterion": torch.nn.BCEWithLogitsLoss(),
"optimizer": {
"name": "torch.optim.AdamW",
"params": {
"lr": 1e-5,
},
},
"adj_denom": 0.,
"scheduler": {
"name": "torch.optim.lr_scheduler.CosineAnnealingWarmRestarts",
"params": {
"T_0": 20,
"eta_min": 0,
},
},
}
config = Box(config)
seed_everything(config.seed)
class jigsawDataset(Dataset):
def __init__(self, merged_dataset, cfg, is_train=True ):
self.merged_dataset = merged_dataset
self.max_length = cfg.max_length
self.tokenizer = cfg.bert_tokenizer
self.is_train = is_train
def __len__(self):
return len(self.merged_dataset)
def __getitem__(self, idx):
merged_dataset = self.merged_dataset.iloc[idx,:]
more_toxic = merged_dataset.more_toxic
less_toxic = merged_dataset.less_toxic
tokenized_more_toxic = self.tokenizer(
more_toxic,
add_special_tokens=True,
truncation=True,
padding='max_length',
max_length=self.max_length,
return_attention_mask=True,
return_token_type_ids=True,
)
tokenized_less_toxic = self.tokenizer(
less_toxic,
add_special_tokens=True,
truncation=True,
padding='max_length',
max_length=self.max_length,
return_attention_mask=True,
return_token_type_ids=True,
)
ids_more_toxic = tokenized_more_toxic['input_ids']
mask_more_toxic = tokenized_more_toxic['attention_mask']
token_type_ids_more_toxic = tokenized_more_toxic['token_type_ids']
ids_less_toxic = tokenized_less_toxic['input_ids']
mask_less_toxic = tokenized_less_toxic['attention_mask']
token_type_ids_less_toxic = tokenized_less_toxic['token_type_ids']
if self.is_train:
return [
# torch.tensor([merged_dataset.worker.astype("long")], dtype=torch.long),
torch.tensor(ids_more_toxic, dtype=torch.long),
torch.tensor(mask_more_toxic, dtype=torch.long),
torch.tensor(token_type_ids_more_toxic, dtype=torch.long),
torch.tensor(ids_less_toxic, dtype=torch.long),
torch.tensor(mask_less_toxic, dtype=torch.long),
torch.tensor(token_type_ids_less_toxic, dtype=torch.long),
torch.tensor([merged_dataset.target.astype("float")], dtype=torch.float),
]
else:
return [
# torch.tensor([merged_dataset.worker.astype("long")], dtype=torch.long),
torch.tensor(ids_more_toxic, dtype=torch.long),
torch.tensor(mask_more_toxic, dtype=torch.long),
torch.tensor(token_type_ids_more_toxic, dtype=torch.long),
torch.tensor(ids_less_toxic, dtype=torch.long),
torch.tensor(mask_less_toxic, dtype=torch.long),
torch.tensor(token_type_ids_less_toxic, dtype=torch.long),
# torch.tensor(merged_dataset.target.astype("int").to_numpy(), dtype=torch.int),
]
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class JigsawSeverityModel(pl.LightningModule):
def __init__(self,cfg):
super().__init__()
self.bert_model = cfg.bert_model
self.regressor = nn.Sequential(
nn.LayerNorm(768),
nn.Linear(768, 1),
)
self.cfg = cfg
self.criterion = cfg.criterion
# self.save_hyperparameters()
def forward(self, x):
ids_more_toxic, mask_more_toxic, token_type_ids_more_toxic, ids_less_toxic, mask_less_toxic, token_type_ids_less_toxic, target = x
more_toxic_embed = self.bert_model(ids_more_toxic, attention_mask=mask_more_toxic, token_type_ids=token_type_ids_more_toxic)
less_toxic_embed = self.bert_model(ids_less_toxic, attention_mask=mask_less_toxic, token_type_ids=token_type_ids_less_toxic)
more_toxic_embed = torch.mean(more_toxic_embed.last_hidden_state,axis=1)
less_toxic_embed = torch.mean(less_toxic_embed.last_hidden_state,axis=1)
more_toxic_score = self.regressor(more_toxic_embed)
less_toxic_score = self.regressor(less_toxic_embed)
out = more_toxic_score - less_toxic_score
return out
def configure_optimizers(self):
optimizer = eval(self.cfg.optimizer.name)(
self.parameters(), **self.cfg.optimizer.params
)
self.scheduler = eval(self.cfg.scheduler.name)(
optimizer, **self.cfg.scheduler.params
)
scheduler = {"scheduler": self.scheduler, "interval": "step",}
return [optimizer], [scheduler]
def training_step(self, train_batch, batch_idx):
ids_more_toxic, mask_more_toxic, token_type_ids_more_toxic, ids_less_toxic, mask_less_toxic, token_type_ids_less_toxic, target = train_batch
out = self.forward( train_batch )
criterion = self.criterion
loss = criterion(out, target )
self.log('train_loss', loss)
return {"loss":loss, "targets":target, "pred":out}
def training_epoch_end(self, training_step_outputs):
loss_list = []
pred_list = []
target_list = []
for out in training_step_outputs:
loss_list.extend([out["loss"].cpu().detach().tolist()])
pred_list.extend(out["pred"].cpu().detach().tolist())
target_list.extend(out["targets"].cpu().detach().tolist())
meanloss = sum(loss_list)/len(loss_list)
try:
acc = accuracy_score( np.ones_like(np.array(target_list)), (sigmoid(np.array(pred_list))>0.5)*1 )
except:
acc = 0.
logs = {f"train_loss_end": meanloss,
f"train_acc_end": acc,}
self.log_dict(
logs,
on_step=False,
on_epoch=True,
prog_bar=True,
logger=True
)
def validation_step(self, val_batch, batch_idx):
ids_more_toxic, mask_more_toxic, token_type_ids_more_toxic, ids_less_toxic, mask_less_toxic, token_type_ids_less_toxic, target = val_batch
out = self.forward( val_batch )
criterion = self.criterion
loss = criterion(out, target)
self.log('val_loss', loss, prog_bar=True, on_epoch=True)
return {"loss":loss, "targets":target, "pred":out}
def validation_epoch_end(self, validation_step_outputs):
loss_list = []
pred_list = []
target_list = []
for out in validation_step_outputs:
loss_list.extend([out["loss"].cpu().detach().tolist()])
pred_list.extend(out["pred"].cpu().detach().tolist())
target_list.extend(out["targets"].cpu().detach().tolist())
meanloss = sum(loss_list)/len(loss_list)
try:
acc = accuracy_score( np.ones_like(np.array(target_list)), (sigmoid(np.array(pred_list))>0.5)*1)
except:
acc = 0.
logs = {f"valid_loss_end":meanloss,
f"valid_acc_end":acc,}
self.log_dict(
logs,
on_step=False,
on_epoch=True,
prog_bar=True,
logger=True
)
# def predict_step(self, batch, batch_idx, dataloader_idx=0):
# return self.forward(batch)
!kaggle datasets download -d shunsukeohashi/jigsaw-less-more
try:
df_train = pd.read_csv("/content/jigsaw-less-more.zip")
df_train["target"]=1
except:
df_train = pd.read_csv("../input/jigsaw-less-more/classification_less_more.csv")
df_train["target"]=1
try:
df_val = pd.read_csv("/content/validation_data.csv.zip")
df_val["target"]=1
except:
df_val = pd.read_csv("../input/jigsaw-toxic-severity-rating/validation_data.csv")
df_val["target"]=1
def preprocess( texts ):
new_texts = texts
new_texts = new_texts.replace( ":", " " )
return new_texts
df_train.less_toxic=df_train.less_toxic.apply(preprocess)
df_train.more_toxic=df_train.more_toxic.apply(preprocess)
df_val.less_toxic=df_val.less_toxic.apply(preprocess)
df_val.more_toxic=df_val.more_toxic.apply(preprocess)
if train_mode:
try:
user_secrets = UserSecretsClient()
# I have saved my API token with "wandb_api" as Label.
# If you use some other Label make sure to change the same below.
wandb_api = user_secrets.get_secret("wandb_api")
wandb.login(key=wandb_api)
except:
wandb.login()
try:
if train_mode == False:
shutil.copyfile('../input/jigsawtoxicv027/model.ckpt', './model.ckpt')
except:
pass
seed_everything(config.seed)
wandb_logger = WandbLogger(
project=config.project,
entity=config.entity,
name = config.exp_name,
)
if train_mode:
try:
os.remove('model.ckpt')
except:
pass
seed_everything(config.seed)
train_dataset = jigsawDataset(df_train, config)
val_dataset = jigsawDataset(df_val, config)
train_loader = DataLoader(train_dataset, batch_size=config.batch_size, shuffle=True, num_workers=4)
val_loader = DataLoader(val_dataset, batch_size=config.batch_size, shuffle=False, num_workers=2)
model = JigsawSeverityModel(config)
es_callback = pl.callbacks.EarlyStopping(monitor="valid_loss_end", patience=1)
cp_callback = pl.callbacks.ModelCheckpoint(monitor="valid_loss_end",
dirpath="./",
filename="model",
save_top_k=1,
mode="min",
save_last=False,
save_weights_only=True)
config.scheduler.params.T_0 = config.epoch * len(train_loader)
if train_mode:
trainer = pl.Trainer(
gpus=1,
precision=16,
max_epochs=config.epoch,
callbacks=[
es_callback,
cp_callback
],
fast_dev_run=config.fast_dev_run,
logger=wandb_logger,
# accumulate_grad_batches=8,
)
trainer.fit(model, train_loader, val_loader)
try:
model = model.load_from_checkpoint(
"./model.ckpt",
cfg=config
)
print("Loaded Model")
except:
print("Failed to Load Model")
predictor = pl.Trainer(gpus=1)
val_pred = predictor.predict(model, dataloaders=val_loader)
val_preds = []
for v in val_pred:
val_preds.append(v)
val_preds = torch.cat(val_preds, 0)
oof = val_preds.cpu().numpy()
gc.collect()
wandb.finish()
np.save( "oof.npy" , oof )
np.mean(oof>0.)
try:
df_comments_to_score = pd.read_csv("/content/comments_to_score.csv.zip")
except:
df_comments_to_score = pd.read_csv("../input/jigsaw-toxic-severity-rating/comments_to_score.csv")
df_comments_to_score
df_comments_to_score.text = df_comments_to_score.text.apply(preprocess)
class JigsawSeverityInferenceModel(pl.LightningModule):
def __init__(self,cfg):
super().__init__()
self.bert_model = cfg.bert_model
self.regressor = nn.Sequential(
nn.LayerNorm(768),
nn.Linear(768, 1),
)
self.cfg = cfg
self.criterion = cfg.criterion
def forward(self, x):
ids_more_toxic, mask_more_toxic, token_type_ids_more_toxic = x
more_toxic_embed = self.bert_model(ids_more_toxic, attention_mask=mask_more_toxic, token_type_ids=token_type_ids_more_toxic)
more_toxic_embed = torch.mean(more_toxic_embed.last_hidden_state,axis=1)
more_toxic_score = self.regressor(more_toxic_embed)
return more_toxic_score
class JigsawSeverityInferenceDataset(Dataset):
def __init__(self, classify_dataset, cfg ):
self.classify_dataset = classify_dataset
self.max_length = cfg.max_length
self.tokenizer = cfg.bert_tokenizer
def __len__(self):
return len(self.classify_dataset)
def __getitem__(self, idx):
classify_dataset = self.classify_dataset.iloc[idx]
clean_text = str(classify_dataset.text)
inputs_text = self.tokenizer.encode_plus(
clean_text,
truncation=True,
return_attention_mask=True,
return_token_type_ids=True,
max_length = self.max_length,
padding="max_length"
)
ids = inputs_text['input_ids']
mask = inputs_text['attention_mask']
token_type_ids = inputs_text['token_type_ids']
return [
torch.tensor(ids, dtype=torch.long),
torch.tensor(mask, dtype=torch.long),
torch.tensor(token_type_ids, dtype=torch.long),
]
val_score_dataset = JigsawSeverityInferenceDataset(pd.DataFrame( {"text":df_val.less_toxic}), config)
val_score_loader = DataLoader(val_score_dataset, batch_size=config.batch_size, shuffle=False, num_workers=2)
infernce_model = JigsawSeverityInferenceModel(config)
infernce_model.bert_model = model.bert_model
infernce_model.regressor = model.regressor
predictor = pl.Trainer(gpus=1)
val_score_pred = predictor.predict(infernce_model, dataloaders=val_score_loader)
val_score_preds = []
for v in val_score_pred:
val_score_preds.append(v)
val_score_preds = torch.cat(val_score_preds, 0)
df_val["less_score"]=val_score_preds.cpu().numpy()
val_score_dataset = JigsawSeverityInferenceDataset(pd.DataFrame( {"text":df_val.more_toxic}), config)
val_score_loader = DataLoader(val_score_dataset, batch_size=config.batch_size, shuffle=False, num_workers=2)
infernce_model = JigsawSeverityInferenceModel(config)
infernce_model.bert_model = model.bert_model
infernce_model.regressor = model.regressor
predictor = pl.Trainer(gpus=1)
val_score_pred = predictor.predict(infernce_model, dataloaders=val_score_loader)
val_score_preds = []
for v in val_score_pred:
val_score_preds.append(v)
val_score_preds = torch.cat(val_score_preds, 0)
df_val["more_score"]=val_score_preds.cpu().numpy()
df_val
df_val.to_csv("df_val.csv", index=False)
test_dataset = JigsawSeverityInferenceDataset(df_comments_to_score, config)
test_loader = DataLoader(test_dataset, batch_size=config.batch_size, shuffle=False, num_workers=2)
test_pred_list=[]
infernce_model = JigsawSeverityInferenceModel(config)
infernce_model.bert_model = model.bert_model
infernce_model.regressor = model.regressor
predictor = pl.Trainer(gpus=1)
test_pred = predictor.predict(infernce_model, dataloaders=test_loader)
test_preds = []
for v in test_pred:
test_preds.append(v)
test_preds = torch.cat(test_preds, 0)
test_pred_list.append(test_preds)
scores=sigmoid(np.mean( [ v.cpu().numpy() for v in test_pred_list] ,axis=0))
plt.hist(scores)
plt.show()
df_comments_to_score["score"] = scores
df_comments_to_score.drop("text", axis=1).to_csv("submission.csv", index=False)
!pwd
!mkdir upload_dataset
!ls
!mv oof.npy /content/upload_dataset/oof.npy
!mv model.ckpt /content/upload_dataset/model.ckpt
!mv submission.csv /content/upload_dataset/submission.csv
! kaggle datasets init -p /content/upload_dataset
!kaggle datasets create -p /content/upload_dataset
df_val[df_val.more_score < df_val.less_score].more_score.hist(alpha=0.3, color="red")
df_val[df_val.more_score < df_val.less_score].less_score.hist(alpha=0.3, color="blue")
df_val[df_val.more_score >= df_val.less_score].more_score.hist(alpha=0.3, color="red")
df_val[df_val.more_score >= df_val.less_score].less_score.hist(alpha=0.3, color="blue")
df_val[df_val.more_score < df_val.less_score].more_score.hist( color="red", histtype='step')
df_val[df_val.more_score < df_val.less_score].less_score.hist( color="blue", histtype='step')
df_val[df_val.more_score >= df_val.less_score].more_score.hist( color="orange", histtype='step')
df_val[df_val.more_score >= df_val.less_score].less_score.hist( color="green", histtype='step')
```
| github_jupyter |
```
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 16, 3, bias=False) #Input = 28X28X1 - Output = 26X26X16 - RF = 3
self.bn1 = nn.BatchNorm2d(16, affine=True)
self.dropout1 = nn.Dropout2d(0.1)
self.conv2 = nn.Conv2d(16, 16, 3, bias=False) #Input = 26X26X16 - Output = 24X24X16 - RF = 5
self.bn2 = nn.BatchNorm2d(16, affine=True)
self.dropout2 = nn.Dropout2d(0.1)
self.conv3 = nn.Conv2d(16, 16, 3, bias=True) #Input = 24X24X16 - Output = 22X22X16 - RF = 7
self.bn3 = nn.BatchNorm2d(16, affine=True)
self.dropout3 = nn.Dropout2d(0.1)
self.pool1 = nn.MaxPool2d(2, 2) #Input = 22X22X16 - Output = 11X11X16 - RF = 8
self.conv4 = nn.Conv2d(16, 16, 3, bias=False) #Input = 11X11X16 - Output = 9X9X16- RF = 14
self.bn4 = nn.BatchNorm2d(16, affine=True)
self.dropout4 = nn.Dropout2d(0.1)
self.conv5 = nn.Conv2d(16, 16, 3, bias=False) #Input = 9X9X16 - Output = 7X7X16 - RF = 16
self.bn5 = nn.BatchNorm2d(16, affine=True)
self.dropout5 = nn.Dropout2d(0.1)
self.conv6 = nn.Conv2d(16, 16, 3, bias=False, padding=1) #Input = 7X7X16 - Output = 7X7X16 - RF = 18
self.bn6 = nn.BatchNorm2d(16, affine=True)
self.dropout6 = nn.Dropout2d(0.1)
self.avg_pool = nn.AvgPool2d(7) #Output = 1X1X16
self.pointwise3 = nn.Conv2d(16, 10, 1, bias=False)
#self.fc1 = nn.Linear(32, 10)
# self.conv7 = nn.Conv2d(16, 10, 3, bias=False) #Input = 3X3X32 - Output = 1X1X10 - RF = 28
def forward(self, x):
x = self.dropout1(self.bn1(F.relu(self.conv1(x))))
x = self.dropout2(self.bn2(F.relu(self.conv2(x))))
x = self.dropout3(self.bn3(F.relu(self.conv3(x))))
x = self.pool1(x)
x = self.dropout4(self.bn4(F.relu(self.conv4(x))))
x = self.dropout5(self.bn5(F.relu(self.conv5(x))))
x = self.dropout6(self.bn6(F.relu(self.conv6(x))))
# x = self.conv7(x)
#print(x.shape)
x = self.avg_pool(x)
#print(x.shape)
#x = x.view(-1, 32)
x = self.pointwise3(x)
#print(x.shape)
x = x.view(-1, 10)
return F.log_softmax(x, dim=1)
#!pip install torchsummary
from torchsummary import summary
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
model = Net().to(device)
summary(model, input_size=(1, 28, 28))
torch.manual_seed(1)
batch_size = 32
kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True, **kwargs)
from tqdm import tqdm
def train(model, device, train_loader, optimizer, epoch):
model.train()
pbar = tqdm(train_loader)
for batch_idx, (data, target) in enumerate(pbar):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
pbar.set_description(desc= f'loss={loss.item()} batch_id={batch_idx}')
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
for epoch in range(0, 19):
train(model, device, train_loader, optimizer, epoch)
test(model, device, test_loader)
```
| github_jupyter |
```
## Imports
import sys
import os
import time
import math
import random
import pdb
import h5py
import glob
# Plotting import
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.animation as animation
import numpy as np
import pandas as pd
from IPython.display import HTML
from mpl_toolkits.axes_grid1 import ImageGrid
import torchvision.utils as vutils
from torch import from_numpy
# Add the path to the parent directory to augment search for module
par_dir = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
if par_dir not in sys.path:
sys.path.append(par_dir)
from io_utils.data_handling_hitarray_train import WCH5DatasetT
# Import the utils for plotting the metrics
from plot_utils import plot_utils
from plot_utils import notebook_utils_2
from utils.plot_utils import get_plot_array
from sklearn.metrics import roc_curve, auc
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def disp_learn_hist_smoothed(location, losslim=None, window_train=400,window_val=40,show=True):
train_log=location+'/log_train.csv'
train_log_csv = pd.read_csv(train_log)
epoch_train = moving_average(np.array(train_log_csv.epoch),window_train)
gloss_train = moving_average(np.array(train_log_csv.g_loss),window_train)
dloss_train = moving_average(np.array(train_log_csv.d_loss),window_train)
fig, ax1 = plt.subplots(figsize=(12,8),facecolor='w')
line11 = ax1.plot(epoch_train, dloss_train, linewidth=2, label='Average training D loss', color='b', alpha=0.3)
ax1.set_xlabel('Epoch',fontweight='bold',fontsize=24,color='black')
ax1.tick_params('x',colors='black',labelsize=18)
ax1.set_ylabel('D Loss', fontsize=24, fontweight='bold',color='b')
ax1.tick_params('y',colors='b',labelsize=18)
'''
if losslim is not None:
ax1.set_ylim(0.,losslim)
else:
ax1.set_ylim(0.,1.5)
'''
ax2 = ax1.twinx()
line21 = ax2.plot(epoch_train, gloss_train, linewidth=2, label='Average training G loss', color='r', alpha=0.3)
ax2.set_ylabel('G Loss', fontsize=24, fontweight='bold',color='r')
ax2.tick_params('y',colors='r',labelsize=18)
# added these four lines
#lines = line11+ line12+ [line13]+ line21+ line22+ [line23]
lines = line11+ line21
#lines_sctr=[line13,line23]
#lines=lines_plt+lines_sctr
labels = [l.get_label() for l in lines]
leg = ax2.legend(lines, labels, fontsize=16, loc=5, numpoints=1)
leg_frame = leg.get_frame()
leg_frame.set_facecolor('white')
if show:
plt.grid()
plt.show()
return
return fig
disp_learn_hist_smoothed('/home/cmacdonald/CNN/dumps/20200814_170837_gan_19channels_randominit')
image_batches = [np.load(fname,allow_pickle=True)['gen_imgs'] for fname in glob.glob(os.path.join('/home/cmacdonald/CNN/dumps/20200814_170837_gan_19channels_randominit','imgs/*'))]
len(image_batches)
batch_grids=[]
for image_batch in image_batches:
batch_grid = np.concatenate([np.pad(np.squeeze(img),2,mode='constant',constant_values=(np.nan,)) for img in image_batch[0:8]],axis=1)
for row_index in range(1,8,1):
image_row = np.concatenate([np.pad(np.squeeze(img),2,mode='constant',constant_values=(np.nan,)) for img in image_batch[row_index*8:(row_index+1)*8]],axis=1)
batch_grid = np.concatenate((batch_grid,image_row),axis=0)
batch_grids.append(batch_grid)
fig = plt.figure(figsize=(25,25))
display_imgs=[batch_grids[5 * i] for i in range(int(len(batch_grids)/15))]
plt.axis("off")
ims = [[plt.imshow(img[:,:], animated=True,cmap=plt.cm.viridis)] for img in display_imgs]
ani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)
HTML(ani.to_jshtml())
fig=plt.figure(figsize=(15,15))
plt.imshow(batch_grids[-1],cmap=plt.cm.viridis)
```
## Note: the model above was trained on a dataset which had massively scaled charge values, some of which were negative
```
from io_utils.data_handling_hitarray_train import WCH5DatasetT
dset = WCH5DatasetT( ['/fast_scratch/WatChMaL/data/IWCDmPMT_4pi_full_tank_pointnet.h5'], ['/fast_scratch/WatChMaL/data/IWCD_fulltank_300_pe_idxs.npz'], '/fast_scratch/WatChMaL/data/IWCDmPMT_4pi_fulltank_9M_norm_params/IWCDmPMT_4pi_fulltank_9M_trainval_norm_params.npz', chrg_norm="identity", time_norm="identity", shuffle=1, collapse_arrays=True,trainval_subset=None, num_datasets = 1, seed=42)
image_batch_dset = [dset[idx][0]/np.max(dset[idx][0]) for idx in np.random.randint(0,high=len(dset),size=64)]
batch_grid_dset = np.concatenate([np.pad(np.squeeze(img),2,mode='constant',constant_values=(np.nan,)) for img in image_batch_dset[0:8]],axis=1)
for row_index in range(1,8,1):
image_row = np.concatenate([np.pad(np.squeeze(img),2,mode='constant',constant_values=(np.nan,)) for img in image_batch_dset[row_index*8:(row_index+1)*8]],axis=1)
batch_grid_dset = np.concatenate((batch_grid_dset,image_row),axis=0)
fig = plt.figure(figsize=(25,25))
plt.imshow(batch_grid_dset, animated=False,cmap=plt.cm.viridis)
count=0
for i in np.random.choice(len(dset),size=100000,replace=False):
if np.min(dset[i][0]) < 0: count +=1
print(count/100000)
import os
par_dir = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
if par_dir not in sys.path:
sys.path.append(par_dir)
from io_utils.data_handling_hitarray_train import WCH5DatasetT
dset = WCH5DatasetT( ['/fast_scratch/WatChMaL/data/IWCDmPMT_4pi_full_tank_pointnet.h5'], ['/fast_scratch/WatChMaL/data/IWCD_fulltank_300_pe_idxs.npz'], '/fast_scratch/WatChMaL/data/IWCDmPMT_4pi_fulltank_9M_norm_params/IWCDmPMT_4pi_fulltank_9M_trainval_norm_params.npz', chrg_norm="identity", time_norm="identity", shuffle=1, collapse_arrays=False,trainval_subset=None, num_datasets = 1, seed=42)
example_event=np.squeeze(dset[0][0])
print(f'Max: {np.max(example_event)} Min: {np.min(example_event)}')
example_event.dtype
hit_charges=np.random.randint(0,high=1000, dtype = np.int16, size=500)
hit_cols=np.random.randint(0,high=40, dtype = np.int16, size=500)
hit_rows=np.random.randint(0,high=40, dtype = np.int16, size=500)
hit_pmt_in_modules = np.random.randint(0,high=19, dtype = np.int16, size=500)
data = np.zeros((19,40,40))
data[hit_pmt_in_modules, hit_rows, hit_cols] = hit_charges
data=bogus_data
np.min(data)
from io_utils.data_handling_train import WCH5DatasetT
old_dset = WCH5DatasetT( ['/fast_scratch/WatChMaL/data/IWCDmPMT_4pi_fulltank_9M_splits_CNN/IWCDmPMT_4pi_fulltank_9M_trainval.h5'], ['/fast_scratch/WatChMaL/data/IWCDmPMT_4pi_fulltank_9M_splits_CNN/IWCDmPMT_4pi_fulltank_9M_trainval_idxs.npz'], '/fast_scratch/WatChMaL/data/IWCDmPMT_4pi_fulltank_9M_norm_params/IWCDmPMT_4pi_fulltank_9M_trainval_norm_params.npz', chrg_norm="identity", time_norm="identity", shuffle=1,trainval_subset=None, num_datasets = 1, seed=42)
old_example_event=old_dset[444][0]
plt.imshow(np.squeeze(np.sum(old_example_event,axis=0)),cmap=plt.cm.viridis)
np.min(old_example_event)
np.max(old_example_event)
for i in np.random.randint(0,high=len(old_dset),size=10000):
assert np.min(old_dset[i][0])>=0
```
| github_jupyter |
# Using a Vector Class
Copyright (c) 2017, 2019 Tor Olav Kristensen, http://subcube.com
https://github.com/t-o-k/scikit-vectors
Use of this source code is governed by a BSD-license that can be found in the LICENSE file.
```
from skvectors import create_class_Vector
# Create a 3-dimensional vector class
VC = create_class_Vector('VC', 'abc')
# Explicit alternative:
# VC = \
# create_class_Vector(
# name = 'VC',
# component_names = [ 'a', 'b', 'c' ],
# brackets = [ '<', '>' ],
# sep = ', ',
# cnull = 0,
# cunit = 1,
# functions = None
# )
# Null value for vector components in the class
VC.component_null()
# Unit value for vector components in the class
VC.component_unit()
# Basis vectors in class
VC.basis_a(), VC.basis_b(), VC.basis_c()
# Create a vector with all the components set to the cnull value
VC.zero()
# Create a vector with all the components set to the cunit value
VC.one()
# Null value for vector components
v = VC(7, -8, 9)
v.cnull
# Unit value for vector components
v = VC(7, -8, 9)
v.cunit
# Sum of component values in vector
v = VC(-3, 4, 5)
v.csum
# Product of component values in vector
v = VC(-3, 4, 5)
v.cprod
# Check if vector is zero vector
v = VC.zero()
v.is_zero_vector()
# Check if vector is zero vector
v = VC(0, 1e-14, 0)
v.is_zero_vector()
# Check if vector is not zero vector
v = VC(0, 0, 0)
bool(v)
# Check if vector is not zero vector
v = VC(0, 1e-14, 0)
bool(v)
# Check if vector contains a value
u = VC(2, 3, 4)
u.contains(3)
# Check if a vector does not contain a value
u = VC(2, 3, 4)
u.contains_not(3.0)
# Create a vector from the sum of vectors
VC.sum_of_vectors([ ])
# Create a vector from the sum of vectors
vectors = [ VC(-1, 2, 3), VC(-2, -2, 2), VC(4, 0, 5) ]
VC.sum_of_vectors(vectors)
# Create a vector from the sum of vectors
vectors = [ VC(-1, 2, 3), VC(-2, -2, 2), VC(4, 0, 5) ]
VC.sum_of_vectors(v for v in vectors)
# Create a vector from the sum of vectors and scalars
VC.sum_of_vectors([ VC(-1, 2, 3), 100, VC(-2, -2, 2), 8000 ])
# Create a vector from the product of vectors
VC.prod_of_vectors([ ])
# Create a vector from the product of vectors
vectors = [ VC(-1, 2, 3), VC(-2, -2, 2), VC(4, 0, 5) ]
VC.prod_of_vectors(vectors)
# Create a vector from the product of vectors
vectors = [ VC(-1, 2, 3), VC(-2, -2, 2), VC(4, 0, 5) ]
VC.prod_of_vectors(v for v in vectors)
# Create a vector from the product of vectors and scalars
VC.prod_of_vectors([ VC(-1, 2, 3), -1/2, VC(-2, -2, 2), 10 ])
# Create vectors by applying the math methods floor, ceil and trunc to vector components
from math import floor, ceil, trunc
v = VC(-2.8, 3.3, 5.9)
ceil(v), floor(v), trunc(v)
```
| github_jupyter |
```
import bluefog.torch as bf
from bluefog.common import topology_util
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import torch
%matplotlib inline
```
# Dynamic Topology over Exponential Two Graph
When running average consensus based decentralized algorithm, the communication cost is not neglectable usually. In one round, the vector length of communication is proportional to the number of edges -- $O(E)$. Even for exponential graph each node will contain only $O(log(|V|))$ edge, the total communication cost will be $O(|V|log(|V|))$, i.e. $O(Nlog(N))$. This is actually worse than the [ring-allreduce](https://arxiv.org/pdf/1802.05799.pdf) based decentralized algorithm, which only requires $O(2N)$ communication cost. Although ring-structed neighbor allreduce will have similar communication cost, the convergence speed of ring-structure is so slow that it can hinder the gradient descent. Actually, it is shown under some assumptions that ring-allreduce algorithm actually achieve the optimal bandwidth usage for static topology.
Fortunately, AWC algorithms or other variantions also work under dynamic topology. It means in each round, the underlying topology is dynamic, i.e., the communication graph $\mathcal{G}^k$ changes with time/iteration $k$. There are many choices for generating dynamic topologies. Among them, this notebook focuses on the *dynamic one peer strategy*, which means all agents only selection one neighbor agents (peer) at each communication around. You can immediate find that the communication cost decreased to $O(N)$ now.
When it combined with Exponential graph, you will see that it not only reduces the communications cost but surprisingly accelerates the average consensus speed under mild conditions.
```
# Consider a static exponential-2 graph with size 16
nx.draw_circular(topology_util.ExponentialTwoGraph(16))
```
Under exponential-2 graph, we know the agent $i$ will send the informaiton to $[i+1, i+2, i+4, \ldots, i+2^n]$ module $N$. Then, the dynamic one peer strategy can be easily generated through at iteration $k$, agent $i$ selects the neighbro $i+2^{k\%n}$. It is easy to see that dynamic topology is periodical and the period is $n$. Let's plot the case for exponential-2 graph with size 16, which should have 4 distinct one peer graphs.
```
n = 4
size = 2 ** n
G_full = topology_util.ExponentialTwoGraph(size=size)
for k in range(4):
plt.figure(figsize=(8, 6))
x = np.array([1.0 if i == 2 ** (k % n) else 0 for i in range(size)])
x /= x.sum()
topo = np.empty((size, size))
for i in range(size):
topo[i] = np.roll(x, i)
G = nx.from_numpy_array(topo, create_using=nx.DiGraph)
nx.draw_circular(G_full, node_size=800, width=2, edge_color="#C2C2C2")
nx.draw_circular(G, node_size=800, width=2)
plt.text(
1,
-1.2,
"Iteration K" + ("+" + str(k) if k != 0 else " "),
horizontalalignment="right",
verticalalignment="center",
fontsize=25,
)
plt.show()
```
It is not surprising that the communication cost is reduced. But you may wonder when we decrease the communication, will it hinder our convergence speed and eventually undermine the speedup brought by the communication? There is one simple lemma:
**Lemma** Suppose $W^{(k)}$ is the combination matrix at iteration $k$ over the dynamic one-peer exponential-2 graph with $N=2^n$ nodes. It holds that each $W^{(k)}$ is doubly-stochastic, i.e., $W^{(k)} \mathbb{1} = \mathbb{1}$ and $\mathbb{1}^T W^{(k)} = \mathbb{1}^T$. Furthermore, it holds that
\begin{align}\label{finite-time-average}
W^{(k+\ell)} W^{(k+\ell-1)} \cdots W^{(k+1)} W^{(k)}= \frac{1}{n}\mathbb{1}\mathbb{1}^T
\end{align}
for any integer $k \ge0$ and $\ell \ge n$.
Let's verify this in code.
```
all_combined_matrix = np.eye(size)
for k in range(4):
x = np.array([1.0 if i == 2 ** (k % n) else 0 for i in range(size)])
x /= x.sum()
topo = np.empty((size, size))
for i in range(size):
topo[i] = np.roll(x, i) # topo does not include self
W = (np.eye(size) + topo) / 2
all_combined_matrix = all_combined_matrix @ W
uniform_matrix = np.ones([size, size]) / size
np.all(np.isclose(all_combined_matrix - uniform_matrix, 0))
```
# Dynamic One Peer Strategy over General Topology
Similarly, we can design one peer strategy over general topology, i.e. every node pick one peer to send at each iterations. BlueFog provided several topology utility functions for several common dynamic topology cases. This dynamic one peer strategy is definitely covered -- `topology_util.GetDynamicOnePeerSendRecvRanks`.
It is not a function but [generator](https://docs.python.org/3/tutorial/classes.html#generators) actually. If you are not familar with the concept of generator, don't be afraid. It is easy. Check the following example
```
def simple_generator():
yield 1
yield 2
g = simple_generator()
print(next(g))
print(next(g))
```
You should use the `topology_util.GetDynamicOnePeerSendRecvRanks` in a similar style. It takes the `topology` and `self_rank` as input and at each iteration, it returns two lists -- one for the ranks of sending to and another for the ranks of receiving from with respect to that `self_rank`.
```
generator = topology_util.GetDynamicOnePeerSendRecvRanks(
topology_util.ExponentialTwoGraph(size=16), self_rank=0
)
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
```
Another example of using it over mesh grid topology.
```
generator = topology_util.GetDynamicOnePeerSendRecvRanks(
topology_util.MeshGrid2DGraph(size=16), self_rank=0
)
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
```
| github_jupyter |
# Dictionaries
A dictionary is datatype that contains a series of key-value pairs. It is similar to a list except for that the indices of the values can be strings, tuples, etc. not just integers. It is also different in that it is unordered. You cannot expect to get the keys in the same order out as you put them in.
To create a dictionary:
my_dict = { key1: value1, key2: value2 }
Creating an empty dictionary
my_dict = {}
my_dict = dict()
```
fruit_season = {
'raspberry': 'May',
'apple' : 'September',
'peach' : 'July',
'grape' : 'August'
}
print(type(fruit_season))
print(fruit_season)
```
To access a value, you index into it similarly to a list using square brackets.
value_of_key1 = my_dict['key1']
```
raspberry_season = fruit_season['raspberry']
print(raspberry_season)
```
Trying to access a key not in the dictionary throws an error
```
print(fruit_season['mangos'])
```
To add an item to the dictionary set the value equal to the indexed keys
dict['new_key'] = value
```
fruit_season['strawberry'] = 'May'
print(fruit_season)
fruit_season['strawberry']
```
To delete a key, use the del keyword
del dict['key to delete']
```
del fruit_season['strawberry']
print(fruit_season)
```
### Rules on keys
Keys in dictionary must be unique. If you try to make a duplicate key, the data will be overwritten
Keys must be hashable. What this means is they must come from immutable values and be comparable. You can use strings, numbers, tuples, sets, (most) objects. You cannot use lists or dictionaries as keys.
```
duplicate_fruit_season = {
'raspberry': 'May',
'raspberry': 'June',
}
print(duplicate_fruit_season)
mutable_key = {
['watermelon', 'cantaloupe', 'honeydew']: 'July'
}
# The solution is to use a tuple instead
immutable_key = {
('watermelon', 'cantelope', 'honeydew'): 'July'
}
```
### TRY IT
Create a dictionary called vegetable_season with Eggplant-> July and Onion -> May
```
vegetable_season = {
'Eggplant': 'July',
'Onion': 'May'
}
print(vegetable_season)
```
## Dictionary Operators
The in operator returns a boolean for whether the key is in the dictionary or not.
key in dictionary
```
print('raspberry' in fruit_season)
print('mangos' in fruit_season)
```
You can use this in if statement
```
if 'pineapple' in fruit_season:
print('Lets eat tropical fruit')
else:
print("Temperate fruit it is.")
```
### TRY IT
Check if 'broccoli' is in vegetable_season. If so, print 'Yum, little trees!'
```
if 'broccoli' in vegetable_season:
print('Yum, little trees!')
else:
print('No little trees.')
```
## Dictionaries and Loops
You can use a for in loop to loop through dictionaries
for key in dictionary:
print key
```
for fruit in fruit_season:
print ("{0} is best in {1} (at least in Virginia)".format(fruit.title(), fruit_season[fruit]))
```
## Dictionary Methods
You can use the `keys`, `values`, or `items` methods to return lists of keys, values, or key-value tuples respectively.
You can then use these for sorting or for looping
```
print(fruit_season.keys())
print(fruit_season.values())
print(fruit_season.items())
for key, value in fruit_season.items():
print ("In {0} eat a {1}".format(value, key))
print (sorted(fruit_season.keys()))
```
### TRY IT
Loop through the sorted keys of the vegetable_season dictionary. For each key, print the month it is in season
```
for fruit in sorted(fruit_season.keys()):
print('In {0} {1} is in season.'.format(fruit_season[fruit], fruit))
```
## More complex dictionaries
Dictionary keys and values can be almost anything. The keys must be hashable which means it cannot change. That means that lists and dictionaries cannot be keys (but strings, tuples, and integers can).
Values can be just about anything, though.
```
my_complicated_dictionary = {
(1, 2, 3): 6,
'weevil': {
'e': 2,
'i': 1,
'l': 1,
'v': 1,
'w': 1,
},
9: [3, 3]
}
print (my_complicated_dictionary)
```
Let's use this to create a more realistic fruit season dictionary
```
true_fruit_season = {
'raspberry': ['May', 'June'],
'apple': ['September', 'October', 'November', 'December'],
'peach': ['July', 'August'],
'grape': ['August', 'September', 'October']
}
print (true_fruit_season)
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
for month in months:
print ('It is {0}'.format(month))
for fruit, season in true_fruit_season.items():
if month in season:
print ("\tEat {0}".format(fruit))
```
### TRY IT
Add a key to the true_fruit_season for 'watermelons' the season is July, August, and September
## Project: Acrostic
Create an acrostic poem generator.
You will create a function that takes a name and generates an acrostic poem
1. Create a dictionary that has each of the capital letters as keys and an adjective that start with the letter as the value and store in variable named adjectives. (Reference: http://www.enchantedlearning.com/wordlist/adjectives.shtml)
2. Create a function called "acrostic", which takes one parameter "name" as argument.
3. In the acrostic function capitalize the name (use the upper method)
4. For each letter in the name
5. Get the adjective corresponding to that letter (from our dictionary) and store it in a variable called current_adj
6. Print out Letter-current_adj
** Challenge ** instead of just one adjective have each letter's value be a list of adjectives. Use the random module to select a random adjective instead of always selecting the same one.
```
from random import randint #necessary for "challenge"
# step 1: create dictionary with one adjective per letter of the alphabet
myadjectives = {
'A':['admirable','aggressive','agile','agitated','agonizing','agreeable'],
'B':'biodegradable',
'C':['cloudy','creative'],
'D':'deserted',
'E':'everlasting',
'F':'flamboyant',
'G':'grotesque',
'H':'humming',
'I':'imperfect',
'J':'joyful',
'K':'kosher',
'L':'lively',
'M':'modest',
'N':'nervous',
'O':'ornate',
'P':'playful',
'Q':'quick',
'R':['restless','relieved','remarkable','remorseful', 'remote'],
'S':'strong',
'T':'tiny',
'U':'ugly',
'V':'vital',
'W':['wobbly','well-made'],
'X':'oops!',
'Y':'youthful',
'Z':'zesty'
}
type(myadjectives['C'])
# step 2: create funtion acrostic, takes name as an argument
def acrostic (name):
# step 3: capitalize name
capName = name.upper()
# step 4
for letter in capName:
current_adj_list = myadjectives[letter]
if type(current_adj_list) == list:
current_adj = current_adj_list[randint(0,len(current_adj_list)-1)]
else:
current_adj = current_adj_list
print("{0} - {1}".format(letter, current_adj))
acrostic('Lilly')
```
## Bonus Material
Auto generating the dictionary for the acrostic:
```
# If you have a list of adjectives
my_dict = {}
# Imaging this is the full alphabet
for i in ['A', 'B', 'C']:
my_dict[i] = []
for i in ['Adoreable', 'Acceptable', 'Bad', 'Cute', 'Basic', 'Dumb','Active']:
first_char = i[0]
if first_char in my_dict:
my_dict[first_char].append(i)
print (my_dict)
# Generating from a file
my_dict = {}
for i in ['A', 'B', 'C']:
my_dict[i] = []
# adjectives.txt has one adjective per line
with open('adjectives.txt') as fh:
for line in fh:
word = line.rstrip().title()
first_char = word[0]
if first_char in my_dict:
my_dict[first_char].append(word)
print (my_dict['A'])
```
| github_jupyter |
# Analysis for reactions addition allowing growth on uncommon substrates
Once the models have been loaded and prepared (*see Tutorial 1*) the analysis can be performed. The pipeline first conisders if the model is able to grow on the user-indicated carbon source and if not it looks for which reactions from the universal model could be added to the model of the chassis organism in order to confer that function to it.
This first search of reactions allowing growth on an uncommon substrate is done with the function *analysis_gf_sol*. This function sets the right constraint in the model of the chassis and then calls the COBRApy[1] function for [gapfilling analysis](https://cobrapy.readthedocs.io/en/latest/gapfilling.html). In particular, *analysis_gf_sol* sets the upper bound of the biomass reactions to the normal growth rate in the wild type chassis. Thus, any reaction addition that is identified with gap-filling leads to a growth rate that is maximally equal to the wild type. (The objective of the optimization is the biomass reaction)
The function *dict_prod_sol* is used to evaluate if the addition of the reactions indicated by the gapfilling analysis makes the chassis' model also able to produce a target product indicate by the user. If the model can't already simulate production the function *dict_prod_sol* calls again the COBRApy[1] function for [gapfilling analysis](https://cobrapy.readthedocs.io/en/latest/gapfilling.html).
Checking the model's ability to produce the target compound requires a different model objective and additional constraints. The objective of the optimization is set to be the exchange reaction of the target. The biomass reaction has to be constrained in the lower bound, to indicate the model that the optimization of the formation of the target should still allow growth, otherwise the simulation will maximize production leading to 0 1/h growth rate, which is not realistic. Additionally, the uptake of the substrate is constrained by setting a minium lower value that can be indicated by the user if the ammount of substrate in the medium can be estimated.
If the consumption of a compound in the medium is the only optimization of interest, an intermediate of the degradation pathway should be indicated anyway in order to be able to use the other functions of the pipeline (including the one needed to score the options). This is due to the fact that the functions downstream to *analysis_gf_sol* build upon the output of this function, hence *dict_prod_sol* uses the output of *analysis_gf_sol* as argument, while the output of both previous function is used by *cons_prod_dict* to generate a final object comprehensive of all the information gathered previously and calls the thermodynamic analysis too. This final output is used among others by *scores_evaluations* to score the several alternative reaction addition and the fluxes of substrate uptake and product formation.
In this example a model of *Escherichia coli* is used to generate strains able to grow on methane. Formate is indicated as target product as it is an intermediate of methane oxidation pathway.
#### Import statemets
```
from pipeline_package import import_models, input_parser, analysis
```
#### Load models
```
data_repo = "../inputs"
model = import_models.get_reference_model(data_repo, '../inputs/ecoli_tutorial2.csv')
universal = import_models.get_universal_main(data_repo, '../inputs/ecoli_tutorial2.csv')
```
#### Prepare models
```
input_parser.parser('../inputs/ecoli_tutorial2.csv', universal, model)
```
The printed output above can be unserstood better looking at the example input file *ecoli_tutorial2.csv* that can be found in the inputs directory.
* There is not transporter of methane in E. coli model iML1515. Thus, the pipeline adds the reaction included in the input file
* Formate, intermediate product of methane oxidation is indicated as target
* ALCD1 reaction (methanole dehydrogenase) is already in the model, so the pipeline recognize it and does not add it to the universal
* There are no methane oxidizing reactions in the BiGG database, therefore the pipeline adds them to the universal reaction model.

## Running the analysis for making the model able to grow on the indicated substrate
In this case the objective is to have an *E. coli* strain able to grow on methane. The chassis can't naturally grow on methane, therefore it is expected that the pipeline will use gapfilling to serach for additional reactions. The search can take few hours, depending on the PC, the number of iteration and the type of reactions needed. For this analysis on a Windows AMD64 processor running the pipeline via Jupyter notebook it takes apporximately 4 hours.
```
consumption = analysis.analysis_gf_sol('../inputs/ecoli_tutorial2.csv', model, universal)
```
## Explanation of the printed output
The output reports several information relative to the set up of the analysis as introduced above (e.g. constraints) and the results of the analysis with gapfilling. In order from top to bottom you can find the following information:
- The biomass upper bound to the growth rate of the wild type (0.87 1/h)
- Indication of the fluxes of the compounds that are take up from the mediume by the wild type strain
- The old and new bounds of the exchange reaction of the compounds indicated by the user
- The result of the analysis start after the indication that GapFilling algorithm is being run.
- The analysis of gapfilling can be run in several iteration (each one looking for reactions that if added satisfy the model's objective, growth in this case). The result of each iteration starts with a number.
This function also generate an intermediate .csv file that can be found in the pipeline/outputs folder. It is advicable to rename the file before running *analysis_gf_sol* further, otherwise it get overwritten
```
production = analysis.dict_prod_sol('../inputs/ecoli_tutorial2.csv', consumption, model, universal)
```
### Explanation of the printed output
since the model can already produce formate, gapfilling analysis is not run and thus the analysis is way faster. production variable is then a dictionary in which the production rates are indicated. This output is not to be read on its own but mostly needed by the following function, that integrates it with the output of *analysis_gf_sol* function
```
final = analysis.cons_prod_dict('../inputs/ecoli_tutorial2.csv', model, universal, consumption, production)
```
### Explanation of the printed output
Most of what is preinted is related to the thermodynamic analysis. This output is the most comprehensive one and is structured with nested python dictionaries. Every solution of *analysis_gf_sol* is indicated as with the key consumption following by the number of the round of iteration of gapfilling (with the fluxes of consumption of the substrate). The respective production key reports the results of *dict_prod_sol* analysis (i.e. the fluxes of production of the target) and the result of the thermodynamic analysis.
scores_output = scores_evaluations('../inputs/ecoli_tutorial2.csv', consumption, final)
**References**
1. A. Ebrahim, J. A. Lerman, B. O. Palsson, and D. R. Hyduke, “COBRApy: COnstraints-Based Reconstruction and Analysis for Python,” BMC Syst. Biol., vol. 7, no. 1, p. 74, Aug. 2013, doi: 10.1186/1752-0509-7-74.
| github_jupyter |
# Machine Translation English-German Example Using SageMaker Seq2Seq
1. [Introduction](#Introduction)
2. [Setup](#Setup)
3. [Download dataset and preprocess](#Download-dataset-and-preprocess)
3. [Training the Machine Translation model](#Training-the-Machine-Translation-model)
4. [Inference](#Inference)
## Introduction
Welcome to our Machine Translation end-to-end example! In this demo, we will train a English-German translation model and will test the predictions on a few examples.
SageMaker Seq2Seq algorithm is built on top of [Sockeye](https://github.com/awslabs/sockeye), a sequence-to-sequence framework for Neural Machine Translation based on MXNet. SageMaker Seq2Seq implements state-of-the-art encoder-decoder architectures which can also be used for tasks like Abstractive Summarization in addition to Machine Translation.
To get started, we need to set up the environment with a few prerequisite steps, for permissions, configurations, and so on.
## Setup
Let's start by specifying:
- The S3 bucket and prefix that you want to use for training and model data. **This should be within the same region as the Notebook Instance, training, and hosting.**
- The IAM role arn used to give training and hosting access to your data. See the documentation for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the boto regexp in the cell below with a the appropriate full IAM role arn string(s).
```
# S3 bucket and prefix
bucket = '<your_s3_bucket_name_here>'
prefix = 'sagemaker/DEMO-seq2seq'
import boto3
import re
from sagemaker import get_execution_role
role = get_execution_role()
```
Next, we'll import the Python libraries we'll need for the remainder of the exercise.
```
from time import gmtime, strftime
import time
import numpy as np
import os
import json
# For plotting attention matrix later on
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
```
## Download dataset and preprocess
In this notebook, we will train a English to German translation model on a dataset from the
[Conference on Machine Translation (WMT) 2017](http://www.statmt.org/wmt17/).
```
%%bash
wget http://data.statmt.org/wmt17/translation-task/preprocessed/de-en/corpus.tc.de.gz & \
wget http://data.statmt.org/wmt17/translation-task/preprocessed/de-en/corpus.tc.en.gz & wait
gunzip corpus.tc.de.gz & \
gunzip corpus.tc.en.gz & wait
mkdir validation
curl http://data.statmt.org/wmt17/translation-task/preprocessed/de-en/dev.tgz | tar xvzf - -C validation
```
Please note that it is a common practise to split words into subwords using Byte Pair Encoding (BPE). Please refer to [this](https://github.com/awslabs/sockeye/tree/master/tutorials/wmt) tutorial if you are interested in performing BPE.
Since training on the whole dataset might take several hours/days, for this demo, let us train on the **first 10,000 lines only**. Don't run the next cell if you want to train on the complete dataset.
```
!head -n 10000 corpus.tc.en > corpus.tc.en.small
!head -n 10000 corpus.tc.de > corpus.tc.de.small
```
Now, let's use the preprocessing script `create_vocab_proto.py` (provided with this notebook) to create vocabulary mappings (strings to integers) and convert these files to x-recordio-protobuf as required for training by SageMaker Seq2Seq.
Uncomment the cell below and run to see check the arguments this script expects.
```
%%bash
# python3 create_vocab_proto.py -h
```
The cell below does the preprocessing. If you are using the complete dataset, the script might take around 10-15 min on an m4.xlarge notebook instance. Remove ".small" from the file names for training on full datasets.
```
%%time
%%bash
python3 create_vocab_proto.py \
--train-source corpus.tc.en.small \
--train-target corpus.tc.de.small \
--val-source validation/newstest2014.tc.en \
--val-target validation/newstest2014.tc.de
```
The script will output 4 files, namely:
- train.rec : Contains source and target sentences for training in protobuf format
- val.rec : Contains source and target sentences for validation in protobuf format
- vocab.src.json : Vocabulary mapping (string to int) for source language (English in this example)
- vocab.trg.json : Vocabulary mapping (string to int) for target language (German in this example)
Let's upload the pre-processed dataset and vocabularies to S3
```
def upload_to_s3(bucket, prefix, channel, file):
s3 = boto3.resource('s3')
data = open(file, "rb")
key = prefix + "/" + channel + '/' + file
s3.Bucket(bucket).put_object(Key=key, Body=data)
upload_to_s3(bucket, prefix, 'train', 'train.rec')
upload_to_s3(bucket, prefix, 'validation', 'val.rec')
upload_to_s3(bucket, prefix, 'vocab', 'vocab.src.json')
upload_to_s3(bucket, prefix, 'vocab', 'vocab.trg.json')
region_name = boto3.Session().region_name
containers = {'us-west-2': '433757028032.dkr.ecr.us-west-2.amazonaws.com/seq2seq:latest',
'us-east-1': '811284229777.dkr.ecr.us-east-1.amazonaws.com/seq2seq:latest',
'us-east-2': '825641698319.dkr.ecr.us-east-2.amazonaws.com/seq2seq:latest',
'eu-west-1': '685385470294.dkr.ecr.eu-west-1.amazonaws.com/seq2seq:latest'}
container = containers[region_name]
print('Using SageMaker Seq2Seq container: {} ({})'.format(container, region_name))
```
## Training the Machine Translation model
```
job_name = 'DEMO-seq2seq-en-de-' + strftime("%Y-%m-%d-%H", gmtime())
print("Training job", job_name)
create_training_params = \
{
"AlgorithmSpecification": {
"TrainingImage": container,
"TrainingInputMode": "File"
},
"RoleArn": role,
"OutputDataConfig": {
"S3OutputPath": "s3://{}/{}/".format(bucket, prefix)
},
"ResourceConfig": {
# Seq2Seq does not support multiple machines. Currently, it only supports single machine, multiple GPUs
"InstanceCount": 1,
"InstanceType": "ml.p2.xlarge", # We suggest one of ["ml.p2.16xlarge", "ml.p2.8xlarge", "ml.p2.xlarge"]
"VolumeSizeInGB": 50
},
"TrainingJobName": job_name,
"HyperParameters": {
# Please refer to the documentation for complete list of parameters
"max_seq_len_source": "60",
"max_seq_len_target": "60",
"optimized_metric": "bleu",
"batch_size": "64", # Please use a larger batch size (256 or 512) if using ml.p2.8xlarge or ml.p2.16xlarge
"checkpoint_frequency_num_batches": "1000",
"rnn_num_hidden": "512",
"num_layers_encoder": "1",
"num_layers_decoder": "1",
"num_embed_source": "512",
"num_embed_target": "512",
"checkpoint_threshold": "3",
"max_num_batches": "2100"
# Training will stop after 2100 iterations/batches.
# This is just for demo purposes. Remove the above parameter if you want a better model.
},
"StoppingCondition": {
"MaxRuntimeInSeconds": 48 * 3600
},
"InputDataConfig": [
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": "s3://{}/{}/train/".format(bucket, prefix),
"S3DataDistributionType": "FullyReplicated"
}
},
},
{
"ChannelName": "vocab",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": "s3://{}/{}/vocab/".format(bucket, prefix),
"S3DataDistributionType": "FullyReplicated"
}
},
},
{
"ChannelName": "validation",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": "s3://{}/{}/validation/".format(bucket, prefix),
"S3DataDistributionType": "FullyReplicated"
}
},
}
]
}
sagemaker_client = boto3.Session().client(service_name='sagemaker')
sagemaker_client.create_training_job(**create_training_params)
status = sagemaker_client.describe_training_job(TrainingJobName=job_name)['TrainingJobStatus']
print(status)
status = sagemaker_client.describe_training_job(TrainingJobName=job_name)['TrainingJobStatus']
print(status)
# if the job failed, determine why
if status == 'Failed':
message = sagemaker_client.describe_training_job(TrainingJobName=job_name)['FailureReason']
print('Training failed with the following error: {}'.format(message))
raise Exception('Training job failed')
```
> Now wait for the training job to complete and proceed to the next step after you see model artifacts in your S3 bucket.
You can jump to [Use a pretrained model](#Use-a-pretrained-model) as training might take some time.
## Inference
A trained model does nothing on its own. We now want to use the model to perform inference. For this example, that means translating sentence(s) from English to German.
This section involves several steps,
- Create model - Create a model using the artifact (model.tar.gz) produced by training
- Create Endpoint Configuration - Create a configuration defining an endpoint, using the above model
- Create Endpoint - Use the configuration to create an inference endpoint.
- Perform Inference - Perform inference on some input data using the endpoint.
### Create model
We now create a SageMaker Model from the training output. Using the model, we can then create an Endpoint Configuration.
```
use_pretrained_model = False
```
### Use a pretrained model
#### Please uncomment and run the cell below if you want to use a pretrained model, as training might take several hours/days to complete.
```
# use_pretrained_model = True
# model_name = "DEMO-pretrained-en-de-model"
# !curl https://s3-us-west-2.amazonaws.com/gsaur-seq2seq-data/seq2seq/eng-german/full-nb-translation-eng-german-p2-16x-2017-11-24-22-25-53/output/model.tar.gz > model.tar.gz
# !curl https://s3-us-west-2.amazonaws.com/gsaur-seq2seq-data/seq2seq/eng-german/full-nb-translation-eng-german-p2-16x-2017-11-24-22-25-53/output/vocab.src.json > vocab.src.json
# !curl https://s3-us-west-2.amazonaws.com/gsaur-seq2seq-data/seq2seq/eng-german/full-nb-translation-eng-german-p2-16x-2017-11-24-22-25-53/output/vocab.trg.json > vocab.trg.json
# upload_to_s3(bucket, prefix, 'pretrained_model', 'model.tar.gz')
# model_data = "s3://{}/{}/pretrained_model/model.tar.gz".format(bucket, prefix)
%%time
sage = boto3.client('sagemaker')
if not use_pretrained_model:
info = sage.describe_training_job(TrainingJobName=job_name)
model_name=job_name
model_data = info['ModelArtifacts']['S3ModelArtifacts']
print(model_name)
print(model_data)
primary_container = {
'Image': container,
'ModelDataUrl': model_data
}
create_model_response = sage.create_model(
ModelName = model_name,
ExecutionRoleArn = role,
PrimaryContainer = primary_container)
print(create_model_response['ModelArn'])
```
### Create endpoint configuration
Use the model to create an endpoint configuration. The endpoint configuration also contains information about the type and number of EC2 instances to use when hosting the model.
Since SageMaker Seq2Seq is based on Neural Nets, we could use an ml.p2.xlarge (GPU) instance, but for this example we will use a free tier eligible ml.m4.xlarge.
```
from time import gmtime, strftime
endpoint_config_name = 'DEMO-Seq2SeqEndpointConfig-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print(endpoint_config_name)
create_endpoint_config_response = sage.create_endpoint_config(
EndpointConfigName = endpoint_config_name,
ProductionVariants=[{
'InstanceType':'ml.m4.xlarge',
'InitialInstanceCount':1,
'ModelName':model_name,
'VariantName':'AllTraffic'}])
print("Endpoint Config Arn: " + create_endpoint_config_response['EndpointConfigArn'])
```
### Create endpoint
Lastly, we create the endpoint that serves up model, through specifying the name and configuration defined above. The end result is an endpoint that can be validated and incorporated into production applications. This takes 10-15 minutes to complete.
```
%%time
import time
endpoint_name = 'DEMO-Seq2SeqEndpoint-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print(endpoint_name)
create_endpoint_response = sage.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=endpoint_config_name)
print(create_endpoint_response['EndpointArn'])
resp = sage.describe_endpoint(EndpointName=endpoint_name)
status = resp['EndpointStatus']
print("Status: " + status)
# wait until the status has changed
sage.get_waiter('endpoint_in_service').wait(EndpointName=endpoint_name)
# print the status of the endpoint
endpoint_response = sage.describe_endpoint(EndpointName=endpoint_name)
status = endpoint_response['EndpointStatus']
print('Endpoint creation ended with EndpointStatus = {}'.format(status))
if status != 'InService':
raise Exception('Endpoint creation failed.')
```
If you see the message,
> Endpoint creation ended with EndpointStatus = InService
then congratulations! You now have a functioning inference endpoint. You can confirm the endpoint configuration and status by navigating to the "Endpoints" tab in the AWS SageMaker console.
We will finally create a runtime object from which we can invoke the endpoint.
```
runtime = boto3.client(service_name='runtime.sagemaker')
```
# Perform Inference
### Using JSON format for inference (Suggested for a single or small number of data instances)
#### Note that you don't have to convert string to text using the vocabulary mapping for inference using JSON mode
```
sentences = ["you are so good !",
"can you drive a car ?",
"i want to watch a movie ."
]
payload = {"instances" : []}
for sent in sentences:
payload["instances"].append({"data" : sent})
response = runtime.invoke_endpoint(EndpointName=endpoint_name,
ContentType='application/json',
Body=json.dumps(payload))
response = response["Body"].read().decode("utf-8")
response = json.loads(response)
print(response)
```
### Retrieving the Attention Matrix
Passing `"attention_matrix":"true"` in `configuration` of the data instance will return the attention matrix.
```
sentence = 'can you drive a car ?'
payload = {"instances" : [{
"data" : sentence,
"configuration" : {"attention_matrix":"true"}
}
]}
response = runtime.invoke_endpoint(EndpointName=endpoint_name,
ContentType='application/json',
Body=json.dumps(payload))
response = response["Body"].read().decode("utf-8")
response = json.loads(response)['predictions'][0]
source = sentence
target = response["target"]
attention_matrix = np.array(response["matrix"])
print("Source: %s \nTarget: %s" % (source, target))
# Define a function for plotting the attentioan matrix
def plot_matrix(attention_matrix, target, source):
source_tokens = source.split()
target_tokens = target.split()
assert attention_matrix.shape[0] == len(target_tokens)
plt.imshow(attention_matrix.transpose(), interpolation="nearest", cmap="Greys")
plt.xlabel("target")
plt.ylabel("source")
plt.gca().set_xticks([i for i in range(0, len(target_tokens))])
plt.gca().set_yticks([i for i in range(0, len(source_tokens))])
plt.gca().set_xticklabels(target_tokens)
plt.gca().set_yticklabels(source_tokens)
plt.tight_layout()
plot_matrix(attention_matrix, target, source)
```
### Using Protobuf format for inference (Suggested for efficient bulk inference)
Reading the vocabulary mappings as this mode of inference accepts list of integers and returns list of integers.
```
import io
import tempfile
from record_pb2 import Record
from create_vocab_proto import vocab_from_json, reverse_vocab, write_recordio, list_to_record_bytes, read_next
source = vocab_from_json("vocab.src.json")
target = vocab_from_json("vocab.trg.json")
source_rev = reverse_vocab(source)
target_rev = reverse_vocab(target)
sentences = ["this is so cool",
"i am having dinner .",
"i am sitting in an aeroplane .",
"come let us go for a long drive ."]
```
Converting the string to integers, followed by protobuf encoding:
```
# Convert strings to integers using source vocab mapping. Out-of-vocabulary strings are mapped to 1 - the mapping for <unk>
sentences = [[source.get(token, 1) for token in sentence.split()] for sentence in sentences]
f = io.BytesIO()
for sentence in sentences:
record = list_to_record_bytes(sentence, [])
write_recordio(f, record)
response = runtime.invoke_endpoint(EndpointName=endpoint_name,
ContentType='application/x-recordio-protobuf',
Body=f.getvalue())
response = response["Body"].read()
```
Now, parse the protobuf response and convert list of integers back to strings
```
def _parse_proto_response(received_bytes):
output_file = tempfile.NamedTemporaryFile()
output_file.write(received_bytes)
output_file.flush()
target_sentences = []
with open(output_file.name, 'rb') as datum:
next_record = True
while next_record:
next_record = read_next(datum)
if next_record:
rec = Record()
rec.ParseFromString(next_record)
target = list(rec.features["target"].int32_tensor.values)
target_sentences.append(target)
else:
break
return target_sentences
targets = _parse_proto_response(response)
resp = [" ".join([target_rev.get(token, "<unk>") for token in sentence]) for
sentence in targets]
print(resp)
```
# Stop / Close the Endpoint (Optional)
Finally, we should delete the endpoint before we close the notebook.
```
sage.delete_endpoint(EndpointName=endpoint_name)
```
| github_jupyter |
# Specific arguments for particular field geometry
The openPMD format supports 3 types of geometries:
- Cartesian 2D
- Cartesian 3D
- Cylindrical with azimuthal decomposition (thetaMode)
This notebook shows how to use the arguments of `get_field` which are specific to a given geometry.
## (optional) Preparing this notebook to run it locally
If you choose to run this notebook on your local machine, you will need to download the openPMD data files which will then be visualized. To do so, execute the following cell. (Downloading the data may take a few seconds.)
```
import os, sys, tarfile, wget
def download_if_absent( dataset_name ):
"Function that downloads and decompress a chosen dataset"
if os.path.exists( dataset_name ) is False:
tar_name = "%s.tar.gz" %dataset_name
url = "https://github.com/openPMD/openPMD-example-datasets/raw/draft/%s" %tar_name
wget.download(url, tar_name)
with tarfile.open( tar_name ) as tar_file:
tar_file.extractall()
os.remove( tar_name )
download_if_absent( 'example-3d' )
download_if_absent( 'example-thetaMode' )
```
In addition, we choose here to incorporate the plots inside the notebook.
```
%matplotlib inline
```
## Preparing the API
Again, we need to import the `OpenPMDTimeSeries` object:
```
from opmd_viewer import OpenPMDTimeSeries
```
and to create objects that point to the 3D data and the cylindrical data.
(NB: The argument `check_all_files` below is optional. By default, `check_all_files` is `True`, and in this case the code checks that all files in the timeseries are consistent
i.e. that they all contain the same fields and particle quantities, with the same metadata. When `check_all_files` is `False`, these verifications are skipped, and this allows to create the `OpenPMDTimeSeries` object faster.)
```
ts_3d = OpenPMDTimeSeries('./example-3d/hdf5/', check_all_files=False )
ts_circ = OpenPMDTimeSeries('./example-thetaMode/hdf5/', check_all_files=False )
```
## 3D Cartesian geometry
For 3D Cartesian geometry, the `get_field` method has additional arguments, in order to select a 2D slice into the 3D volume:
- `slicing_dir` allows to choose the axis across which the slice is taken. See the examples below:
```
# Slice across y (i.e. in a plane parallel to x-z)
rho1, info_rho1 = ts_3d.get_field( field='rho', iteration=500, vmin=-5e6,
slicing_dir='y', plot=True )
# Slice across z (i.e. in a plane parallel to x-y)
rho2, info_rho2 = ts_3d.get_field( field='rho', iteration=500, vmin=-5e6,
slicing_dir='z', plot=True )
```
- For one given slicing direction, `slicing` allows to select which slice to take: `slicing` is a number between -1 and 1, where -1 indicates to take the slice at the lower bound of the slicing range (e.g. $z_min$ if `slicing_dir` is `z`) and 1 indicates to take the slice at the upper bound of the slicing range (e.g. $z_max$ if `slicing_dir` is `z`). For example:
```
# Slice across z, very close to zmin.
rho2, info_rho2 = ts_3d.get_field( field='rho', iteration=500, vmin=-5e6,
slicing_dir='z', slicing=-0.9, plot=True )
```
## Cylindrical geometry (with azimuthal decomposition)
In for data in the `thetaMode` geometry, the fields are decomposed into azimuthal modes. Thus, the `get_field` method has an argument `m`, which allows to select the mode:
- Choosing an integer value for selects a particular mode (for instance, here one can see a laser-wakefield, which is entirely contained in the mode 0)
```
Ey, info_Ey = ts_circ.get_field( field='E', coord='y', iteration=500, m=0,
plot=True, theta=0.5)
```
- Choosing `m='all'` sums all the modes (for instance, here the laser field, which is in the mode 1, dominates the fields)
```
Ey, info_Ey = ts_circ.get_field( field='E', coord='y', iteration=500, m='all',
plot=True, theta=0.5)
```
The argument `theta` (in radians) selects the plane of observation: this plane contains the $z$ axis and has an angle `theta` with respect to the $x$ axis.
In addition, in cylindrical geometry, the users can also choose the coordinates `r` and `t` for the radial and azimuthal components of the fields. For instance:
```
Er, info_Er = ts_circ.get_field( field='E', coord='r', iteration=500, m=0,
plot=True, theta=0.5)
```
| github_jupyter |
# Pytorch.Org Basics
Following tutorial on https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html.
**What is Pytorch?**
It’s a Python based scientific computing package targeted at two sets of audiences:
- A replacement for NumPy to use the power of GPUs
- A deep learning research platform that provides maximum flexibility and speed
## Tensors
Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.
```
from __future__ import print_function
import torch
```
Construct a 5x3 matrix, uninitialized:
```
x = torch.empty(5, 3)
print(x)
```
Construct a randomly initialized matrix:
```
x = torch.rand(5, 3)
print(x)
```
Construct a matrix filled zeros and of dtype long:
```
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
```
Construct a tensor directly from data:
```
x = torch.tensor([5.5, 3])
print(x)
```
Or create a tensor based on an existing tensor. These methods will reuse properties of the input tensor, e.g. dtype, unless new values are provided by user
```
x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes
print(x)
x = torch.randn_like(x, dtype=torch.float) # override dtype!
print(x) # result has the same size
```
Get its size:
```
print(x.size())
```
## Operations
There are multiple syntaxes for operations. In the following example, we will take a look at the addition operation.
Addition: syntax 1
```
y = torch.rand(5, 3)
print(x + y)
```
Syntax 2.
```
print(torch.add(x, y))
```
Addition: providing an output tensor as argument
```
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
```
Addition: in-place
```
# adds x to y
y.add_(x)
print(y)
```
You can use standard NumPy-like indexing with all bells and whistles!
```
print(x[:, 1])
```
Resizing: If you want to resize/reshape tensor, you can use torch.view:
```
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
```
If you have a one element tensor, use .item() to get the value as a Python number
```
x = torch.randn(1)
print(x)
print(x.item())
```
**Read later**
100+ Tensor operations, including transposing, indexing, slicing, mathematical operations, linear algebra, random numbers, etc., are described at http://pytorch.org/docs/torch.
-----
## Autograd: automatic differentiation
Central to all neural networks in PyTorch is the `autograd` package. Let’s first briefly visit this, and we will then go to training our first neural network.
The `autograd` package provides automatic differentiation for all operations on Tensors. It is a define-by-run framework, which means that your backprop is defined by how your code is run, and that every single iteration can be different.
Let us see this in more simple terms with some examples.
### Tensor
`torch.Tensor` is the central class of the package. If you set its attribute `.requires_grad` as `True`, it starts to track all operations on it. When you finish your computation you can call `.backward()` and have all the gradients computed automatically. The gradient for this tensor will be accumulated into `.grad` attribute.
To stop a tensor from tracking history, you can call `.detach()` to detach it from the computation history, and to prevent future computation from being tracked.
To prevent tracking history (and using memory), you can also wrap the code block in with `torch.no_grad()`:. This can be particularly helpful when evaluating a model because the model may have trainable parameters with `requires_grad=True`, but for which we don’t need the gradients.
There’s one more class which is very important for autograd implementation - a `Function`.
`Tensor` and `Function` are interconnected and build up an acyclic graph, that encodes a complete history of computation. Each tensor has a `.grad_fn` attribute that references a Function that has created the `Tensor` (except for Tensors created by the user - their `grad_fn is None`).
If you want to compute the derivatives, you can call `.backward()` on a `Tensor`. If `Tensor` is a scalar (i.e. it holds a one element data), you don’t need to specify any arguments to `backward()`, however if it has more elements, you need to specify a `gradient` argument that is a tensor of matching shape.
```
import torch
```
Create a tensor and set `requires_grad=True` to track computation with it.
```
x = torch.ones(2, 2, requires_grad=True)
print(x)
```
Do an operation of tensor:
```
y = x + 2
print(y)
```
`y` was created as a result of an operation, so it has a `grad_fn`.
```
print(y.grad_fn)
```
Do more operations on y
```
z = y * y * 3
out = z.mean()
print(z, out)
```
`.requires_grad_( ... )` changes an existing Tensor’s `requires_grad` flag in-place. The input flag defaults to `False` if not given.
```
a = torch.randn(2, 2)
a = ((a * 3) / (a - 1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b = (a * a).sum()
print(b.grad_fn)
```
### Gradients
Let’s backprop now because `out` contains a single scalar, `out.backward()` is equivalent to `out.backward(torch.tensor(1))`.
```
out.backward()
```
print gradients d(out)/dx
```
print(x.grad)
```
-----
## Neural Networks
Neural networks can be constructed using the `torch.nn` package.
Now that you had a glimpse of `autograd`, `nn` depends on `autograd` to define models and differentiate them. An `nn.Module` contains layers, and a method `forward(input)` that returns the `output`.
For example, look at this network that classifies digit images:
<img src="https://pytorch.org/tutorials/_images/mnist.png">
A typical training procedure for a neural network is as follows:
1. Define the neural network that has some learnable parameters (or weights)
2. Iterate over a dataset of inputs
3. Process input through the network
4. Compute the loss (how far is the output from being correct)
5. Propagate gradients back into the network’s parameters
6. Update the weights of the network, typically using a simple update rule: weight = weight - learning_rate * gradient
### Define Feed-Forward Network
Let’s define this feed-forward network:
```
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 5x5 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
```
You just have to define the `forward` function, and the `backward` function (where gradients are computed) is automatically defined for you using `autograd`. You can use any of the Tensor operations in the `forward` function.
The learnable parameters of a model are returned by net.parameters()
```
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
```
Let try a random 32x32 input Note: Expected input size to this net(LeNet) is 32x32. To use this net on MNIST dataset, please resize the images from the dataset to 32x32.
```
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
```
Zero the gradient buffers of all parameters and backprop with random gradients:
```
net.zero_grad()
out.backward(torch.randn(1, 10))
```
** Note **
`torch.nn` only supports mini-batches. The entire `torch.nn` package only supports inputs that are a mini-batch of samples, and not a single sample.
For example, `nn.Conv2d` will take in a 4D Tensor of nSamples x nChannels x Height x Width.
If you have a single sample, just use `input.unsqueeze(0)` to add a fake batch dimension.
At this point, we covered:
- Defining a neural network
- Processing inputs and calling backward
Still Left:
- Computing the loss
- Updating the weights of the network
### Loss Function
A loss function takes the (output, target) pair of inputs, and computes a value that estimates how far away the output is from the target.
There are several different loss functions under the `nn` package . A simple loss is: `nn.MSELoss` which computes the mean-squared error between the input and the target.
For example:
```
output = net(input)
target = torch.randn(10) # a dummy target, for example
target = target.view(1, -1) # make it the same shape as output
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
```
Now, if you follow loss in the backward direction, using its `.grad_fn` attribute, you will see a graph of computations that looks like this:
``
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> view -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss
``
So, when we call `loss.backward()`, the whole graph is differentiated w.r.t. the loss, and all Tensors in the graph that has `requires_grad=True` will have their `.grad` Tensor accumulated with the gradient.
For illustration, let us follow a few steps backward:
```
print(loss.grad_fn) # MSELoss
print(loss.grad_fn.next_functions[0][0]) # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU
```
### Backprop
To backpropagate the error all we have to do is to `loss.backward()`. You need to clear the existing gradients though, else gradients will be accumulated to existing gradients.
Now we shall call `loss.backward()`, and have a look at conv1’s bias gradients before and after the backward.
```
net.zero_grad() # zeroes the gradient buffers of all parameters
print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)
loss.backward()
print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)
```
### Update the weights
The simplest update rule used in practice is the Stochastic Gradient Descent (SGD):
`weight = weight - learning_rate * gradient`
We can implement this using simple python code:
```
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
```
However, as you use neural networks, you want to use various different update rules such as SGD, Nesterov-SGD, Adam, RMSProp, etc. To enable this, we built a small package: `torch.optim` that implements all these methods. Using it is very simple:
```
import torch.optim as optim
# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)
# in your training loop
optimizer.zero_grad() # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step() # does the update
```
-----
## Example: Linear Regression
This follows a simple example from https://github.com/yunjey/pytorch-tutorial.
```
import numpy as np
import matplotlib.pyplot as plt
```
Define model parameters
```
NUM_EPOCHS = 80
LEARNING_RATE = 0.001
```
Create random toy data
```
x_train = np.linspace(0, 1, num = 100, dtype = np.float32) \
.reshape(100, 1)
epsilon = np.random.normal(0, 1, size=100).astype('f') \
.reshape(100, 1)
w = 2.0
b = 0.5
y_train = w * x_train + b + epsilon
```
Plot toy data
```
plt.plot(x_train, y_train, 'ro', label='Toy data')
plt.show()
```
Define a linear model (y = x AT + b) for input/output
```
model = nn.Linear(x_train.shape[1], y_train.shape[1])
```
Define loss and optimizer
```
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=LEARNING_RATE)
```
Train the model
```
for epoch in range(NUM_EPOCHS):
# Convert numpy arrays to torch tensors
inputs = torch.from_numpy(x_train)
targets = torch.from_numpy(y_train)
# FORWARD PASS
outputs = model(inputs)
loss = criterion(outputs, targets)
# BACKWARD AND OPTIMIZE
# zero gradients (at the start of a minibatch)
optimizer.zero_grad()
# computes dloss/dx for every parameter x
loss.backward()
# optimizer.step performs a parameter update based on the current gradient
# (stored in .grad attribute of a parameter)
optimizer.step()
if (epoch+1) % 10 == 0:
print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, NUM_EPOCHS, loss.item()))
```
Plot the fitted line
```
predicted = model(torch.from_numpy(x_train)).detach().numpy()
plt.plot(x_train, y_train, 'ro', label='Original data')
plt.plot(x_train, predicted, label='Fitted line')
plt.legend()
plt.show()
```
Check parameters
```
print('w:', model.weight)
print('b:', model.bias)
```
And optionally save model checkpoint
```
# torch.save(model.state_dict(), 'model.ckpt')
```
| github_jupyter |
# Lecture 04: Random numbers and simulation
[Download on GitHub](https://github.com/NumEconCopenhagen/lectures-2021)
[<img src="https://mybinder.org/badge_logo.svg">](https://mybinder.org/v2/gh/NumEconCopenhagen/lectures-2021/master?urlpath=lab/tree/04/Random_numbers_and_simulation.ipynb)
1. [Exchange economy with many consumers](#Exchange-economy-with-many-consumers)
2. [Random numbers](#Random-numbers)
3. [Demand](#Demand)
4. [Interactive figures](#Interactive-figures)
5. [Equilibrium](#Equilibrium)
6. [Numerical integration by Monte Carlo](#Numerical-integration-by-Monte-Carlo)
7. [Load and save](#Load-and-save)
8. [Summary](#Summary)
You will learn how to use a random number generator with a seed and produce simulation results (**numpy.random**, **scipy.stats**), and calcuate the expected value of a random variable through Monte Carlo integration. You will learn how to save your results for later use (**pickle**). Finally, you will learn how to make your figures interactive (**ipywidgets**).
**Links:**
* [numpy.random](https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.random.html)
* [scipy.stats](https://docs.scipy.org/doc/scipy/reference/stats.html)
* [ipywidgets](https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20List.html)
* datacamp on [pickle](https://www.datacamp.com/community/tutorials/pickle-python-tutorial)
**Imports:** We now import all the modules, we need for this notebook. Importing everything in the beginning makes it more clear what modules the notebook relies on.
```
import math
import pickle
import numpy as np
from scipy.stats import norm # normal distribution
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import ipywidgets as widgets
```
<a id="Exchange-economy-with-many-consumers"></a>
# 1. Exchange economy with many consumers
Consider an **exchange economy** with
1. 2 goods, $(x_1,x_2)$
2. $N$ consumers indexed by $j \in \{1,2,\dots,N\}$
3. Preferences are Cobb-Douglas with uniformly *heterogenous* coefficients
$$
\begin{aligned}
u^{j}(x_{1},x_{2}) & = x_{1}^{\alpha_{j}}x_{2}^{1-\alpha_{j}}\\
& \,\,\,\alpha_{j}\sim\mathcal{U}(\underline{\mu},\overline{\mu})\\
& \,\,\,0<\underline{\mu}<\overline{\mu}<1
\end{aligned}
$$
4. Endowments are *homogenous* and given by
$$
\boldsymbol{e}^{j}=(e_{1}^{j},e_{2}^{j})=(k,1),\,k>0
$$
The implied **demand functions** are:
$$
\begin{aligned}
x_{1}^{\star j}(p_{1},p_{2},e^{j})&=&\alpha_{j}\frac{I}{p_{1}}=\alpha_{j}\frac{kp_{1}+p_{2}}{p_{1}} \\
x_{2}^{\star j}(p_{1},p_{2},e^{j})&=&(1-\alpha_{j})\frac{I}{p_{2}}=(1-\alpha_{j})\frac{kp_{1}+p_{2}}{p_{2}}
\end{aligned}
$$
The **equilibrium** for a random draw of $\alpha = \{\alpha_1,\alpha_2,\dots,\alpha_N\}$ is a set of **prices** $p_1$ and $p_2$ satifying:
$$
\begin{aligned}
x_1(p_1,p_2) = \sum_{j=1}^N x_{1}^{\star j}(p_{1},p_{2},e^{j}) &= \sum_{j=1}^N e_1^j = Nk \\
x_2(p_1,p_2) = \sum_{j=1}^N x_{2}^{\star j}(p_{1},p_{2},e^{j}) &= \sum_{j=1}^N e_2^j = N
\end{aligned}
$$
**Problem:** Solve for this equilibrium. But how do we handle the randomness? We need a random number generator (RNG).
**Warm-up**: Choose parameters and define demand functions.
```
# a. parameters
N = 1000
k = 2 # endowment
mu_low = 0.1 # lower bound on alpha
mu_high = 0.9 # upper bound on alpha
# b. demand functions
def demand_good_1_func(alpha,p1,p2,k):
I = k*p1+p2
return alpha*I/p1
def demand_good_2_func(alpha,p1,p2,k):
I = k*p1+p2
return (1-alpha)*I/p2
```
**Quizz:** take a quick [quizz](https://forms.office.com/Pages/ResponsePage.aspx?id=kX-So6HNlkaviYyfHO_6kckJrnVYqJlJgGf8Jm3FvY9UMFpSRTIzUlJKMkdFQlpIN1VZUE9EVTBaMSQlQCN0PWcu) regarding the demand functions.
<a id="Random-numbers"></a>
# 2. Random numbers
The two main approaches to generating random numbers are:
1. **Physical observations** of random processes (radioactive decay, atmospheric noise, roulette wheels, etc.)
2. **Algorithms** creating pseudo-random numbers
**Pseudo-random numbers** satisfy propoerties such that they are as good as random. It should be impossible (for all practical purposes) to calculate, or otherwise guess, from any given subsequence, any previous or future values in the sequence.
**More information:** See this [video](https://www.youtube.com/watch?v=C82JyCmtKWg&app=desktop#fauxfullscreen) by Infinite Series.
## 2.1 Simple example: Middle-square method
Proposed by **John von Neumann**:
1. Start with a $N$ digit number
2. Square the number
3. Pad the number with leading zeros making it a $2N$ digit number
4. Extract the middle $N$ digits (*your random number*)
5. Return to step 1 to generate one more
> **Pro:** Simple and easy to implement. Conceptually somewhat similar to more advanced methods (e.g. *Mersenne-Twister* used by *numpy*).
>
> **Con:** Cycles can be no longer than $8^N$ periods. Many repeating cycles are very short. Internal state is directly observable.
>
> **Conclusion:** Can not be used in practice.
**Code:** An implementation in Python for $N = 4$ digit random integers:
```
def rng(number,max_iter=100):
already_seen = [] # list of seen numbers
i = 0
while number not in already_seen and i < max_iter:
already_seen.append(number)
squared = number**2
padded = str(squared).zfill(8) # add leading zeros
number = int(padded[2:6]) # extract middle 4 numbers
print(f"square = {squared:8d}, padded = {padded} -> {number:4d}")
i += 1
```
A reasonable cycle:
```
rng(4653)
```
A short cycle:
```
rng(540)
```
No cycle at all:
```
rng(3792)
```
## 2.2 Numpy
Numpy provides various functions for drawing random numbers. We can, for example, draw random integers between 0 and 10000:
```
X = np.random.randint(0,10000,size=5)
print(X)
```
**Problem:** How can we reproduce our results the next time we open Python?
**Solution:** Use a seed! Choose the seed, and reset the random number generator:
```
print('set seed to 2000 and create numbers:')
np.random.seed(2000)
print(np.random.uniform(size=5))
print(np.random.uniform(size=5))
print('\nreset algorithm by stating the same seed again:')
np.random.seed(2000)
print(np.random.uniform(size=5))
```
> **Note:** The first and third draws above are exactly the same.
We can also **save and load the state** of the random number generator.
```
# a. save state
state = np.random.get_state()
# b. draw some random number
print('generate numbers from current state:')
print(np.random.uniform(size=5))
print(np.random.uniform(size=5))
# c. reset state
np.random.set_state(state)
# d. draw the same random numbers again
print('\ngenerate numbers from past state by reloading it:')
print(np.random.uniform(size=5))
print(np.random.uniform(size=5))
```
> **Note**: You should *only set the seed once* per program. Changing seed might brake randomness.
## 2.3 Different distributions
Draw random numbers from various distributions:
```
X = np.random.normal(loc=0,scale=1,size=10**6)
Y = np.random.beta(a=5,b=2,size=10**6)
Z = np.random.uniform(low=-2,high=2,size=10**6)
vec = np.array([-2.5,-2.0,-1.5,-1.0,-0.5,0,0.5,1.0,1.5,2,2.5])
prob = (np.linspace(-1,1,vec.size)+0.1)**2 # all positive numbers
prob /= np.sum(prob) # make them sum to one
K = np.random.choice(vec,size=10**6,p=prob)
```
Plot the various distributions:
```
fig = plt.figure(dpi=100)
ax = fig.add_subplot(1,1,1)
ax.hist(X,bins=100,density=True,alpha=0.5,label='normal') # alpha < 1 = transparent
ax.hist(Y,bins=100,density=True,alpha=0.5,label='beta')
ax.hist(Z,bins=100,density=True,alpha=0.5,label='uniform')
ax.hist(K,bins=100,density=True,alpha=0.5,label='choice')
ax.set_xlim([-3,3])
ax.legend(loc='upper left'); # note: the ; stops output from being printed
```
**Task:** Follow this [link](https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.random.html). Choose a distribution and add it to the figure above.
## 2.4 Analytical results
How close are our draws to a normal distribution?
```
from scipy.stats import norm
# a. create analytical distribution
loc_guess = 0.25
scale_guess = 0.75
# loc_guess, scale_guess = norm.fit(X)
F = norm(loc=loc_guess,scale=scale_guess)
rnd = F.rvs(5) # example: create 5 random draws from the distribution F
print(f'F pdf at 0.0: {F.pdf(0.0): 1.3f} \nF cdf at 0.0: {F.cdf(0.0): 1.3f}') # the object F has several useful functions available
# b. vector of x values
x_low = F.ppf(0.001) # x value where cdf is 0.001
x_high = F.ppf(0.999) # x value where cdf is 0.999
x = np.linspace(x_low,x_high,100)
# c. compare
fig = plt.figure(dpi=100)
ax = fig.add_subplot(1,1,1)
ax.plot(x,F.pdf(x),lw=2,label='estimated')
ax.hist(X,bins=100,density=True,histtype='stepfilled');
```
**Task:** Make the pdf fit the historgram.
## 2.5 Permutations
```
class dice_cup:
def __init__(self,ndice):
self.ndice = ndice
def roll(self):
self.dice = np.random.randint(1,7,size=self.ndice)
print(self.dice)
def shuffle(self):
np.random.shuffle(self.dice)
print(self.dice)
def roll_and_sum(self):
self.roll()
print(self.dice.sum())
my_dice_cup = dice_cup(4)
my_dice_cup.roll()
my_dice_cup.shuffle()
my_dice_cup.roll_and_sum()
```
**Task:** Add a method ``roll_and_sum()`` to the class above, which rolls and print the sum of the dice. Compare the value of your roll to your neighbor.
*(You can delete the pass statement when starting to code. It's there to inform Python that roll_and_sum() is well defined as Python cannot handle a totally codeless function)*
<a id="Demand"></a>
# 3. Demand
$$
x_1(p_1,p_2) = \sum_{j=1}^N x_{1}^{\star j}(p_{1},p_{2},e^{j}) = \alpha_{j}\frac{kp_{1}+p_{2}}{p_{1}}
$$
Find demand distribution and total demand:
```
def find_demand_good_1(alphas,p1,p2,k):
distr = demand_good_1_func(alphas,p1,p2,k) # Notice we are passing in arrays of alphas together with scalars! It works because of numpy broadcasting.
total = distr.sum()
return distr,total
```
Calculate for various prices:
```
# a. draw alphas
alphas = np.random.uniform(low=mu_low,high=mu_high,size=N)
# b. prices
p1_vec = [0.5,1,2,5]
p2 = 1
# c. demand
dists = np.empty((len(p1_vec),N))
totals = np.empty(len(p1_vec))
for i,p1 in enumerate(p1_vec):
dist,total = find_demand_good_1(alphas,p1,p2,k)
dists[i,:] = dist
totals[i] = total
```
Plot the results:
```
fig = plt.figure(figsize=(10,4))
ax_left = fig.add_subplot(1,2,1)
ax_left.set_title('Distributions of demand')
for i,p1 in enumerate(p1_vec):
ax_left.hist(dists[i],density=True,alpha=0.5,label=f'$p_1 = {p1}$')
ax_left.legend(loc='upper right')
ax_right = fig.add_subplot(1,2,2)
ax_right.set_title('Level of demand')
ax_right.grid(True)
ax_right.plot(p1_vec,totals)
```
<a id="Interactive-figures"></a>
# 4. Interactive figures
Create a function constructing a figure:
```
def interactive_figure(alphas,p1,p2,k):
# a. calculations
dist,_total = find_demand_good_1(alphas,p1,p2,k)
# b. figure
fig = plt.figure(dpi=100)
ax = fig.add_subplot(1,1,1)
ax.hist(dist,density=True)
ax.set_xlim([0,4]) # fixed x range
ax.set_ylim([0,0.8]) # fixed y range
```
**Case 1:** Make it interactive with a **slider**
```
widgets.interact(interactive_figure,
alphas=widgets.fixed(alphas),
p1=widgets.FloatSlider(description="$p_1$", min=0.1, max=5, step=0.05, value=2),
p2=widgets.fixed(p2),
k=widgets.fixed(k)
);
```
**Case 2:** Make it interactive with a **textbox**:
```
widgets.interact(interactive_figure,
alphas=widgets.fixed(alphas),
p1=widgets.FloatText(description="$p_1$", value=2),
p2=widgets.fixed(p2),
k=widgets.fixed(k)
);
```
**Case 3:** Make it interactive with a **dropdown menu**
```
widgets.interact(interactive_figure,
alphas=widgets.fixed(alphas),
p1=widgets.Dropdown(description="$p_1$", options=[0.5,1,1.5,2.0,2.5,3], value=2),
p2=widgets.fixed(p2),
k=widgets.fixed(k)
);
```
**Task:** Add a slider for \\(k\\) to the interactive figure below.
```
# change this code
widgets.interact(interactive_figure,
alphas=widgets.fixed(alphas),
p1=widgets.FloatSlider(description="$p_1$", min=0.1, max=5, step=0.05, value=2),
p2=widgets.fixed(p2),
k=widgets.fixed(k)
);
```
<a id="Equilibrium"></a>
# 5. Equilibrium
The equilibrium conditions (demand = supply) were:
$$
\begin{aligned}
\sum_{j=1}^N x_{1}^{\star j}(p_{1},p_{2},e^{j}) &= Nk \Leftrightarrow Z_1 \equiv \sum_{j=1}^N x_{1}^{\star j}(p_{1},p_{2},e^{j}) - Nk = 0 \\
\sum_{j=1}^N x_{2}^{\star j}(p_{1},p_{2},e^{j}) &= N \Leftrightarrow Z_2 \equiv \sum_{j=1}^N x_{2}^{\star j}(p_{1},p_{2},e^{j}) - N = 0
\end{aligned}
$$
**Idea:** Solve the first equation. The second is then satisfied due to Walras's law.
**Excess demand functions:**
```
def excess_demand_good_1_func(alphas,p1,p2,k):
# a. demand
demand = np.sum(demand_good_1_func(alphas,p1,p2,k))
# b. supply
supply = k*alphas.size
# c. excess demand
excess_demand = demand-supply
return excess_demand
def excess_demand_good_2_func(alphas,p1,p2,k):
# a. demand
demand = np.sum(demand_good_2_func(alphas,p1,p2,k))
# b. supply
supply = alphas.size
# c. excess demand
excess_demand = demand-supply
return excess_demand
```
**Algorithm:**
First choose a tolerance $\epsilon > 0$ and an adjustment factor $\kappa$, and a guess on $p_1 > 0$.
Then find the equilibrium price by:
1. Calculate excess demand $Z_1 = \sum_{j=1}^N x_{1}^{\star j}(p_{1},p_{2},e^{j}) - Nk$
2. If $|Z_1| < \epsilon $ stop
3. If $|Z_1| \geq \epsilon $ set $p_1 = p_1 + \kappa \cdot \frac{Z_1}{N}$
4. Return to step 1
That is, if if excess demand is positive and far from 0, then increase the price. If excess demand is negative and far from 0, decrease the price.
```
def find_equilibrium(alphas,p1,p2,k,kappa=0.5,eps=1e-8,maxiter=500):
t = 0
while True:
# a. step 1: excess demand
Z1 = excess_demand_good_1_func(alphas,p1,p2,k)
# b: step 2: stop?
if np.abs(Z1) < eps or t >= maxiter:
print(f'{t:3d}: p1 = {p1:12.8f} -> excess demand -> {Z1:14.8f}')
break
# c. step 3: update p1
p1 = p1 + kappa*Z1/alphas.size
# d. step 4: print only every 25th iteration using the modulus operator
if t < 5 or t%25 == 0:
print(f'{t:3d}: p1 = {p1:12.8f} -> excess demand -> {Z1:14.8f}')
elif t == 5:
print(' ...')
t += 1
return p1
```
Find the equilibrium price:
```
p1 = 1.4
p2 = 1
kappa = 0.1
eps = 1e-8
p1 = find_equilibrium(alphas,p1,p2,k,kappa=kappa,eps=eps)
```
**Check:** Ensure that excess demand of both goods are (almost) zero.
```
Z1 = excess_demand_good_1_func(alphas,p1,p2,k)
Z2 = excess_demand_good_2_func(alphas,p1,p2,k)
print(Z1,Z2)
assert np.abs(Z1) < eps
assert np.abs(Z2) < eps
```
**Quizz:** take a quick quizz on the algorithm [here](https://forms.office.com/Pages/ResponsePage.aspx?id=kX-So6HNlkaviYyfHO_6kckJrnVYqJlJgGf8Jm3FvY9UMjRVRkEwQTRGVVJPVzRDS0dIV1VJWjhJVyQlQCN0PWcu)
<a id="Numerical-integration-by-Monte-Carlo"></a>
# 6. Numerical integration by Monte Carlo
Numerical integration is the task of computing
$$
\mathbb{E}[g(x)] \text{ where } x \sim F
$$
and $F$ is a known probability distribution and $g$ is a function.
Relying on the law of large numbers we approximate this integral with
$$
\mathbb{E}[g(x)] \approx \frac{1}{N}\sum_{i=1}^{N} g(x_i)
$$
where $x_i$ is drawn from $F$ using a random number generator. This is also called **numerical integration by Monte Carlo**.
**Monte Carlo function:**
```
def g(x):
return (x-1)**2
def MC(N,g,F):
X = F.rvs(size=N) # rvs = draw N random values from F
return np.mean(g(X))
```
**Example** with a normal distribution:
```
N = 1000
mu = 0.1
sigma = 0.5
F = norm(loc=mu,scale=sigma)
print(MC(N,g,F))
```
Function for drawning \\( K \\) Monte Carlo samples:
```
def MC_sample(N,g,F,K):
results = np.empty(K)
for i in range(K):
results[i] = MC(N,g,F)
return results
```
The variance across Monte Carlo samples falls with larger $N$:
```
K = 1000
for N in [10**2,10**3,10**4,10**5]:
results = MC_sample(N,g,F,K)
print(f'N = {N:8d}: {results.mean():.6f} (std: {results.std():.4f})')
```
## 6.1 Advanced: Gauss-Hermite quadrature
**Problem:** Numerical integration by Monte Carlo is **slow**.
**Solution:** Use smarter integration formulas on the form
$$
\mathbb{E}[g(x)] \approx \sum_{i=1}^{n} w_ig(x_i)
$$
where $(x_i,w_i), \forall n \in \{1,2,\dots,N\}$, are called **quadrature nodes and weights** and are provided by some theoretical formula depending on the distribution of $x$.
**Example I, Normal:** If $x \sim \mathcal{N}(\mu,\sigma)$ then we can use [Gauss-Hermite quadrature](https://en.wikipedia.org/wiki/Gauss%E2%80%93Hermite_quadrature) as implemented below.
```
def gauss_hermite(n):
""" gauss-hermite nodes
Args:
n (int): number of points
Returns:
x (numpy.ndarray): nodes of length n
w (numpy.ndarray): weights of length n
"""
# a. calculations
i = np.arange(1,n)
a = np.sqrt(i/2)
CM = np.diag(a,1) + np.diag(a,-1)
L,V = np.linalg.eig(CM)
I = L.argsort()
V = V[:,I].T
# b. nodes and weights
x = L[I]
w = np.sqrt(math.pi)*V[:,0]**2
return x,w
def normal_gauss_hermite(sigma, n=7, mu=None, exp=False):
""" normal gauss-hermite nodes
Args:
sigma (double): standard deviation
n (int): number of points
mu (double,optinal): mean
exp (bool,optinal): take exp and correct mean (if not specified)
Returns:
x (numpy.ndarray): nodes of length n
w (numpy.ndarray): weights of length n
"""
if sigma == 0.0 or n == 1:
x = np.ones(n)
if mu is not None:
x += mu
w = np.ones(n)
return x,w
# a. GaussHermite
x,w = gauss_hermite(n)
x *= np.sqrt(2)*sigma
# b. log-normality
if exp:
if mu is None:
x = np.exp(x - 0.5*sigma**2)
else:
x = np.exp(x + mu)
else:
if mu is None:
x = x
else:
x = x + mu
w /= np.sqrt(math.pi)
return x,w
```
**Results:** Becuase the function is "nice", very few quadrature points are actually needed (*not generally true*).
```
for n in [1,2,3,5,7,9,11]:
x,w = normal_gauss_hermite(mu=mu,sigma=sigma,n=n)
result = np.sum(w*g(x))
print(f'n = {n:3d}: {result:.10f}')
```
**Example II, log-normal ([more info](https://en.wikipedia.org/wiki/Log-normal_distribution)):**
1. Let $\log x \sim \mathcal{N}(\mu,\sigma)$.
2. Gauss-Hermite quadrature nodes and weights can be used with the option `exp=True`.
3. To ensure $\mathbb{E}[x] = 1$ then $\mu = -0.5\sigma^2$.
```
z = np.random.normal(size=1_000_000,scale=sigma)
print('mean(x) when mu = 0')
x,w = normal_gauss_hermite(mu=0,sigma=sigma,n=7,exp=True)
print(f'MC: {np.mean(np.exp(z)):.4f}')
print(f'Gauss-Hermite: {np.sum(x*w):.4f}')
print('')
print('mean(x), mu = -0.5*sigma^2')
x,w = normal_gauss_hermite(sigma=sigma,n=7,exp=True)
print(f'MC: {np.mean(np.exp(z)-0.5*sigma**2):.4f}')
print(f'Gauss-Hermite: {np.sum(x*w):.4f}')
```
<a id="Load-and-save"></a>
# 7. Load and save
## 7.1 Pickle
A good allround method for loading and saving is to use **pickle**. Here is how to save:
```
# a. variables
my_dict = {'a':1,'b':2}
my_vec = np.array([1,2,3])
my_tupple = (1,4,2)
# b. put them in a dictionary
my_data = {}
my_data['my_dict'] = my_dict
my_data['my_vec'] = my_vec
my_data['my_tupple'] = my_tupple
# c. save the dictionary in a file
with open(f'data.p', 'wb') as f: # wb = write binary
pickle.dump(my_data, f)
```
Delete the variables:
```
del my_dict
del my_vec
del my_tupple
```
Load the data again:
```
# a. try
try:
print(my_tupple)
except:
print('my_vec does not exist')
# b. load
with open(f'data.p', 'rb') as f: # rb = read binary
data = pickle.load(f)
my_dict = data['my_dict']
my_vec = data['my_vec']
my_tupple = data['my_tupple']
# c. try again
print(my_vec)
print(my_tupple)
```
## 7.2 Saving with numpy
When only saving/loading **numpy arrays**, an alternative is to use ``np.savez`` (or ``np.savez_compressed``). This is typically faster than pickle.
Here is how to save some data:
```
my_data = {}
my_data['A'] = np.array([1,2,3])
my_data['B'] = np.zeros((5,8))
my_data['C'] = np.ones((7,3,8))
np.savez(f'data.npz', **my_data)
# '**' unpacks the dictionary
```
Here is how to load the data again:
```
# a. delete
del my_data
# a. load all
my_data = {}
with np.load(f'data.npz') as data_obj:
for key in data_obj.files:
my_data[key] = data_obj[key]
print(my_data['A'])
# b. load single array
X = np.load(f'data.npz')['A']
print(X)
```
<a id="Summary"></a>
# 8. Summary
**This lecture:** We have talked about:
1. numpy.random: Drawing (pseudo-)random numbers (seed, state, distributions)
2. scipy.stats: Using analytical random distributions (ppf, pdf, cdf, rvs)
3. ipywidgets: Making interactive figures
4. pickle and np.savez: Saving and loading data
The method you learned for finding the equilibrium can be used in a lot of models. For example, a simple method can be applied with multiple goods.
**Your work:** Before solving Problem Set 2 read through this notebook and play around with the code.
**Next lecture:** Workflow and debugging. Go through these guides beforehand:
1. [Installing Python and VSCode](https://numeconcopenhagen.netlify.com//guides/python-setup)
2. [Running Python in JupyterLab](https://numeconcopenhagen.netlify.com//guides/jupyterlab)
3. [Running Python in VSCode](https://numeconcopenhagen.netlify.com//guides/vscode-basics)
You must have installed **git** and have a **GitHub account!** (step 2 in [Installing Python and VSCode](https://numeconcopenhagen.netlify.com//guides/python-setup)).
**Finally:** You can begin to think about who you want to work together with for the group assignments. We will talk more about inaugural project next-time.
| github_jupyter |
# Problem Set 4.1.5—ANSWERS. How Important Are Resources in Generating Late 20th-Century Global Inequality?
## Do resources play an important role on a global scale in relative prosperity?
These notebook assignments are a required part of the course.
Collaborating on the notebooks is more than okay—it is encouraged! Seek help from a classmate or an instructor or a roommate or a passerby when you get stuck! (Explaining things is beneficial, too—the best way to solidify your knowledge of a subject is to explain it.)
But the work should be your own.
No cutting-&-pasting from others' notebooks, please! We want you to learn this stuff, and your fingers typing every keystroke is an important way of building muscle memory here.
In this notebook, you will attempt to assess whether and how much engrossment of natural resources by the global north since the start of the commercial revolution era in 1500 has played an important role in the rise of global inequality.
Let us get started!
# 1. Preliminaries
### A. Computing environment
First, we set up the computing environment with the libraries we need:
```
# 4.1.5.1.A.1. set up the computing environment: ensure that graphs
# appear inline in the notebook & not in extra windows:
%matplotlib inline
# 4.1.5.1.A.2. set up the computing environment: standard libraries...
import numpy as np
import pandas as pd
# 4.1.5.1.A.3. set up the computing environment: plotting library
import matplotlib as mpl
import matplotlib.pyplot as plt
```
### B. Our Picture of Global Economic History
First, set up our conception of global economic history:
```
# 4.1.5.1.B.1. year, population, income, ideas
# for the world as a whole:
long_run_growth_list = [
[-68000, 0.1, 1200, 379.47],
[-8000, 2.5, 1200, 1897.37],
[-6000, 7, 900, 2381.18],
[-3000, 15, 900, 3485.68],
[-1000, 50, 900, 6363.96],
[1, 170, 900, 11734.56],
[1500, 500, 900, 20124.61],
[1770, 750, 1100, 30124.74],
[1870, 1300, 1300, 46872.1],
[2020, 7600, 11842, 1032370.8]
]
long_run_growth_df = pd.DataFrame(
data=np.array(long_run_growth_list), columns = ['year', 'population',
'income_level', 'human_ideas']
)
long_run_growth_df['year'] = long_run_growth_df['year'].apply(np.int64)
initial_year = long_run_growth_df['year'][0:10]
span = []
g = []
h = []
n = []
for t in range(9):
span = span + [long_run_growth_df['year'][t+1]-long_run_growth_df['year'][t]]
h = h + [np.log(long_run_growth_df['human_ideas'][t+1]/long_run_growth_df['human_ideas'][t])/span[t]]
g = g + [np.log(long_run_growth_df['income_level'][t+1]/long_run_growth_df['income_level'][t])/span[t]]
n = n + [np.log(long_run_growth_df['population'][t+1]/long_run_growth_df['population'][t])/span[t]]
long_run_growth_df.set_index('year', inplace=True)
# finally, add a note to the end of each observation, reminding
# us of what was going on in human history back in each of the
# eras into which we have divided it
eras = ['at the dawn', 'agriculture & herding', 'proto-agrarian age',
'writing', 'axial age', 'dark & middle age slowdown', 'commercial revolution',
'industrial revolution', 'modern economic growth', 'whatever the 21st century brings']
long_run_growth_df['eras'] = eras
format_dict = {'year': '{d}', 'human_ideas': '{0:,.0f}',
'income_level': '${0:,.0f}', 'population': '{0:,.1f}'}
print('We now have our standard global economic history\neagle-eye view table in the computer:')
print(' ')
print('WORLD LEVELS')
long_run_growth_df.style.format(format_dict)
```
And now let's again calculate numbers we have seen many times before—growth rates in the different ages separated by humanity's watershed-crossings:
```
# 4.1.5.1.B.2.
data_list = np.array([span, h, g, n]).transpose()
long_run_growth_rates_df = pd.DataFrame(
data=data_list, columns = ['span', 'n', 'g', 'h'])
long_run_growth_rates_df['initial_year'] = initial_year
eras2 = eras[0:9]
long_run_growth_rates_df['era'] = eras2
format_dict = {'initial_year':'{0:.0f}', 'span': '{0:.0f}', 'h': '{0:,.3%}',
'g': '{0:,.2%}', 'n': '{0:,.2%}'}
print('We now have growth rates for each age:')
print(' ')
print('WORLD GROWTH RATES')
long_run_growth_rates_df.style.format(format_dict)
```
# 2. Global North & Global South
### A. Global North
Now let me provide you with another set of data analogous to those for the world as a whole. This set will be for the "global north" or "west"—that part of the world that dominated the Americas starting in the 1500s and then became much richer and more powerful than the rest since the start of the 1700s—consisting of northwest Europe, and then by 1770 of that plus the Atlantic seaboard of the Americas, adding on Australia and New Zealand by 1870, and now including those areas plus southwest and some of central Europe, plus Japan, South Korea, and Taiwan.
The data are:
```
# 4.1.5.2.A.1. for the "global north" or "west":
long_run_growth_list_global_north = [
[-68000, 0.00001, 1200, 379.47, 0.0001],
[-8000, 0.1, 1200, 1897.37, 0.0294],
[-6000, 0.2, 900, 2012.5, 0.0294],
[-3000, 0.5, 900, 3182, 0.0294],
[-1000, 2, 900, 6364.1, 0.0294],
[1, 5, 900, 10062.5, 0.0294],
[1500, 25, 1000, 25000.4, 0.0294],
[1770, 75, 1400, 42866.8, 0.0588],
[1870, 175, 2800, 106928.6, 0.0882],
[2020, 800, 50000, 3580637.4, 0.1147]
]
```
Note that there is an extra column: it will be "resources"—the share of the world's resources that is occupied/owned/conquered/exploited by the global north. For the world as a whole, it always had 100% of the world's resources. But as the global north expands, and as it engrosses ownership of resources beyond its borders, its share of the world's resources rises.
Then, with this list-of-lists, repeat what was done for the world as a whole by stuffing them into a dataframe, and doing the calculations of growth rates by era for the growth-rates dataframe:
```
# 4.1.5.2.A.2. create global-north levels dataframe
long_run_growth_global_north_df = pd.DataFrame(
data=np.array(long_run_growth_list_global_north), columns = ['year', 'population',
'income_level', 'human_ideas', 'resources']
)
long_run_growth_global_north_df['year'] = long_run_growth_global_north_df['year'].apply(np.int64)
# 4.1.5.2.A.3. do calculations for the global-north growth-rates dataframe
initial_year = long_run_growth_global_north_df['year'][0:10]
span = []
g = []
h = []
n = []
rho = []
for t in range(9):
span = span + [long_run_growth_global_north_df['year'][t+1]-long_run_growth_global_north_df['year'][t]]
h = h + [np.log(long_run_growth_global_north_df['human_ideas'][t+1]/long_run_growth_global_north_df['human_ideas'][t])/span[t]]
g = g + [np.log(long_run_growth_global_north_df['income_level'][t+1]/long_run_growth_global_north_df['income_level'][t])/span[t]]
n = n + [np.log(long_run_growth_global_north_df['population'][t+1]/long_run_growth_global_north_df['population'][t])/span[t]]
rho = rho + [np.log(long_run_growth_global_north_df['resources'][t+1]/long_run_growth_global_north_df['resources'][t])/span[t]]
long_run_growth_global_north_df.set_index('year', inplace=True)
# 4.1.5.2.A.4. finally, add a note to the end of each observation, reminding
# us of what was going on in human history back in each of the
# eras into which we have divided it
eras = ['at the dawn', 'agriculture & herding', 'proto-agrarian age',
'writing', 'axial age', 'dark & middle age slowdown', 'commercial revolution',
'industrial revolution', 'modern economic growth', 'whatever the 21st century brings']
long_run_growth_global_north_df['eras'] = eras
format_dict = {'year': '{d}', 'human_ideas': '{0:,.0f}',
'income_level': '${0:,.0f}', 'population': '{0:,.1f}','resources': '{0:,.3f}'}
print('We now have an analogous dataframe table\nfor the "global north"')
print(' ')
print('GLOBAL NORTH LEVELS')
long_run_growth_global_north_df.style.format(format_dict)
```
Now construct the global-north growth-rates dataframe:
```
# 4.1.5.2.A.5. create global-north growth-rates dataframe
data_list = np.array([span, h, g, n, rho]).transpose()
long_run_growth_rates_global_north_df = pd.DataFrame(
data=data_list, columns = ['span', 'h', 'g', 'n', 'rho'])
long_run_growth_rates_global_north_df['initial_year'] = initial_year
eras2 = eras[0:9]
long_run_growth_rates_global_north_df['era'] = eras2
format_dict = {'initial_year':'{0:.0f}', 'span': '{0:.0f}', 'h': '{0:,.3%}',
'g': '{0:,.2%}', 'n': '{0:,.2%}', 'n': '{0:,.2%}' , 'rho': '{0:,.3%}'}
print('GLOBAL NORTH GROWTH RATES')
long_run_growth_rates_global_north_df.style.format(format_dict)
```
### B. Global South
Now let me provide you with yet a third set of data, this time for the "global south" or "non-west"—that part of the world that was outside the charmed circle. It consists at the start of everything outside northwest Europe. As of 1770 we subtract the Atlantic seaboard of the Americas, we substract Australia and New Zealand by 1870, and by now we have subtraced those areas plus southwest and some of central Europe, plus Japan, South Korea, and Taiwan:
```
# 4.1.5.2.B.1. for the "global south" or "not-west":
long_run_growth_list_global_south = [
[-68000, 0.1, 1200, 379.47, 0.9999],
[-8000, 2.4, 1200, 1897.37, 0.971],
[-6000, 6.8, 900, 2395.3, 0.971],
[-3000, 14.5, 900, 3497.9, 0.971],
[-1000, 48, 900, 6364.1, 0.971],
[1, 165, 900, 11799.4, 0.971],
[1500, 475, 900, 20019.9, 0.971],
[1770, 675, 1070, 29386.7, 0.9412],
[1870, 1125, 1000, 36172.8, 0.9118],
[2020, 6800, 7700, 693805.9, 0.8853]
]
```
Now let's have you write a code cell to duplicate the work done in code cell # 4.1.5.2.A.2 above. Simply wherever you see the character string "north" replace it with "south", and then run the code cell:
```
# 4.1.5.2.B.2. create global-south levels dataframe
# this cell should be almost the same as # 4.1.5.2.A.2., with "south"
# replacing "north"
long_run_growth_global_south_df = pd.DataFrame(
data=np.array(long_run_growth_list_global_south), columns = ['year', 'population',
'income_level', 'human_ideas', 'resources']
)
long_run_growth_global_south_df['year'] = long_run_growth_global_south_df['year'].apply(np.int64)
```
The cell you just wrote should then mesh perfectly with the next two cells to create and print the global-south levels dataframe:
```
# 4.1.5.2.B.3. do calculations for the global-south growth-rates
# dataframe
initial_year = long_run_growth_global_south_df['year'][0:10]
span = []
g = []
h = []
n = []
rho = []
for t in range(9):
span = span + [long_run_growth_global_south_df['year'][t+1]-long_run_growth_global_south_df['year'][t]]
h = h + [np.log(long_run_growth_global_south_df['human_ideas'][t+1]/long_run_growth_global_south_df['human_ideas'][t])/span[t]]
g = g + [np.log(long_run_growth_global_south_df['income_level'][t+1]/long_run_growth_global_south_df['income_level'][t])/span[t]]
n = n + [np.log(long_run_growth_global_south_df['population'][t+1]/long_run_growth_global_south_df['population'][t])/span[t]]
rho = rho + [np.log(long_run_growth_global_south_df['resources'][t+1]/long_run_growth_global_south_df['resources'][t])/span[t]]
long_run_growth_global_south_df.set_index('year', inplace=True)
# 4.1.5.2.B.4. add legend notes & print the dataframe
#
# finally, add a note to the end of each observation, reminding
# us of what was going on in human history back in each of the
# eras into which we have divided it
eras = ['at the dawn', 'agriculture & herding', 'proto-agrarian age',
'writing', 'axial age', 'dark & middle age slowdown', 'commercial revolution',
'industrial revolution', 'modern economic growth', 'whatever the 21st century brings']
long_run_growth_global_south_df['eras'] = eras
format_dict = {'year': '{d}', 'human_ideas': '{0:,.0f}',
'income_level': '${0:,.0f}', 'population': '{0:,.1f}', 'resources': '{0:,.3f}'}
print('And if everything went well you now have an\nanalogous "global south" table:')
print(' ')
print('GLOBAL SOUTH LEVELS')
long_run_growth_global_south_df.style.format(format_dict)
```
Did it work? Everything should have run, and should have produced something like:
<img src="https://delong.typepad.com/img/very-long-run-growth-global-south-levels-python-2020-09-23.png" width="500" />
If not, recheck your work. And if you are still stuck, call someone for help...
Now construct the global-south growth-rates dataframe, duplicating what was in the above code cell # 4.1.5.2.A.5, once again simply by taking the code and replacing the character string "north" by "south" every place that it appears:
```
# 4.1.5.2.B.5. create global-south growth-rates dataframe
# this cell is analogous to # 4.1.5.2.A.5., with "south"
# replacing "north"
data_list = np.array([span, n, g, h, rho]).transpose()
long_run_growth_rates_global_south_df = pd.DataFrame(
data=data_list, columns = ['span', 'n', 'g', 'h', 'rho'])
long_run_growth_rates_global_south_df['initial_year'] = initial_year
eras2 = eras[0:9]
long_run_growth_rates_global_south_df['era'] = eras2
format_dict = {'initial_year':'{0:.0f}', 'span': '{0:.0f}', 'h': '{0:,.3%}',
'g': '{0:,.2%}', 'n': '{0:,.2%}', 'n': '{0:,.2%}' , 'rho': '{0:,.3%}'}
print('GLOBAL SOUTH GROWTH RATES')
long_run_growth_rates_global_south_df.style.format(format_dict)
```
And, once again, if things did not work and did not produce a table analogous to the "GLOBAL NORTH GROWTH RATES" table above, go back, try to figure out what went wrong. And correct your work.
## 3. North-South Comparisons
Now let us calculate the differences in growth rates in labor productivity, incomes, and living standards between the global north and the global south:
```
# 4.1.5.3.1. "differences" dataframe
g_north_south_diff = pd.DataFrame(long_run_growth_rates_global_north_df[['g', 'n', 'h', 'rho']] - long_run_growth_rates_global_south_df[['g', 'n', 'h', 'rho']])
g_north_south_diff['era'] = ['-68000 to -8000', '-8000 to -6000', '-8000 to -3000', '-3000 to -1000', '-1000 to 1', '1-1500', '1500-1770', '1770-1870', '1870-2020']
g_north_south_diff['span'] = long_run_growth_rates_global_north_df['span']
g_north_south_diff['initial_year'] = long_run_growth_rates_global_north_df['initial_year']
format_dict = {'initial_year':'{0:.0f}', 'span': '{0:.0f}', 'h': '{0:,.3%}',
'g': '{0:,.2%}', 'n': '{0:,.2%}', 'n': '{0:,.2%}' , 'rho': '{0:,.3%}'}
print('GROWTH RATE NORTH-SOUTH DIFFERENCES')
g_north_south_diff.style.format(format_dict)
```
### A. Population
Note that the population of the global north grows for two reasons: (1) the populations of economies already in it expand in its own territories and then in other territories it conquers, occupies, and settles; and (2) new economies join it. In 1500 the civilization we now call the "global north" was pretty much restricted to the countries that touched or were just across the sea from what is now Belgium and Holland—and of what are now France and Germany, only northern France and nortwestern Germany counted. Now it encompasses all of western and most of central Europe, North America, and Asia's Pacific Rim plus Australia and New Zealand.
### B. Resources
Note that the natural resources controlled by the global north grew both because the global north expanded in area and becomes its citizens acquired—well, largely stole—resources outside of the global north, many of which global north citizens control to this day.
### C. Productivity
We first see the global north acquiring a (very small) edge in productivity, income per capita, and living standard growth over the period 1 to 1500. Northwest Europe in 1500 is an an up-phase of the Malthusian cycle: it lost 1/4 of its population to the Black Plague of 1346-8, and subsequent plagues kept its population from recovering, leaving it with a favorable land-labor ratio and a high level of labor productivity. It also had a small edge in technology: sails and guns and clocks, mostly.
Then, after 1500, in the three subsequent Commercial Revolution, Industrial Revolution, and 20th-century Modern Economic Growth Ages, the global north's productivity and income edge surges: useful ideas are invented and deployed in the global north faster than they diffuse across the global south, resources are engrossed by the global north through settlement, expansion, conquest, theft, purchase, and investment. And, until the demographic transition to something close to zero population growth in the global north becomes well established, its population share of the world grows as well.
### D. Not in the Model
The numbers in the "differences" table above understate the magnitude of the true historical differences between the global north and south for three reasons not in the model that seem to me to be obvious, and perhaps for other non-obvious reasons as well.
First, the global north did not just gain growth advantage from the workings of the global economy and its imperialism after 1500. It gained a current consumption advantage as well, for a component of production and income earned in the global south was transferred to the global north.
Second, the model above has no place in it for the people killed, enslaved, and enserfed.
Third, the model has no place in it for differences and changes in the terms-of-trade between global north and global south. Put broadly, The terms of trade of market exchange favored the global north from 1500 to 1770, then favored the global south from 1770 to 1860, then favored the global south as far as manufactured and the global north as far as resource products were concerned from 1860 to 1950, and, last, have favored the global north—with a very important exception of oil—since 1950.
Plus imperialism and exploitation were profoundly uneven. They share of global south resources in Asia conquered by the global north was small. But if you happen to live on an island in the East Indies and the Portuguese or Dutch arrived, the likelihood was that they took everything that was not nailed down—and then exploited and diverted the income from a lot that was.
### E. Questions:
Now let me ask you some questions that you can then do calculations to answer:
#### 1. Productivity Multiple—a Worked Example
What relative multiple of global-south average income and productivity do we guess global-north average income and productivity was in 1500? (To answer this question, reach back into your dataframes and do a calculation to pull out and then print the answer, like this:
```
# 4.1.5.3.E.1. global-north income multiple in 1500: worked example
# worked example: simply divide the income levels
income_mult_1500 = (long_run_growth_global_north_df['income_level'][1500] /
long_run_growth_global_south_df['income_level'][1500])
print("The global north's relative income multiple in 1500 =", income_mult_1500)
```
<img src="https://www.evernote.com/l/AAFrudTDb4FHb7W-HVn11Ckh6y4cuvoZwB4B/image.png" width="400" />
<img src="https://www.evernote.com/l/AAGKSCQruIxEzZnpshLB4ExU16sIc1v4W2AB/image.png" width="400" />
#### 2. Income Multiple
What relative multiple of global-south average income and productivity do we estimate global-north average income and productivity is today?
```
## 4.1.5.3.E.2. global-north income multiple today
# notice that this is simply # 3.2.C.5.a. but
# with "2020" replacing "1500"; simply divide
# the income levels
income_mult_2020 = (long_run_growth_global_north_df['income_level'][2020] /
long_run_growth_global_south_df['income_level'][2020])
print("The global north's relative income multiple today =", income_mult_2020)
```
<img src="https://www.evernote.com/l/AAEWDzsvIoVN6Yo5qitUwRF-Wfad9p1ExaAB/image.png" width="400" />
#### 3. Income Growth Multiple
How much greater has been the average annual growth rate in income and productivity in the global north than the global south since 1500?
```
# 4.1.5.3.E.3. income growth-rate difference since 1500?
# simply take a weighted average of growth rates over the
# three periods 1500-1770, 1770-1870, 1870-2020
income_growth_rate_diff_1500_2020 = (
g_north_south_diff['g'][6]*g_north_south_diff['span'][6]
+ g_north_south_diff['g'][7]*g_north_south_diff['span'][7]
+ g_north_south_diff['g'][8]*g_north_south_diff['span'][8]
)/(
g_north_south_diff['span'][6]+
g_north_south_diff['span'][7]+
g_north_south_diff['span'][8]
)
print("The difference in annual average income growth rates since 1500 =",
income_growth_rate_diff_1500_2020)
```
<img src="https://www.evernote.com/l/AAEDcK-KrUdPTbl-cJMvgphGMbGGSyn0Yh4B/image.png" width="400" />
#### 4. Growth Rate Differentials
How much greater has been the growth rate of the resources available to the global north than to the global south since 1500? And what have been the differences in population growth rates? And in ideas-stock growth rates?
```
# 4.1.5.3.E.4. resource growth-rate difference since 1500?
# notice that this is simply simply # 4.1.5.3.E.3. with
# "rho" replacing "g"; simply take a weighted average
resource_growth_rate_diff_1500_2020 = (g_north_south_diff['rho'][6]*g_north_south_diff['span'][6]
+ g_north_south_diff['rho'][7]*g_north_south_diff['span'][7]
+ g_north_south_diff['rho'][8]*g_north_south_diff['span'][8]
)/(g_north_south_diff['span'][6]+g_north_south_diff['span'][7]+g_north_south_diff['span'][8])
print("The difference in annual average resource-availability growth rates since 1500 =",
resource_growth_rate_diff_1500_2020)
```
<img src="https://www.evernote.com/l/AAH7HpHwIFBKA5xsw9Cydk2NbO_msgU53H0B/image.png" width="400" />
```
# 4.1.5.3.E.4.a. n growth-rate difference since 1500?
population_growth_rate_diff_1500_2020 = (g_north_south_diff['n'][6]*g_north_south_diff['span'][6]
+ g_north_south_diff['n'][7]*g_north_south_diff['span'][7]
+ g_north_south_diff['n'][8]*g_north_south_diff['span'][8]
)/(g_north_south_diff['span'][6]+g_north_south_diff['span'][7]+g_north_south_diff['span'][8])
print("The difference in annual average population growth rates since 1500 =",
population_growth_rate_diff_1500_2020)
# 4.1.5.3.E.4.b. h growth-rate difference since 1500?
ideas_growth_rate_diff_1500_2020 = (g_north_south_diff['h'][6]*g_north_south_diff['span'][6]
+ g_north_south_diff['h'][7]*g_north_south_diff['span'][7]
+ g_north_south_diff['h'][8]*g_north_south_diff['span'][8]
)/(g_north_south_diff['span'][6]+g_north_south_diff['span'][7]+g_north_south_diff['span'][8])
print("The difference in annual average ideas growth rates since 1500 =",
ideas_growth_rate_diff_1500_2020)
```
#### 5. Counterfactuals...
And now we get to the point of the whole exercise.
Recall that our very crude growth framework assumes that ideas are twice as salient in boosting productivity and income than resources per capita are at retarding it—that while a 1% increase in the value of the ideas stock boosts income and productivity by 1%, other things being equal—_ceteris paribus_, if we drop into Latin, and _cet. par._ if we drop into Latin and abbreviate, as John Maynard Keynes's teachers back around 1900 were wont to do—an increase in resources per capita by 1% increased income and productivity by only 0.5%. (And, of course, this runs in reverse as well for resource scarcity per capita or for ideas lack depressing income and productivity.)
In equations, the relationship between the rates of labor-efficiency growth g, ideas growth h, resource-stock growth ⍴, and population and labor-force growth n is:
>$ g = h + \frac{\rho - n}{2} $
Suppose that the global north had not engrossed more of the world's resources since 1500—that the 850 million people in today's global north were still drawing on the 2.71% of the global resource base that northwest European civilization drew on back in 1500.
What does our model then say would be the difference in income and productivity growth rates between the global north and south since 1500—the number that you calculated (or should have calculated) as 0.00339 (that is, 0.34%/year)?
```
# 4.1.5.3.E.5. counterfactual stable-resources income differential growth rate since 1500
# the first paragraph reminds you of this equation:
# g = h + (⍴-n)/2
#
# compare historical with a counterfactual in which
# resources open to the global north do not increase:
# .0034 = .0027 + (.0028 - .0015)/2 <--historical
# .???? = .0027 + (.0000 - .0015)/2 <--counterfactual
resource_stability_counterfactual_income_growth_rate_diff_1500_2020 = (
income_growth_rate_diff_1500_2020 -
resource_growth_rate_diff_1500_2020/2)
print("RESOURCE STABILITY COUNTERFACTUAL")
print("The difference in annual average income growth rates since 1500 would have been =",
resource_stability_counterfactual_income_growth_rate_diff_1500_2020)
```
#### 6. Relative Productivity in the Counterfactual
Under that resource-stability counterfactual, what relative multiple of global-south average income and productivity do we guess about the analogue to the answer to the 6.49—what global-north average income and productivity as a multiple of global south would have been today, holding all variable in our model other than resource access and availability constant?
```
# 4.1.5.3.E.6. resource-stability counterfactual; current global-north income multiple
#
# with something growing at 0.2%/year for 500 years
# Y_final = Y_inital * np.exp(g*t)
resource_stability_counterfactual_income_diff_2020 = (income_mult_1500
* np.exp(
resource_stability_counterfactual_income_growth_rate_diff_1500_2020
* (g_north_south_diff['span'][6]+g_north_south_diff['span'][7]+g_north_south_diff['span'][8])
))
print("RESOURCE STABILITY COUNTERFACTUAL")
print("Global north average income today as a multiple of global south would have been =",
resource_stability_counterfactual_income_diff_2020)
```
$ Y_{cfratio2020} = Y_{ratio1500} * e^{g_{cf}t} $
$ g_{cf} = g + \frac{1}{2} \Delta \rho = 0.002 $
$ t = 520 $
$ Y_{ratio1500} = 1.11 $
If all has gone well you got an answer of 6.49—the actual multiple of global north income today relative to global south—and an answer of 3.14 for question—what that multiple would have been had the 850 million people today in the global north not owned and controlled immense proportions of the world's resources outside global-north civilization's original northwest European homelands clustered around what are now Belgium and Holland.
#### 7. Explain Your Calculations...
Tell us, in the markdown cell immediately below, your thoughts as to the relevance or non-relevance of these two numbers—6.49 and 3.14—for what would be the "right" global political-economy order of resource ownership and control going forward into the 21st century. 500-1000 words, please. We are looking for you to set out what you think the best definition of "right" is here, why it is the best definition, whether these two numbers do or do not have a significant role to play in answering that question of the "right" order, and then how these two numbers play that role:
<span style="color:blue;">**ANSWER TO 7**: [500-1000 words of answer replace this text and go here...]</span>
## 4. Done!
Print your finished notebook to pdf, and upload it as an answer on the assignment page. URL:
But, first, run this last summary code cell below unchanged:
```
# calculations summary
print("The global north's relative income multiple in 1500 =", income_mult_1500)
print("The global north's relative income multiple today =", income_mult_2020)
print("The difference in annual average income growth rates since 1500 =",
income_growth_rate_diff_1500_2020)
print("The difference in annual average resource-availability growth rates since 1500 =",
resource_growth_rate_diff_1500_2020)
print("The difference in annual average population growth rates since 1500 =",
population_growth_rate_diff_1500_2020)
print("The difference in annual average ideas growth rates since 1500 =",
ideas_growth_rate_diff_1500_2020)
print("The difference in annual average income growth rates since 1500 would have been =",
resource_stability_counterfactual_income_growth_rate_diff_1500_2020)
print("Global north average income today as a multiple of global south would have been =",
resource_stability_counterfactual_income_diff_2020)
```
## 5. Appendix Programming Dos and Don'ts...
### A Running List...
1. **Do** restart your kernel and run cells up to your current working point every fifteen minutes or so. Yes, it takes a little time. But if you don't, sooner or later the machine's namespace will get confused, and then you will get confused about the state of the machine's namespace, and by assuming things about it that are false you will lose hours and hours...
2. **Do** reload the page when restarting the kernel does not seem to do the job...
3. **Do** edit code cells by copying them below your current version and then working on the copy: when you break everything in the current cell (as you will), you can then go back to the old cell and start fresh...
4. **Do** exercise agile development practices: if there is a line of code that you have not tested, test it. The best way to test is to ask the machine to echo back to you the thing you have just created in its namespace to make sure that it is what you want it to be. Only after you are **certain** that your namespace contains what you think it does should you write the next line of code. And then you should immediately test it...
5. **Do** take screenshots of your error messages...
6. **Do** google your error messages: Ms. Google is your best friend here...
7. **Do not** confuse assignment ("=") and test for equality ("=="). In general, if there is an "if" anywhere nearby, you should be testing for equality. If there is not, you should be assignment a variable in your namespace to a value. **Do** curse the mathematicians 500 years ago who did not realize that in the twenty-first century it would be very convenient if we had different and not confusable symbols for equals-as-assignment and equals-as-test...
----
**Thanks to**: Rachel Grossberg, Christopher Hench, Meghana Krishnakumer, Seth Lloyd, Ronald Walker...
----
## <font color="880000"> Resources and Relative Prosperity on a Global Scale </font>
<img src="https://tinyurl.com/20190119a-delong" width="300" style="float:right" />
### <font color="000088">Catch Our Breath—Further Notes:</font>
<br clear="all" />
----
----
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.