text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|

```
#from IPython.display import HTML, display
#display(HTML("<table><tr><td><img src='data/rings2.png' width='620'></td><td><img src='data/sports.png' width='300'></td></tr></table>"))
```
### Prep work
```
#library should be installed already
#!pip install cufflinks ipywidgets
```
Run the next cells to load libaries and pre-defined functions:
```
!wget https://raw.githubusercontent.com/callysto/hackathon/master/Group3_Olympics/helper_code/olympics.py -P helper_code -nc
import pandas as pd
import cufflinks as cf
cf.go_offline()
colors20 = ['#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0',
'#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8',
'#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', '#ffffff', '#000000']
#to enable plotting in colab
def enable_plotly_in_cell():
import IPython
from plotly.offline import init_notebook_mode
display(IPython.core.display.HTML('''
<script src="/static/components/requirejs/require.js"></script>
'''))
init_notebook_mode(connected=False)
get_ipython().events.register('pre_run_cell', enable_plotly_in_cell)
#helper code
from helper_code.olympics import *
```
# Group goal
Go through the analysis below, work on challenges.
**Extra challenge**:
Is there anything else interesting you can find and visualize for these data?
### Getting data
Olympics dataset was downloaded from [Kaggle](https://www.kaggle.com/heesoo37/120-years-of-olympic-history-athletes-and-results/data#athlete_events.csv)
**Kaggle** is the online community of data scientists and machine learners and the most well known competition platform for predictive modeling and analytics.
```
#reading from cloud object storage
olympics_url ="https://swift-yeg.cloud.cybera.ca:8080/v1/AUTH_d22d1e3f28be45209ba8f660295c84cf/hackaton/olympics.csv"
olympics =pd.read_csv(olympics_url)
#how many rows and colums does the dataframe have?
olympics.shape
#what are the column names?
olympics.columns
```
Here is the column description from Kaggle:
**ID** - Unique number for each athlete
**Name** - Athlete's name
**Sex** - M or F
**Age** - Integer
**Height** - In centimeters
**Weight** - In kilograms
**Team** - Team name
**NOC** - National Olympic Committee 3-letter code
**Games** - Year and season
**Year** - Integer
**Season** - Summer or Winter
**City** - Host city
**Sport** - Sport
**Event** - Event
**Medal** - Gold, Silver, Bronze, or NA
**region** - Country
```
#display first 5 rows to explore what the data looks like
olympics.head()
```
### Number of participants by year
```
#lets group by year and calculate number of rows for every group
athletes_by_year = olympics.groupby(["Year"]).size()
#create additional column "count" to store the number of athlets
athletes_by_year = athletes_by_year.reset_index(name='count')
#print first 5 years and number of athletes
athletes_by_year.head()
#what is the maximum number of participants:
athletes_by_year.max()
#creating a line graph
athletes_by_year.set_index("Year").iplot(xTitle="Year",yTitle="Number of participants")
```
### Challenge
Find the minimum number of Olympics participants using `min()` function
Experiment with different kinds of plots:
- Try creating new cell by copying the call above and change `iplot()` to `iplot(kind="bar")` or `iplot(kind="barh")` or `.iplot(kind="area",fill=True)`. Which plot helps you better understand the data?
- What interesting can you notice on this plot? What do you think happened between the years 1992 and 1994?
### Number of participants by year and by season
```
#in this case we call function "get_counts_by_group()"
athletes_by_season = get_counts_by_group(olympics, "Season")
athletes_by_season.head()
athletes_by_season.iplot(kind="bar", barmode="stack",xTitle="Year",yTitle="Number of participants")
```
Looks like Summer and Winter Olympics were run in the same year before 1994!
Let's find the year with the most participants in Summer season:
- we will do this using `sort_values()` function:
```
athletes_by_season.sort_values("Summer", ascending = False).head(10)
```
### Challenge
- Using the example above, create new cell(s) and try to find number of participants by year and by sex (using "Sex" column)
- Which year had the most female participants?
### Number of medals by country by sport
```
#we will keep only the rows for athletes who got medals
medals = olympics.dropna(subset=["Medal"])
#lets select only Winter season
medals_winter = medals[medals["Season"]=="Winter"]
#grouping by year and country and calculating the number of rows
medals_by_region = get_counts_by_group(medals_winter, "region")
#displaying top 5 rows
medals_by_region.head()
#we will display data only for some countries. There are too many of them, it will get too messy if we plot all
medals_subset = medals_by_region[["Canada","Russia","USA","Norway","Japan","China"]]
medals_subset.iplot(kind="area",fill=True,xTitle="Year",yTitle="Number of medals")
```
### Challenge
- Using the example above, create new code cell(s) and display number of medals for the Summer Olympics
- Is Canada more successful at winning medals in Winter or in Summer Olympics?
- What was the year when Canada got the most medals in the Winter Olympics? in the Summer Olympics?
### Extra:
We can choose country using interactive input
**Note**: if you enter a country that doesn't exist in the data set, the code will give an error. Restart the cell to start over.
```
print("Enter country: ")
country = input()
medals_subset1 = medals_by_region[country]
medals_subset1.iplot(kind="area",fill=True,xTitle="Year",yTitle="Number of medals")
```
### For Summer Olympics in 1984, how many gold/silver/bronze medals in total and by sport
```
# subset by specific year, county and season
medals_by_country = medals[(medals["Season"]=="Summer")
&(medals["Year"]==1984)
&(medals["region"]=="Canada")]
#count number of rows
medals_by_kind = medals_by_country.groupby(["Medal"]).size()
#create additional column "count" to store the number of athlets
medals_by_kind = medals_by_kind.reset_index(name='count')
medals_by_kind
#using new kind of plot - Pie chart, note it needs labels and values set so specific columns
medals_by_kind.iplot(kind="pie", labels="Medal",values="count")
# calling function to get medal counts by sport
medal_by_sport = get_counts_by_medal(medals_by_country)
medal_by_sport
#note: barmode ='stack' means bars stack on top of each other
medal_by_sport.iplot(kind = "bar", barmode = "stack",xTitle="Sport",yTitle="Count")
```
### Challenge
- Using the example above, create new cell(s) and analyze the number of medals for Russia in Summer 1980
- What was the location of these Olympic games?
## Extra
On the plot below we can compare the number of participants versus number of medals, feel free to play with the
different years, countries, and seasons.
```
summary = get_participation_counts(olympics ,year=1984, season="Summer", country="Canada")
summary.iplot(kind= "bar", barmode="stack",xTitle="Year",yTitle="Number of participants")
```

| github_jupyter |
```
from __future__ import print_function
from tensorflow.keras.layers import Dense, Conv2D, BatchNormalization, Activation
from tensorflow.keras.layers import AveragePooling2D, Input, Flatten, MaxPooling2D
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.regularizers import l2
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.datasets import cifar10
import tensorflow as tf
import numpy as np
import os
# Training parameters
batch_size = 32 # orig paper trained all networks with batch_size=128
epochs = 2
data_augmentation = True
num_classes = 10
# Subtracting pixel mean improves accuracy
subtract_pixel_mean = True
n = 3
version = 1
depth = n * 6 + 2
# Model name, depth and version
model_type = 'ResNet%dv%d' % (depth, version)
# Load the CIFAR10 data.
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# Input image dimensions.
input_shape = x_train.shape[1:]
# Normalize data.
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# If subtract pixel mean is enabled
if subtract_pixel_mean:
x_train_mean = np.mean(x_train, axis=0)
x_train -= x_train_mean
x_test -= x_train_mean
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print('y_train shape:', y_train.shape)
# Convert class vectors to binary class matrices.
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)
```
# Your model
```
model = Sequential()
model.add(Conv2D(16, (3, 3), activation='relu', padding='same', input_shape=(32, 32, 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dense(10, activation='softmax'))
# compile model
model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(x_test, y_test),
shuffle=True)
# Score trained model.
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])
```
# Resnet model
```
def resnet_layer(inputs,
num_filters=16,
kernel_size=3,
strides=1,
activation='relu',
batch_normalization=True,
conv_first=True):
"""2D Convolution-Batch Normalization-Activation stack builder
# Arguments
inputs (tensor): input tensor from input image or previous layer
num_filters (int): Conv2D number of filters
kernel_size (int): Conv2D square kernel dimensions
strides (int): Conv2D square stride dimensions
activation (string): activation name
batch_normalization (bool): whether to include batch normalization
conv_first (bool): conv-bn-activation (True) or
bn-activation-conv (False)
# Returns
x (tensor): tensor as input to the next layer
"""
conv = Conv2D(num_filters,
kernel_size=kernel_size,
strides=strides,
padding='same',
kernel_initializer='he_normal',
kernel_regularizer=l2(1e-4))
x = inputs
if conv_first:
x = conv(x)
if batch_normalization:
x = BatchNormalization()(x)
if activation is not None:
x = Activation(activation)(x)
else:
if batch_normalization:
x = BatchNormalization()(x)
if activation is not None:
x = Activation(activation)(x)
x = conv(x)
return x
def resnet_v1(input_shape, depth, num_classes=10):
"""ResNet Version 1 Model builder [a]
Stacks of 2 x (3 x 3) Conv2D-BN-ReLU
Last ReLU is after the shortcut connection.
At the beginning of each stage, the feature map size is halved (downsampled)
by a convolutional layer with strides=2, while the number of filters is
doubled. Within each stage, the layers have the same number filters and the
same number of filters.
Features maps sizes:
stage 0: 32x32, 16
stage 1: 16x16, 32
stage 2: 8x8, 64
The Number of parameters is approx the same as Table 6 of [a]:
ResNet20 0.27M
ResNet32 0.46M
ResNet44 0.66M
ResNet56 0.85M
ResNet110 1.7M
# Arguments
input_shape (tensor): shape of input image tensor
depth (int): number of core convolutional layers
num_classes (int): number of classes (CIFAR10 has 10)
# Returns
model (Model): Keras model instance
"""
if (depth - 2) % 6 != 0:
raise ValueError('depth should be 6n+2 (eg 20, 32, 44 in [a])')
# Start model definition.
num_filters = 16
num_res_blocks = int((depth - 2) / 6)
inputs = Input(shape=input_shape)
x = resnet_layer(inputs=inputs)
# Instantiate the stack of residual units
for stack in range(3):
for res_block in range(num_res_blocks):
strides = 1
if stack > 0 and res_block == 0: # first layer but not first stack
strides = 2 # downsample
y = resnet_layer(inputs=x,
num_filters=num_filters,
strides=strides)
y = resnet_layer(inputs=y,
num_filters=num_filters,
activation=None)
if stack > 0 and res_block == 0: # first layer but not first stack
# linear projection residual shortcut connection to match
# changed dims
x = resnet_layer(inputs=x,
num_filters=num_filters,
kernel_size=1,
strides=strides,
activation=None,
batch_normalization=False)
x = tf.keras.layers.add([x, y])
x = Activation('relu')(x)
num_filters *= 2
# Add classifier on top.
# v1 does not use BN after last shortcut connection-ReLU
x = AveragePooling2D(pool_size=8)(x)
y = Flatten()(x)
outputs = Dense(num_classes,
activation='softmax',
kernel_initializer='he_normal')(y)
# Instantiate model.
model = Model(inputs=inputs, outputs=outputs)
return model
model = resnet_v1(input_shape=input_shape, depth=depth)
model.compile(loss='categorical_crossentropy',
optimizer=Adam(0.1),
metrics=['accuracy'])
model.summary()
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(x_test, y_test),
shuffle=True)
# Score trained model.
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])
```
| github_jupyter |
# Collecting Bundestag data from Abgeordnetenwatch
> [Abgeordnetenwatch](https://www.abgeordnetenwatch.de) provides an [open API](https://www.abgeordnetenwatch.de/api) that provides info on, among other things, politicians, the politicians' votes and the different polls in parliament, including meta info.
This notebook collects the following information and prepares its parsing to `pandas.DataFrame` objects:
* polls for the 2017-2021 period of the Bundestag
* votes of members of the Bundestag 2017-2021
* info on members of the Bundestag 2017-2021
TODOs:
- identify why in vote json files some mandate_id values (politicians / mandates) appear multiple times (not always with the same vote result) -> affects `compile_votes_data` -> currently ignored and first of the duplicates used
```
%load_ext autoreload
%autoreload 2
from bundestag import abgeordnetenwatch as aw
aw.ABGEORDNETENWATCH_PATH.parent
aw.ABGEORDNETENWATCH_PATH.mkdir(exist_ok=True)
```
## Polls 2017-2021
Polls = objects voted on in the Bundestag by the parlamentarians
```
dry = True # set `True` for testing, `False` otherwise
```
### Collecting
```
%%time
legislature_id = 111
info = aw.get_poll_info(legislature_id, dry=dry)
aw.store_polls_json(info, legislature_id, dry=dry)
```
### Parsing
```
%%time
legislature_id = 111
df = aw.get_polls_df(legislature_id)
aw.test_poll_data(df)
df.head()
df.to_parquet(path=aw.ABGEORDNETENWATCH_PATH/'df_polls.parquet')
```
## Info on politicians
### Collecting
```
legislature_id = 111
info = aw.get_mandates_info(legislature_id,dry=dry)
aw.store_mandates_info(info, legislature_id, dry=dry)
```
### Parsing
```
legislature_id = 111
df = aw.get_mandates_df(legislature_id)
aw.test_mandate_data(df)
df['party'] = df.apply(aw.get_party_from_fraction_string, axis=1)
df.head().T
df.to_parquet(path=aw.ABGEORDNETENWATCH_PATH/'df_mandates.parquet')
```
## Votes for one specific poll
### Collecting
```
poll_id = 4217
info = aw.get_vote_info(poll_id, dry=dry)
aw.store_vote_info(info, poll_id, dry=dry)
```
### Parsing
```
%%time
aw.test_stored_vote_ids_check()
%%time
legislature_id, poll_id = 111, 4217
df = aw.get_votes_df(legislature_id, poll_id)
aw.test_vote_data(df)
df.head()
```
## All votes for all remaining polls of a specific legislative period
Above only one specific poll vote information was collected for. Here we collect votes for whatever polls are missing.
### Collecting
```
%%time
legislature_id = 111
aw.get_all_remaining_vote_info(legislature_id, dry=dry)
```
### Parsing
```
%%time
legislature_id = 111
df_all_votes = aw.compile_votes_data(legislature_id)
display(df_all_votes.head(), df_all_votes.tail())
```
Write compiled votes to disk as csv
```
all_votes_path = aw.ABGEORDNETENWATCH_PATH / f'compiled_votes_legislature_{legislature_id}.csv'
df_all_votes.to_csv(all_votes_path, index=False)
df_all_votes = df_all_votes.assign(
**{"politician name": aw.get_politician_names}
)
df_all_votes.to_parquet(path=aw.ABGEORDNETENWATCH_PATH/'df_all_votes.parquet')
!head $all_votes_path
```
| github_jupyter |
<i>Copyright (c) Microsoft Corporation. All rights reserved.</i>
<i>Licensed under the MIT License.</i>
# SAR Single Node on MovieLens (Python, CPU)
In this example, we will walk through each step of the Simple Algorithm for Recommendation (SAR) algorithm using a Python single-node implementation.
SAR is a fast, scalable, adaptive algorithm for personalized recommendations based on user transaction history. It is powered by understanding the similarity between items, and recommending similar items to those a user has an existing affinity for.
## 1 SAR algorithm
The following figure presents a high-level architecture of SAR.
At a very high level, two intermediate matrices are created and used to generate a set of recommendation scores:
- An item similarity matrix $S$ estimates item-item relationships.
- An affinity matrix $A$ estimates user-item relationships.
Recommendation scores are then created by computing the matrix multiplication $A\times S$.
Optional steps (e.g. "time decay" and "remove seen items") are described in the details below.
<img src="https://recodatasets.blob.core.windows.net/images/sar_schema.svg?sanitize=true">
### 1.1 Compute item co-occurrence and item similarity
SAR defines similarity based on item-to-item co-occurrence data. Co-occurrence is defined as the number of times two items appear together for a given user. We can represent the co-occurrence of all items as a $m\times m$ matrix $C$, where $c_{i,j}$ is the number of times item $i$ occurred with item $j$, and $m$ is the total number of items.
The co-occurence matric $C$ has the following properties:
- It is symmetric, so $c_{i,j} = c_{j,i}$
- It is nonnegative: $c_{i,j} \geq 0$
- The occurrences are at least as large as the co-occurrences. I.e., the largest element for each row (and column) is on the main diagonal: $\forall(i,j) C_{i,i},C_{j,j} \geq C_{i,j}$.
Once we have a co-occurrence matrix, an item similarity matrix $S$ can be obtained by rescaling the co-occurrences according to a given metric. Options for the metric include `Jaccard`, `lift`, and `counts` (meaning no rescaling).
If $c_{ii}$ and $c_{jj}$ are the $i$th and $j$th diagonal elements of $C$, the rescaling options are:
- `Jaccard`: $s_{ij}=\frac{c_{ij}}{(c_{ii}+c_{jj}-c_{ij})}$
- `lift`: $s_{ij}=\frac{c_{ij}}{(c_{ii} \times c_{jj})}$
- `counts`: $s_{ij}=c_{ij}$
In general, using `counts` as a similarity metric favours predictability, meaning that the most popular items will be recommended most of the time. `lift` by contrast favours discoverability/serendipity: an item that is less popular overall but highly favoured by a small subset of users is more likely to be recommended. `Jaccard` is a compromise between the two.
### 1.2 Compute user affinity scores
The affinity matrix in SAR captures the strength of the relationship between each individual user and the items that user has already interacted with. SAR incorporates two factors that can impact users' affinities:
- It can consider information about the **type** of user-item interaction through differential weighting of different events (e.g. it may weigh events in which a user rated a particular item more heavily than events in which a user viewed the item).
- It can consider information about **when** a user-item event occurred (e.g. it may discount the value of events that take place in the distant past.
Formalizing these factors produces us an expression for user-item affinity:
$$a_{ij}=\sum_k w_k \left(\frac{1}{2}\right)^{\frac{t_0-t_k}{T}} $$
where the affinity $a_{ij}$ for user $i$ and item $j$ is the weighted sum of all $k$ events involving user $i$ and item $j$. $w_k$ represents the weight of a particular event, and the power of 2 term reflects the temporally-discounted event. The $(\frac{1}{2})^n$ scaling factor causes the parameter $T$ to serve as a half-life: events $T$ units before $t_0$ will be given half the weight as those taking place at $t_0$.
Repeating this computation for all $n$ users and $m$ items results in an $n\times m$ matrix $A$. Simplifications of the above expression can be obtained by setting all the weights equal to 1 (effectively ignoring event types), or by setting the half-life parameter $T$ to infinity (ignoring transaction times).
### 1.3 Remove seen item
Optionally we remove items which have already been seen in the training set, i.e. don't recommend items which have been previously bought by the user again.
### 1.4 Top-k item calculation
The personalized recommendations for a set of users can then be obtained by multiplying the affinity matrix ($A$) by the similarity matrix ($S$). The result is a recommendation score matrix, where each row corresponds to a user, each column corresponds to an item, and each entry corresponds to a user / item pair. Higher scores correspond to more strongly recommended items.
It is worth noting that the complexity of recommending operation depends on the data size. SAR algorithm itself has $O(n^3)$ complexity. Therefore the single-node implementation is not supposed to handle large dataset in a scalable manner. Whenever one uses the algorithm, it is recommended to run with sufficiently large memory.
## 2 SAR single-node implementation
The SAR implementation illustrated in this notebook was developed in Python, primarily with Python packages like `numpy`, `pandas`, and `scipy` which are commonly used in most of the data analytics / machine learning tasks. Details of the implementation can be found in [Recommenders/reco_utils/recommender/sar/sar_singlenode.py](../../reco_utils/recommender/sar/sar_singlenode.py).
## 3 SAR single-node based movie recommender
```
# set the environment path to find Recommenders
import sys
sys.path.append("../../")
import itertools
import logging
import os
import numpy as np
import pandas as pd
import papermill as pm
from reco_utils.dataset import movielens
from reco_utils.dataset.python_splitters import python_random_split
from reco_utils.evaluation.python_evaluation import map_at_k, ndcg_at_k, precision_at_k, recall_at_k
from reco_utils.recommender.sar.sar_singlenode import SARSingleNode
print("System version: {}".format(sys.version))
print("Pandas version: {}".format(pd.__version__))
# top k items to recommend
TOP_K = 10
# Select MovieLens data size: 100k, 1m, 10m, or 20m
MOVIELENS_DATA_SIZE = '100k'
```
### 3.1 Load Data
SAR is intended to be used on interactions with the following schema:
`<User ID>, <Item ID>, <Time>`.
Each row represents a single interaction between a user and an item. These interactions might be different types of events on an e-commerce website, such as a user clicking to view an item, adding it to a shopping basket, following a recommendation link, and so on.
The MovieLens dataset is well formatted interactions of Users providing Ratings to Movies (movie ratings are used as the event weight) - we will use it for the rest of the example.
```
data = movielens.load_pandas_df(
size=MOVIELENS_DATA_SIZE,
header=['UserId', 'MovieId', 'Rating', 'Timestamp'],
title_col='Title'
)
# Convert the float precision to 32-bit in order to reduce memory consumption
data.loc[:, 'Rating'] = data['Rating'].astype(np.float32)
data.head()
```
### 3.2 Split the data using the python random splitter provided in utilities:
We utilize the provided `python_random_split` function to split into `train` and `test` datasets randomly at a 75/25 ratio.
```
train, test = python_random_split(data, 0.75)
header = {
"col_user": "UserId",
"col_item": "MovieId",
"col_rating": "Rating",
"col_timestamp": "Timestamp",
"col_prediction": "Prediction",
}
```
In this case, for the illustration purpose, the following parameter values are used:
|Parameter|Value|Description|
|---------|---------|-------------|
|`similarity_type`|`jaccard`|Method used to calculate item similarity.|
|`time_decay_coefficient`|30|Period in days (term of $T$ shown in the formula of Section 2.2.2)|
|`time_now`|`None`|Time decay reference.|
|`timedecay_formula`|`True`|Whether time decay formula is used.|
```
# set log level to INFO
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s')
model = SARSingleNode(
similarity_type="jaccard",
time_decay_coefficient=30,
time_now=None,
timedecay_formula=True,
**header
)
model.fit(train)
top_k = model.recommend_k_items(test, remove_seen=True)
```
The final output from the `recommend_k_items` method generates recommendation scores for each user-item pair, which are shown as follows.
```
top_k_with_titles = (top_k.join(data[['MovieId', 'Title']].drop_duplicates().set_index('MovieId'),
on='MovieId',
how='inner').sort_values(by=['UserId', 'Prediction'], ascending=False))
display(top_k_with_titles.head(10))
```
### 3.3 Evaluate the results
It should be known that the recommendation scores generated by multiplying the item similarity matrix $S$ and the user affinity matrix $A$ **DOES NOT** have the same scale with the original explicit ratings in the movielens dataset. That is to say, SAR algorithm is meant for the task of *recommending relevent items to users* rather than *predicting explicit ratings for user-item pairs*.
To this end, ranking metrics like precision@k, recall@k, etc., are more applicable to evaluate SAR algorithm. The following illustrates how to evaluate SAR model by using the evaluation functions provided in the `reco_utils`.
```
# all ranking metrics have the same arguments
args = [test, top_k]
kwargs = dict(col_user='UserId',
col_item='MovieId',
col_rating='Rating',
col_prediction='Prediction',
relevancy_method='top_k',
k=TOP_K)
eval_map = map_at_k(*args, **kwargs)
eval_ndcg = ndcg_at_k(*args, **kwargs)
eval_precision = precision_at_k(*args, **kwargs)
eval_recall = recall_at_k(*args, **kwargs)
print(f"Model:",
f"Top K:\t\t {TOP_K}",
f"MAP:\t\t {eval_map:f}",
f"NDCG:\t\t {eval_ndcg:f}",
f"Precision@K:\t {eval_precision:f}",
f"Recall@K:\t {eval_recall:f}", sep='\n')
```
## References
Note SAR is a combinational algorithm that implements different industry heuristics. The followings are references that may be helpful in understanding the SAR logic and implementation.
1. Badrul Sarwar, *et al*, "Item-based collaborative filtering recommendation algorithms", WWW, 2001.
2. Scipy (sparse matrix), url: https://docs.scipy.org/doc/scipy/reference/sparse.html
3. Asela Gunawardana and Guy Shani, "A survey of accuracy evaluation metrics of recommendation tasks", The Journal of Machine Learning Research, vol. 10, pp 2935-2962, 2009.
| github_jupyter |
<img src="../static/aeropython_name_mini.png" alt="AeroPython" style="width: 300px;"/>
# Clase 1a: Introducción a IPython
*En esta clase haremos una rápida introducción al lenguaje Python y al intérprete IPython, así como a su Notebook. Veremos como ejecutar un script y cuáles son los tipos y estructuras básicas de este lenguaje. Seguro que ya has oído hablar mucho sobre las bondades de Python frente a otros lenguajes. Si no es así, échale un vistazo a [esto](http://nbviewer.ipython.org/github/AeroPython/Python_HA/blob/master/razones_python.ipynb).
¿Estás preparado? ¡Pues Empezamos!*
## ¿Qué es Python?
* Lenguaje de programación **dinámico**, **interpretado** y fácil de aprender
* Creado por Guido van Rossum en 1991
* Ampliamente utilizado en ciencia e ingeniería
* Multitud de bibliotecas para realizar diferentes tareas.
### El zen de Python
```
import this
```
### ¿Qué pinta tiene un programa en Python y cómo lo ejecuto?
Vamos a ver `mi_primer_script.py` que está en la carpeta `static`. __De momento no te preocupes por el código,__ ya habrá tiempo para eso...
```
!cat ../static/mi_primer_script.py
```
<div class="alert alert-info"><strong>Tip de IPython</strong>:
`cat` es un comando de la línea de comandos, no propio de Python. Anteponiendo `!` a comandos de la terminal como `cd`, `ls`, `cat`... se pueden ejecutar desde aquí.
</div>
<div class="alert"><strong>Si estás usando Windows</strong> y acabas de obtener un error, susituye la línea anterior por:<br>
`!type ..\static\mi_primer_script.py`
<br><br>
`type` es un comando similar en Windows a `cat`. De nuevo, podemos ejecutar comandos como `cd`, `dir`, `type`, `find`... desde aquí anteponiendo `!` y utilizando `\` en lugar de `/` para la ruta donde se encuentra el archivo.
</div>
```
%run ../static/mi_primer_script.py
```
<div class="alert alert-info"><strong>Tip de IPython</strong>:
`%run` es un _comando mágico_ del notebook que te permite ejecutar un archivo.
Si quieres hacerlo desde una línea de comandos podrías hacer:
`$ python3 ../static/mi_primer_script.py`
</div>
El método más simple es usar un editor (tu preferido) y ejecutar el script desde la línea de comandos. Pero existen también __IDE__s (_integrated development environment_ pensados para facilitar la escritura de código y tener al alcance de la mano otras herramientas como _profilers_, _debuggers_, _explorador de variables_... Entre los más adecuados para la programación científica se encuentran [IEP](http://www.iep-project.org/) y [Spyder](http://code.google.com/p/spyderlib/) (instalado con Anaconda).
<img src="../static/spyder.png" alt="Spyder" style="width: 800px;"/>
## ¿Qué es IPython?
[IPython](http://ipython.org/) no es más que un [intérprete][1] de Python con algunas mejoras sustanciales, pero además su interfaz notebook es más cómoda de manejar que la línea de comandos y nos da un poco más de flexibilidad.
[1]: http://es.wikipedia.org/wiki/Int%C3%A9rprete_(inform%C3%A1tica)
### Notebook de IPython
__Será nuestra herramienta de trabajo durante el curso__. Esto que estás leyendo ahora no es más que un notebook de IPython, que como diremos luego además de código puede contener texto e imágenes. Pero veamos primero cómo funciona.
__Al iniciar el notebook de IPython, en la pantalla principal podemos ver una ruta y una lista de notebooks__. Cada notebook es un archivo que está almacenado en el ordenador en la ruta que aparece. Si en esa carpeta no hay notebooks, veremos un mensaje indicando que la lista de notebooks está vacía.
Al crear un notebook o al abrir uno nuevo se abre la interfaz de IPython propiamente dicha donde ya podemos empezar a trabajar. Es similar a un intérprete, pero está dividida en **celdas**. Las celdas pueden contener, código, texto, imágenes...
Cada celda de código está marcada por la palabra `In [<n>]` y están **numeradas**. Tan solo tenemos que escribir el código en ella y hacer click arriba en Cell -> Run, el triángulo ("Run cell") o usar el atajo `shift + Enter`. El resultado de la celda se muestra en el campo `Out [<n>]`, también numerado y coincidiendo con la celda que acabamos de ejecutar. Esto es importante, como ya veremos luego.
Si en la barra superior seleccionas Markdown (o usas el atajo `Shift-M`) en lugar de Code puedes escribir texto:
```
from IPython.display import Image
Image(url="../static/markdown_cell.gif")
# Fuente Practical Numerical Methods with Python
# http://openedx.seas.gwu.edu/courses/GW/MAE6286/2014_fall/about
```
También ecuaciones en latex y mucho más. Esto es una herramienta muy potente para explicar a alguien o a ti mismo lo que tu código hace, para hacer un informe, un trabajo, escribir en un blog...
Markdown es un lenguaje aparte, no te preocupes por él demasiado ahora, irás aprendiendo sobre la marcha... Para cuando lo vayas necesitando, aquí tienes una [chuleta](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
```
Image(url="../static/markdown_math.gif")
# Fuente Practical Numerical Methods with Python
# http://openedx.seas.gwu.edu/courses/GW/MAE6286/2014_fall/about
```
Puedes mover las celdas de un lugar a otro de este modo:
```
Image(url="../static/cell_move.gif")
# Fuente: Practical Numerical Methods with Python
# http://openedx.seas.gwu.edu/courses/GW/MAE6286/2014_fall/about
```
El Notebook tiene además numerosos atajos que irás aprendiendo sobre la marcha, puedes consultarlos en `Help > Keyboard Shortcourts`
## Introducción a la sintaxis de Python
### Tipos numéricos
Python dispone de los tipos numéricos y las operaciones más habituales:
```
2 * 4 - (7 - 1) / 3 + 1.0
```
Las divisiones por cero lanzan un error:
```
1 / 0
1.0 / 0.0
```
<div class="alert alert-info">Más adelante veremos cómo tratar estos errores. Por otro lado, cuando usemos NumPy esta operación devolverá `NaN`.</div>
La división entre enteros en Python 3 devuelve un número real, al contrario que en Python 2.
```
3 / 2
```
Se puede forzar que la división sea entera con el operador `//`:
```
3 // 2
```
Se puede elevar un número a otro con el operador `**`:
```
2 ** 16
```
Otro tipo que nos resultará muy útil son los complejos:
```
2 + 3j
1j
# Valor absoluto
abs(2 + 3j)
```
<div class="alert alert-info"><strong>Tip de IPython</strong>: podemos recuperar resultados pasados usando `_<n>`. Por ejemplo, para recuperar el resultado correspondiente a `Out [7]`, usaríamos `_7`. Esta variable guarda ese valor para toda la sesión.</div>
```
abs(_13)
```
Podemos __convertir variables__ a `int, float, complex, str`...
```
int(18.6)
round(18.6)
float(1)
complex(2)
str(256568)
```
Podemos __comprobar el tipo de una variable__:
```
a = 2.
type(a)
isinstance(a, float)
```
Otras funciones útiles son:
```
print('hola mundo')
max(1,5,8,7)
min(-1,1,0)
```
__¡Acabas de utilizar funciones!__ Como ves es una manera bastante estándar: los argumentos se encierran entre paréntesis y se separan por comas. Se hace de esta manera en otros lenguajes de programación y no requiere mayor explicación, de momento.
<div class="alert alert-warning">La <strong>función <code>print</code></strong> es la que se usa para imprimir resultados por pantalla. Por si lo ves en algún sitio, en Python 2 era una sentencia y funcionaba de manera distinta, sin paréntesis y sin posibilidad de pasar argumentos adicionales.</div>
### Asignación y operadores de comparación
La asignación se realiza con el operador `=`. Los nombres de las variables en Python pueden contener caracteres alfanuméricos (empezando con una letra) a-z, A-Z, 0-9 y otros símbolos como la \_.
Por cuestiones de estilo, las variables suelen empezar con minúscula, reservando la mayúcula para clases.
Algunos nombres no pueden ser usados porque son usados por python:
and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield
```
a = 1 + 2j
```
En Python __la asignación no imprime el resultado por pantalla__, al contrario de como sucede en MATLAB y Octave (salvo que se incluya el punto y coma al final). La mejor manera de visualizar la variable que acabamos de asignar es esta:
```
b = 3.14159
b
```
En una celda __podemos escribir código que ocupe varias líneas__. Si la última de ellas devuelve un resultado, este se imprimirá.
```
x, y = 1, 2
x, y
```
<div class="alert alert-info">Podemos realizar **asignación múltiple**, que hemos hecho en la celda anterior con las variables `x` e `y` para intercambiar valores de manera intuitiva:</div>
```
x, y = y, x
x, y
```
Los operadores de comparación son:
* `==` igual a
* `!=` distinto de
* `<` menor que
* `<=` menor o igual que
Devolverán un booleano: `True` o `False`
```
x == y
print(x != y)
print(x < y)
print(x <= y)
print(x > y)
print(x >= y)
# incluso:
x = 5.
6. < x < 8.
```
Si la ordenación no tiene sentido nos devolverá un error:
```
1 + 1j < 0 + 1j
# En las cadenas de texto sí existe un orden
'aaab' > 'ba'
```
#### Booleanos
```
True and False
not False
True or False
# Una curiosidad:
(True + True) * 10
# La razón...
isinstance(True, int)
```
#### Otros tipos de datos
Otro tipo de datos muy importante que vamos a usar son las secuencias: las tuplas y las listas. Ambos son conjuntos ordenados de elementos: las tuplas se demarcan con paréntesis y las listas con corchetes.
```
una_lista = [1, 2, 3.0, 4 + 0j, "5"]
una_tupla = (1, 2, 3.0, 4 + 0j, "5")
print(una_lista)
print(una_tupla)
print(una_lista == una_tupla)
```
Para las tuplas, podemos incluso obviar los paréntesis:
```
tupla_sin_parentesis = 2,5,6,9,7
type(tupla_sin_parentesis)
```
En los dos tipos podemos:
* Comprobar si un elemento está en la secuencia con el operador `in`:
```
2 in una_lista
2 in una_tupla
```
* Saber cuandos elementos tienen con la función `len`:
```
len(una_lista)
```
* Podemos *indexar* las secuencias, utilizando la sintaxis `[<inicio>:<final>:<salto>]`:
```
print(una_lista[0]) # Primer elemento, 1
print(una_tupla[1]) # Segundo elemento, 2
print(una_lista[0:2]) # Desde el primero hasta el tercero, excluyendo este: 1, 2
print(una_tupla[:3]) # Desde el primero hasta el cuarto, excluyendo este: 1, 2, 3.0
print(una_lista[-1]) # El último: 4 + 0j
print(una_tupla[:]) # Desde el primero hasta el último
print(una_lista[::2]) # Desde el primero hasta el último, saltando 2: 1, 3.0
```
Veremos más cosas acerca de indexación en NumPy, así que de momento no te preocupes. Sólo __recuerda una cosa:__
##### ¡En Python, la indexación empieza por CERO!
Podemos complicarlo un poco más y hacer cosas como una __lista de listas__:
```
mis_asignaturas = [
['Álgebra', 'Cálculo', 'Física'],
['Mecánica', 'Termodinámica'],
['Sólidos', 'Electrónica']
]
mis_asignaturas
```
Esto nos será de gran ayuda en el futuro para construir arrays.
## Estructuras de control (I): Condicionales
if <condition>:
<do something>
elif <condition>:
<do other thing>
else:
<do other thing>
<div class="alert alert-error"><strong>Importante:</strong> En Python los bloques se delimitan por sangrado, utilizando siempre cuatro espacios. Cuando ponemos los dos puntos al final de la primera línea del condicional, todo lo que vaya a continuación con *un* nivel de sangrado superior se considera dentro del condicional. En cuanto escribimos la primera línea con un nivel de sangrado inferior, hemos cerrado el condicional. Si no seguimos esto a rajatabla Python nos dará errores; es una forma de forzar a que el código sea legible.</div>
```
print(x,y)
if x > y:
print("x es mayor que y")
print("x sigue siendo mayor que y")
if 1 < 0:
print("1 es menor que 0")
print("1 sigue siendo menor que 0") # <-- ¡Mal!
if 1 < 0:
print("1 es menor que 0")
print("1 sigue siendo menor que 0")
```
Si queremos añadir ramas adicionales al condicional, podemos emplear la sentencia `elif` (abreviatura de *else if*). Para la parte final, que debe ejecutarse si ninguna de las condiciones anteriores se ha cumplido, usamos la sentencia `else`:
```
print(x,y)
if x > y:
print("x es mayor que y")
else:
print("x es menor que y")
print(x, y)
if x < y:
print("x es menor que y")
elif x == y:
print("x es igual a y")
else:
print("x no es ni menor ni igual que y")
```
## Estructuras de control (II): Bucles
En Python existen dos tipos de estructuras de control típicas:
1. Bucles `while`
2. Bucles `for`
### `while`
Los bucles `while` repetiran las sentencias anidadas en él mientras se cumpla una condición:
while <condition>:
<things to do>
Como en el caso de los condicionales, los bloques se separan por indentación sin necesidad de sentencias del tipo `end`
```
ii = -2
while ii < 5:
print(ii)
ii += 1
```
<div class="alert alert-info"><strong>Tip</strong>:
`ii += 1` equivale a `ii = ii + 1`. En el segundo Python, realiza la operación ii + 1 creando un nuevo objeto con ese valor y luego lo asigna a la variable ii; es decir, existe una reasignación. En el primero, sin embargo, el incremento se produce sobre la propia variable. Esto puede conducirnos a mejoras en velocidad.
Otros operadores 'in-place' son: `-=`, `*=`, `/=`
</div>
Se puede interrumpir el bucle a la mitad con la sentencia `break`:
```
ii = 0
while ii < 5:
print(ii)
ii += 1
if ii == 3:
break
```
Un bloque `else` justo después del bucle se ejecuta si este no ha sido interrumpido por nosotros:
```
ii = 0
while ii < 5:
print(ii)
ii += 1
if ii == 3:
break
else:
print("El bucle ha terminado")
ii = 0
while ii < 5:
print(ii)
ii += 1
#if ii == 3:
#break
else:
print("El bucle ha terminado")
```
### `for`
El otro bucle en Python es el bucle `for`, y funciona de manera un que puede resultar chocante al principio. La idea es recorrer un conjunto de elementos:
for <element> in <iterable_object>:
<do whatever...>
```
for ii in (1,2,3,4,5):
print(ii)
for nombre in "Juanlu", "Siro", "Carlos":
print(nombre)
for ii in range(3):
print(ii)
for jj in range(2, 5):
print(jj)
```
## PEP 8
__La guía de estilo:__
* Usa sangrado de 4 espacios, no tabuladores [IPython o tu editor se encargan de ello].
* Acota las líneas a 79 caracteres.
* Usa líneas en blanco para separar funciones y bloques de código dentro de ellas.
* Pon los comentarios en líneas aparte si es posible.
* Usa cadenas de documentación (*docstrings*).
* Pon espacios alrededor de los operadores y después de coma.
* Usa la convención minuscula_con_guiones_bajos para los nombres de las funciones y las variables.
* Aunque Python 3 te lo permite, no uses caracteres especiales para los identificadores.
(Traducido de http://docs.python.org/3/tutorial/controlflow.html#intermezzo-coding-style)
Utilizando el módulo pep8
https://pypi.python.org/pypi/pep8
Y la extensión pep8magic
https://gist.github.com/Juanlu001/9082229/
Podemos comprobar si una celda de código cumple con las reglas del PEP8:
---
_Hemos visto como la sintaxis de Python nos facilita escribir código legible así como aprendido algunas buenas prácticas al programar. Características como el tipado dinámico (no hace falta declarar variables) y ser lenguaje interpretado (no hace falta compilarlo) hacen que el tiempo que pasamos escrbiendo código sea menos que en otro tipo de lenguajes._
_Se han presentado los tipos de variables, así como las estructuras de control básicas. En la siguiente clase practicaremos con algunos ejercicios para que te familiarices con ellas_
_Esperamos también que poco a poco te sientas cada vez más a gusto con el Notebook de IPython y puedas sacarle todo el partido_
__Referencias__
* Tutorial de Python oficial actualizado y traducido al español http://docs.python.org.ar/tutorial/
* Vídeo de 5 minutos de IPython http://youtu.be/C0D9KQdigGk
* Introducción a la programación con Python, Universitat Jaume I http://www.uji.es/bin/publ/edicions/ippython.pdf
* PEP8 http://www.python.org/dev/peps/pep-0008/
---
Clase en vídeo, parte del [Curso de Python para científicos e ingenieros](http://cacheme.org/curso-online-python-cientifico-ingenieros/) grabado en la Escuela Politécnica Superior de la Universidad de Alicante.
```
from IPython.display import YouTubeVideo
YouTubeVideo("ox09Jko1ErM", width=560, height=315, list="PLGBbVX_WvN7bMwYe7wWV5TZt1a58jTggB")
```
---
Si te ha gustado esta clase:
<a href="https://twitter.com/share" class="twitter-share-button" data-url="https://github.com/AeroPython/curso_caminos-2016/" data-text="Aprendiendo Python con" data-via="AeroPython" data-size="large" data-hashtags="AeroPython">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
---
#### <h4 align="right">¡Síguenos en Twitter!
###### <a href="https://twitter.com/AeroPython" class="twitter-follow-button" data-show-count="false">Follow @AeroPython</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
##### <a rel="license" href="http://creativecommons.org/licenses/by/4.0/deed.es"><img alt="Licencia Creative Commons" style="border-width:0" src="http://i.creativecommons.org/l/by/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Curso AeroPython</span> por <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">Juan Luis Cano Rodriguez y Alejandro Sáez Mollejo</span> se distribuye bajo una <a rel="license" href="http://creativecommons.org/licenses/by/4.0/deed.es">Licencia Creative Commons Atribución 4.0 Internacional</a>.
##### <script src="//platform.linkedin.com/in.js" type="text/javascript"></script> <script type="IN/MemberProfile" data-id="http://es.linkedin.com/in/juanluiscanor" data-format="inline" data-related="false"></script> <script src="//platform.linkedin.com/in.js" type="text/javascript"></script> <script type="IN/MemberProfile" data-id="http://es.linkedin.com/in/alejandrosaezm" data-format="inline" data-related="false"></script>
---
_Las siguientes celdas contienen configuración del Notebook_
_Para visualizar y utlizar los enlaces a Twitter el notebook debe ejecutarse como [seguro](http://ipython.org/ipython-doc/dev/notebook/security.html)_
File > Trusted Notebook
```
%%html
<a href="https://twitter.com/AeroPython" class="twitter-follow-button" data-show-count="false">Follow @AeroPython</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
# Esta celda da el estilo al notebook
from IPython.core.display import HTML
css_file = '../static/styles/style.css'
HTML(open(css_file, "r").read())
```
| github_jupyter |
**[Introduction to Machine Learning Home Page](https://www.kaggle.com/learn/intro-to-machine-learning)**
---
## Recap
So far, you have loaded your data and reviewed it with the following code. Run this cell to set up your coding environment where the previous step left off.
```
# Code you have previously used to load data
import pandas as pd
# Path of the file to read
iowa_file_path = '../input/home-data-for-ml-course/train.csv'
home_data = pd.read_csv(iowa_file_path)
# Set up code checking
from learntools.core import binder
binder.bind(globals())
from learntools.machine_learning.ex3 import *
print("Setup Complete")
```
# Exercises
## Step 1: Specify Prediction Target
Select the target variable, which corresponds to the sales price. Save this to a new variable called `y`. You'll need to print a list of the columns to find the name of the column you need.
```
# print the list of columns in the dataset to find the name of the prediction target
home_data.columns
y = home_data.SalePrice
# Check your answer
step_1.check()
# The lines below will show you a hint or the solution.
# step_1.hint()
# step_1.solution()
```
## Step 2: Create X
Now you will create a DataFrame called `X` holding the predictive features.
Since you want only some columns from the original data, you'll first create a list with the names of the columns you want in `X`.
You'll use just the following columns in the list (you can copy and paste the whole list to save some typing, though you'll still need to add quotes):
* LotArea
* YearBuilt
* 1stFlrSF
* 2ndFlrSF
* FullBath
* BedroomAbvGr
* TotRmsAbvGrd
After you've created that list of features, use it to create the DataFrame that you'll use to fit the model.
```
# Create the list of features below
feature_names = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']
# Select data corresponding to features in feature_names
X = home_data[feature_names]
# Check your answer
step_2.check()
# step_2.hint()
# step_2.solution()
```
## Review Data
Before building a model, take a quick look at **X** to verify it looks sensible
```
# Review data
# print description or statistics from X
print(X.describe())
# print the top few lines
print(y.head())
```
## Step 3: Specify and Fit Model
Create a `DecisionTreeRegressor` and save it iowa_model. Ensure you've done the relevant import from sklearn to run this command.
Then fit the model you just created using the data in `X` and `y` that you saved above.
```
from sklearn.tree import DecisionTreeRegressor
#specify the model.
#For model reproducibility, set a numeric value for random_state when specifying the model
iowa_model = DecisionTreeRegressor(random_state=1)
# Fit the model
iowa_model.fit(X,y)
# Check your answer
step_3.check()
# step_3.hint()
# step_3.solution()
```
## Step 4: Make Predictions
Make predictions with the model's `predict` command using `X` as the data. Save the results to a variable called `predictions`.
```
predictions = iowa_model.predict(X)
print(predictions)
# Check your answer
step_4.check()
# step_4.hint()
# step_4.solution()
```
## Think About Your Results
Use the `head` method to compare the top few predictions to the actual home values (in `y`) for those same homes. Anything surprising?
```
# You can write code in this cell
print(y.head())
print(predictions[:5])
```
It's natural to ask how accurate the model's predictions will be and how you can improve that. That will be you're next step.
# Keep Going
You are ready for **[Model Validation](https://www.kaggle.com/dansbecker/model-validation).**
---
**[Introduction to Machine Learning Home Page](https://www.kaggle.com/learn/intro-to-machine-learning)**
*Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum) to chat with other Learners.*
| github_jupyter |
<a href="https://colab.research.google.com/github/HRKagdi/Machine-Learning/blob/master/MiniBatchGradientDescent.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
#Importing the required libraries
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
#Loading the Boston Housing Dataset
from sklearn.datasets import load_boston
X, y = load_boston(return_X_y=True)
print(X.shape)
#Dividing the dataset into training and test
x_train=X[0:400,:]
y_train=y[0:400]
x_test=X[400:506,:]
y_test=y[400:506]
sc=StandardScaler()
sc.fit(x_train)
#Normalization
x_train=sc.transform(x_train)
x_test=sc.transform(x_test)
print(x_train.shape)
#Initailizing the parameters randomly
Theta=np.random.rand(14,1)
#Adding the dummy independent variable
Theta[0]=1
print(Theta)
#Adding the dummy independent variable
x_train=np.insert(x_train,0,1,axis=1)
x_test=np.insert(x_test,0,1,axis=1)
y_train=y_train.reshape(400,1)
y_test=y_test.reshape(106,1)
print(x_train.shape)
#Cost Function::Mean Square Error
def Cost_function(x_train,y_train,Theta):
m=x_train.shape[0]
J_Theta=(1/(2*m))*np.sum(pow((np.dot(x_train,Theta)-y_train),2))
return J_Theta
#Gradient Descent Algorithm
def GradientDescent(x_train,y_train,alpha,Theta):
x_mini=x_train[0:50,:]
y_mini=y_train[0:50,:]
J_Theta=Cost_function(x_mini,y_mini,Theta)
cost_list=[]
i=0
print(J_Theta)
dict={}
temp=1000000
max_iterations=15000
size_of_mini_batch=50
number_of_mini_batches=(int)(x_train.shape[0]/size_of_mini_batch)
while(True):
lx=0
rx=50
if(temp-J_Theta<0.00001 and i>max_iterations):
break
temp=J_Theta
for j in range (1,number_of_mini_batches):
x_mini=x_train[lx:rx,:]
y_mini=y_train[lx:rx,:]
J_Theta=Cost_function(x_mini,y_mini,Theta)
Theta=Theta-(1/size_of_mini_batch)*alpha*(np.dot(x_mini.transpose(),np.dot(x_mini,Theta)-y_mini))
lx=lx+50
rx=rx+50
if(lx==400):
break
cost_list.append(J_Theta)
i+=1
#plt.show
dict['cost']=J_Theta
dict['parameters']=Theta
dict['Error']=cost_list
dict['No_of_Iter']=i
return dict
#Displaying the traning error
cost=GradientDescent(x_train,y_train,0.001,Theta)
print(cost['cost'])
param=cost['parameters']
print(param)
test_error=Cost_function(x_test,y_test,param)
print(test_error)
i=cost['No_of_Iter']
iter=np.arange(0,i)
error=cost['Error']
plt.plot(iter,error)
plt.xlabel('No_of_iterations')
plt.ylabel('Error')
plt.show
m=x_test.shape[0]
test_cost=(1/(2*m))*np.sum(pow((np.dot(x_test,param)-y_test),2))
print(test_cost)
#The test accuracy was found minimum for max_no_of_iterations=15000
```
| github_jupyter |
```
import os, platform, pprint, sys
import fastai
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn
import yellowbrick as yb
from fastai.tabular.data import TabularDataLoaders, TabularPandas
from fastai.tabular.all import FillMissing, Categorify, Normalize, tabular_learner, accuracy, ClassificationInterpretation, ShowGraphCallback, RandomSplitter, range_of
from sklearn.base import BaseEstimator
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import GridSearchCV, StratifiedShuffleSplit, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from yellowbrick.model_selection import CVScores, LearningCurve, ValidationCurve
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestClassifier
import time
seed: int = 14
# set up pretty printer for easier data evaluation
pretty = pprint.PrettyPrinter(indent=4, width=30).pprint
# declare file paths for the data we will be working on
data_path_1 : str = '../../data/prepared/baseline/'
data_path_2 : str = '../../data/prepared/timebased/'
modelPath : str = './models'
# list the names of the datasets we will be using
attacks : list = [ 'DNS', 'LDAP', 'MSSQL', 'NetBIOS', 'NTP', 'Portmap', 'SNMP', 'SSDP', 'Syn', 'TFTP', 'UDP', 'UDPLag' ]
dataset_info : list = [ 'Without_Benign', 'With_Benign' ]
datasets : list = [ 'Attacks_Many_vs_Many.csv', 'Benign_Many_vs_Many.csv' ]
# enumerate dataset types
Baseline : int = 0
Timebased: int = 1
# print library and python versions for reproducibility
print(
f'''
python:\t{platform.python_version()}
\tfastai:\t\t{fastai.__version__}
\tmatplotlib:\t{mpl.__version__}
\tnumpy:\t\t{np.__version__}
\tpandas:\t\t{pd.__version__}
\tsklearn:\t{sklearn.__version__}
\tyellowbrick:\t{yb.__version__}
'''
)
def get_file_path(directory: str):
'''
Closure that will return a function that returns the filepath to the directory given to the closure
'''
def func(file: str) -> str:
return os.path.join(directory, file)
return func
def load_data(filePath: str) -> pd.DataFrame:
'''
Loads the Dataset from the given filepath and caches it for quick access in the future
Function will only work when filepath is a .csv file
'''
# slice off the ./CSV/ from the filePath
if filePath[0] == '.' and filePath[1] == '.':
filePathClean: str = filePath[20::]
pickleDump: str = f'{filePath}.pickle'
else:
pickleDump: str = f'../../data/cache/{filePath}.pickle'
print(f'Loading Dataset: {filePath}')
print(f'\tTo Dataset Cache: {pickleDump}\n')
# check if data already exists within cache
if os.path.exists(pickleDump):
df = pd.read_pickle(pickleDump)
# if not, load data and cache it
else:
df = pd.read_csv(filePath, low_memory=True)
df.to_pickle(pickleDump)
return df
def run_experiment(df: pd.DataFrame, name: str) -> tuple:
'''
Run binary classification using K-Nearest Neighbors
returns the 7-tuple with the following indicies:
results: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
# First we split the features into the dependent variable and
# continous and categorical features
dep_var: str = 'Label'
if 'Protocol' in df.columns:
categorical_features: list = ['Protocol']
else:
categorical_features: list = []
continuous_features = list(set(df) - set(categorical_features) - set([dep_var]))
# Next, we set up the feature engineering pipeline, namely filling missing values
# encoding categorical features, and normalizing the continuous features
# all within a pipeline to prevent the normalization from leaking details
# about the test sets through the normalized mapping of the training sets
procs = [FillMissing, Categorify, Normalize]
splits = RandomSplitter(valid_pct=0.2, seed=seed)(range_of(df))
# The dataframe is loaded into a fastai datastructure now that
# the feature engineering pipeline has been set up
to = TabularPandas(
df , y_names=dep_var ,
splits=splits , cat_names=categorical_features ,
procs=procs , cont_names=continuous_features ,
)
# We use fastai to quickly extract the names of the classes as they are mapped to the encodings
dls = to.dataloaders(bs=64)
mds = tabular_learner(dls)
classes : list = list(mds.dls.vocab)
# We extract the training and test datasets from the dataframe
X_train = to.train.xs.reset_index(drop=True)
X_test = to.valid.xs.reset_index(drop=True)
y_train = to.train.ys.values.ravel()
y_test = to.valid.ys.values.ravel()
# Now that we have the train and test datasets, we set up a K-NN classifier
# using SciKitLearn and print the results
model = RandomForestClassifier()
t0 = time.time()
model.fit(X_train, y_train)
train_time = time.time()-t0
prediction = model.predict(X_test)
print(f'\tAccuracy: {accuracy_score(y_test, prediction)}\n Time: {train_time} seconds')
report = classification_report(y_test, prediction)
print(report)
# print('\n3-Fold Cross-Validation Scores\n')
# result = cross_val_score(model, X_train, y_train, cv=StratifiedShuffleSplit(n_splits=3, test_size=0.2, random_state=seed))
# print(f"\tAccuracy: {results.mean()*100}%")
# we add a target_type_ attribute to our model so yellowbrick knows how to make the visualizations
if len(classes) == 2:
model.target_type_ = 'binary'
elif len(classes) > 2:
model.target_type_ = 'multiclass'
else:
print('Must be more than one class to perform classification')
raise ValueError('Wrong number of classes')
# Track the learning curve of the classifier, here we want the
# training and validation scores to approach 1
# visualizer = LearningCurve(model, scoring='f1_weighted')
# visualizer.fit(X_train, y_train)
# visualizer.show()
# Now that the classifier has been created and trained, we pass out our training values
# so that yellowbrick can use them to create various visualizations
results: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
return results
def visualize_learning_curve_train(results: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a learning curve
results: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
# Track the learning curve of the classifier, here we want the
# training and validation scores to approach 1
visualizer = LearningCurve(results[1], scoring='f1_weighted')
visualizer.fit(results[3], results[4])
visualizer.show()
def visualize_learning_curve_test(results: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a learning curve
results: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
# Track the learning curve of the classifier, here we want the
# training and validation scores to approach 1
visualizer = LearningCurve(results[1], scoring='f1_weighted')
visualizer.fit(results[5], results[6])
visualizer.show()
def visualize_confusion_matrix(results: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a confusion matrix
results: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.classifier.ConfusionMatrix(results[1], classes=results[2], title=results[0])
visualizer.score(results[5], results[6])
visualizer.show()
def visualize_roc(results: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a
Receiver Operating Characteristic (ROC) Curve
results: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.classifier.ROCAUC(results[1], classes=results[2], title=results[0])
visualizer.score(results[5], results[6])
visualizer.poof()
def visualize_pr_curve(results: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a
Precision-Recall Curve
Note: only works with binary classification
results: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.classifier.PrecisionRecallCurve(results[1], title=results[0])
visualizer.score(results[5], results[6])
visualizer.poof()
def visualize_report(results: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a report
detailing the Precision, Recall, f1, and Support scores for all
classification outcomes
results: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.classifier.ClassificationReport(results[1], classes=results[2], title=results[0], support=True)
visualizer.score(results[5], results[6])
visualizer.poof()
def visualize_class_balance(results: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a histogram
detailing the balance between classification outcomes
results: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.target.ClassBalance(labels=results[0])
visualizer.fit(results[4], results[6])
visualizer.show()
# use the get_file_path closure to create a function that will return the path to a file
baseline_path = get_file_path(data_path_1)
timebased_path = get_file_path(data_path_2)
# create a list of the paths to all of the dataset files
baseline_files : list = list(map(baseline_path , datasets))
timebased_files: list = list(map(timebased_path, datasets))
baseline_dfs : map = map(load_data , baseline_files )
timebased_dfs: map = map(load_data , timebased_files)
experiments : zip = zip(baseline_dfs, timebased_dfs , dataset_info)
def experiment_runner():
'''
A generator that handles running the experiments
'''
num = 1
for baseline, timebased, info in experiments:
print(f'Running experiment #{num}:\t{info}')
print('Baseline results')
baseline_results = run_experiment(baseline, f'many_vs_many_{info}_baseline')
print('\nTime-based results')
timebased_results = run_experiment(timebased, f'many_vs_many_{info}_timebased')
num += 1
yield (baseline_results, timebased_results, info, num)
def do_experiment(num: int) -> tuple:
'''
A function that runs the specific experiment specified
'''
index = num - 1
baseline = load_data(baseline_files[index])
timebased = load_data(timebased_files[index])
info = attacks[index]
print(f'Running experiment #{num}:\t{info}')
print('Baseline results')
baseline_results = run_experiment(baseline, f'many_vs_many_{info}_baseline')
print('\nTime-based results')
timebased_results = run_experiment(timebased, f'many_vs_many_{info}_timebased')
return (baseline_results, timebased_results, info, num)
experiment = experiment_runner()
```
# Experiments
Our experiments are now conducted, the results are taken and are used to create a series of visualizations each representing various aspects of the experiments.
The Baseline results are plotted followed by the Timebased results for each graph
the variable 'results' holds the references to all the datasets being used by the current experiment, once the next experiment is executed, the results variabe is overwritten and the references to the previous datasets are removed. The previous datasets are then eventually removed from memory by the garbage collector.
## Experiment #1: Multi-Class Classification without Benign Samples
```
results = next(experiment)
visualize_learning_curve_test(results[Baseline])
visualize_learning_curve_test(results[Timebased])
visualize_report(results[Baseline])
visualize_report(results[Timebased])
visualize_confusion_matrix(results[Baseline])
visualize_confusion_matrix(results[Timebased])
visualize_roc(results[Baseline])
visualize_roc(results[Timebased])
```
## Experiment #2: Multi-Class Classification with Benign Samples
```
results = next(experiment)
visualize_learning_curve_test(results[Baseline])
visualize_learning_curve_test(results[Timebased])
visualize_report(results[Baseline])
visualize_report(results[Timebased])
visualize_confusion_matrix(results[Baseline])
visualize_confusion_matrix(results[Timebased])
visualize_roc(results[Baseline])
visualize_roc(results[Timebased])
```
| github_jupyter |
```
from fastscape.models import sediment_model
import xsimlab as xs
import xarray as xr
import numpy as np
import zarr
from ipyfastscape import TopoViz3d
import matplotlib.pyplot as plt
#plt.style.use('dark_background')
import hvplot.xarray
import dask
sediment_model.visualize(show_inputs=True)
```
**Source to Sink model**
We predict the evolution of a source to sink system using the FastScape library. For this, we model an area experiencing uplift in one third of the modeled area and subsidence in the other two thirds. This represent a system composed of an uplifting mountain and an adjacent subsiding foreland basin. The uplift is uniform in the mountain while the subsidence in the basin decreases linearly from the mountain front to the edge of the basin/model.
The flux computed from FastScape will then be used as input for another (more recent) 1D marine deposition model that allows to reproduce more accurately deep water sedimentation. Note that this model is in the process of being published by its author, Charlie Shobe. You should therefore refrained from copying/distributing it.
With this setup we will investigate how a cyclic variation in precipitation rate is transmitted form the mountain area to the sedimentary basin and beyond.
**Periodic_Forcing Process**
We create a process to allow for the parameters depending on precipitation (Kf and G) to be made periodic functions of time.<br>
The inputs are a period and amplitude.
```
from fastscape.processes import (DifferentialStreamPowerChannelTD)
@xs.process
class Periodic_Forcing:
period = xs.variable(intent="inout", description="period of relative precipitation rate", attrs={"units": "yrs"})
amplitude = xs.variable(intent="inout", description="amplitude relative precipitation rate", attrs={"units": "dimensionless"})
k0_coef_bedrock = xs.variable(intent="in", description="erodibility (rate coefficient) for bedrock", attrs={"units": "m^(2-m)/yr"})
k0_coef_soil = xs.variable(intent="in", description="erodibility (rate coefficient) for soil", attrs={"units": "m^(2-m)/yr"})
g0_coef_bedrock = xs.variable(intent="in", description="transport coefficient for bedrock", attrs={"units": "dimensionless"})
g0_coef_soil = xs.variable(intent="in", description="transport coefficient for bedrock", attrs={"units": "dimensionless"})
m = xs.foreign(DifferentialStreamPowerChannelTD, 'area_exp', intent='in')
k_coef_bedrock = xs.foreign(DifferentialStreamPowerChannelTD, 'k_coef_bedrock', intent='out')
k_coef_soil = xs.foreign(DifferentialStreamPowerChannelTD, 'k_coef_soil', intent='out')
g_coef_bedrock = xs.foreign(DifferentialStreamPowerChannelTD, 'g_coef_bedrock', intent='out')
g_coef_soil = xs.foreign(DifferentialStreamPowerChannelTD, 'g_coef_soil', intent='out')
rate = xs.variable(dims=(), static=False, intent="out", description="relative precipitation rate", attrs={"units": "dimensionless"})
@xs.runtime(args="nsteps")
def initialize(self, nsteps):
self.rate = np.empty(nsteps)
@xs.runtime(args=("step_start","step"))
def run_step(self, tim, iout):
precip = (1+self.amplitude + self.amplitude*np.sin(2*np.pi*tim/self.period))**5
self.k_coef_bedrock = self.k0_coef_bedrock*precip**self.m
self.k_coef_soil = self.k0_coef_soil*precip**self.m
self.g_coef_bedrock = self.g0_coef_bedrock/precip
self.g_coef_soil = self.g0_coef_soil/precip
self.rate = precip
```
**DualUplift Process**
We create a process to prescribe an uplift function made of an uplift block next to a subsiding basin.<br>
The inputs are an uplift rate, a subsidence rate and the position in the x-direction of the boundary between the two.
```
from fastscape.processes import (BlockUplift, RasterGrid2D)
@xs.process
class DualUplift:
up = xs.variable(intent="inout", description="uplift rate", attrs={"units": "m/yrs"})
down = xs.variable(intent="inout", description="subsidence rate", attrs={"units": "m/yrs"})
xlim = xs.variable(intent="inout", description="boundary between mountain and basin", attrs={"units": "m"})
uplift_rate = xs.foreign(BlockUplift, 'rate', intent='out')
x = xs.foreign(RasterGrid2D, 'x')
y = xs.foreign(RasterGrid2D, 'y')
def initialize(self):
X, Y = np.meshgrid(self.x, self.y)
self.uplift_rate= np.where(X > self.xlim, self.up, -X/self.xlim*self.down)
```
**Wells Process**
We create a process that's going to record topographic and uplift/subsidence rate information at all time steps (not just the output time steps) but only for a limited number of wells
```
from fastscape.processes import (SurfaceTopography, RasterGrid2D)
@xs.process
class Wells:
strati = xs.variable(dims=("wells",), static=False, intent="out", description="erosion rate", attrs={"units": "m/yr"})
rate = xs.variable(dims=("wells",), static=False, intent="out", description="erosion rate", attrs={"units": "m/yr"})
wellx = xs.variable(dims="well", intent="in")
welly = xs.variable(dims="well", intent="in")
x = xs.foreign(RasterGrid2D, 'x')
y = xs.foreign(RasterGrid2D, 'y')
h = xs.foreign(SurfaceTopography, 'elevation', intent="in")
uplift_rate = xs.foreign(BlockUplift, 'rate', intent='in')
@xs.runtime(args="nsteps")
def initialize(self, nsteps):
self.ix = np.searchsorted(self.x, self.wellx)
self.iy = np.searchsorted(self.y, self.welly)
self.nwells = len(self.ix)
self.rate = np.zeros((self.nwells,nsteps))
self.strati = np.zeros((self.nwells,nsteps))
def run_step(self):
self.strati = self.h[self.iy, self.ix]
self.rate = self.uplift_rate[self.iy, self.ix]
```
# FLux Process
To output the flux out of the model for input into the new 1D marine model developed by Charlie Sobe
```
from fastscape.processes import (SurfaceTopography, RasterGrid2D)
@xs.process
class Flux:
out = xs.variable(dims=(), static=False, intent="out", description="sediment flux", attrs={"units": "km^3/yr"})
h = xs.foreign(SurfaceTopography, 'elevation', intent="in")
u = xs.foreign(DualUplift, 'uplift_rate', intent="in")
a = xs.foreign(RasterGrid2D, 'cell_area', intent="in")
@xs.runtime(args="nsteps")
def initialize(self, nsteps):
self.out = np.zeros(nsteps)
self.prev_dh = 0
@xs.runtime(args=("step_delta"))
def run_step(self, dt):
dh = np.sum(self.h)
self.out = (np.sum(self.u) - (dh-self.prev_dh)/dt)*self.a
# print(self.a, (dh - self.prev_dh)/dt, np.sum(self.u))
self.prev_dh = dh
```
**Model build**
We build the model by removing the diffusion component, adding our new process (SPL_Parameters) and selecting multiple flow direction for the drainage area computation (with $p=1$).
```
from fastscape.processes import (MultipleFlowRouter)
TwoD_model = sediment_model.drop_processes('diffusion').update_processes({'forcing': Periodic_Forcing,
'dualuplift': DualUplift, 'wells': Wells,
'flow': MultipleFlowRouter,
'flux': Flux})
TwoD_model.visualize()
```
**Model setup**
The model is size $nx\times nx$ and the first $nxb$ nodes are set to uplift while the others are subsiding.<br>
Number of time steps is $ntime$ and the number of output is $nout$. Total model run is 10 Myr.<br>
Numbr of wells is nwell
```
nx = 101
ny = 51
nxb = int(2*nx/3)
xl = 100e3
yl = 50e3
xlim = xl*2/3
ntime = 1001
nout = 101
nwell = 9
```
**Model input**
Model input is built using input parameters and others, such as the reference values for Kf, G, m and n, and the size of the model (100x100 km).<br>
Boundary conditions are cyclic in the $y$-direction, no flux at $x=0$ and fixed (base level) at $x=L$.
Now that we have defined a function that takes the period of the climate variations as an input parameter, we can use xsimlab's batch computing optino. If one of the input variables is defined by an array of values with the dimension "batch", at execution, the model will be run as many times as the length of the batch dimension. This will also be done in parallel (using different processors/cores on the computer) if the *parallel* option is activated in the run command. Note that for this to happen, we must import/install *dask*.
```
in_2D_ds = xs.create_setup(
model=TwoD_model,
clocks={
'time': np.linspace(0, 1e7, ntime),
'out': np.linspace(0, 1e7, nout)
},
master_clock='time',
input_vars={
'grid__shape': [ny, nx],
'grid__length': [yl, xl],
'boundary__status': ['fixed_value','core','looped','looped'],
'dualuplift__up': 3e-3,
'dualuplift__down': 1e-4,#('batch', 10**np.linspace(-5,-3,24)),
'dualuplift__xlim': xlim,
'forcing__period': ('batch', [2.e5,1e6,5.e6]),
'forcing__amplitude': 0.5,
'forcing__k0_coef_soil': 1e-5,
'forcing__k0_coef_bedrock': 1e-5,
'forcing__g0_coef_soil': 1,
'forcing__g0_coef_bedrock': 1,
'spl__slope_exp': 1,
'spl__area_exp': 0.4,
'flow__slope_exp': 1,
'wells__wellx': np.linspace(0,xlim,nwell+2)[1:-1],
'wells__welly': np.ones(nwell)*yl/2
},
output_vars={
'topography__elevation': 'out',
'drainage__area': 'out',
'forcing__rate': 'time',
'wells__rate': 'time',
'wells__strati': 'time',
'dualuplift__uplift_rate': 'out',
'flux__out': 'time'
}
)
zgroup = zarr.group("out.zarr", overwrite=True)
```
**Model execution**
We run the model (which can take up to a few minutes depending on computer spped).
```
#with xs.monitoring.ProgressBar():
out_2D_ds = in_2D_ds.xsimlab.run(model=TwoD_model, store=zgroup, batch_dim='batch', parallel=True, scheduler="processes")
```
**Display Results**
We display the model results in 3D including topography and drainage area.
```
app = TopoViz3d(out_2D_ds, canvas_height=600, time_dim="out")
app.components['background_color'].set_color('lightgray')
app.components['vertical_exaggeration'].set_factor(5)
app.components['timestepper'].go_to_time(out_2D_ds.out[-1])
app.show()
```
**Compute stratigraphy**
We compute a stratigraphy along a cross-section at the center of the model.<br>
We also compute the flux out of the model (into the ocean), the flux out of the mountain and the maximum topography of the mountain as a function of time.
Note that the following graphic operations are performed for only one of the three batch models. To specify which one, use ibatch in the next cell.
```
ibatch = 1
ymean = out_2D_ds.y.mean().values
def compute_strati (ds, ymean):
nout, nx = ds.topography__elevation.sel(y=ymean).values.shape
strati = ds.topography__elevation.sel(y=ymean).values
dt = (ds.out[1:].values - ds.out[:-1].values)
for jout in range(1,nout):
strati[:jout-1,:] = strati[:jout-1,:] + ds.dualuplift__uplift_rate.isel(out=jout).sel(y=ymean).values*dt[jout-1]
for iout in range(nout-2, -1, -1):
strati[iout,:] = np.minimum(strati[iout,:], strati[iout+1,:])
return strati
strati_2D = compute_strati (out_2D_ds.isel(batch=ibatch), ymean)
```
We plot the 2D stratigraphy in the middle of the basin, as a synthetic seismic line and as a series of wells, one every four nodes
```
fig, ax = plt.subplots(nrows = 1, ncols = 2, sharex=False, sharey=True, figsize=(32,16))
nfreq_reflector = 1
colors = plt.cm.jet(np.linspace(0,1,nout))
for iout in range(nout-1, -1, -nfreq_reflector):
ax[0].fill_between(out_2D_ds.sel(y=ymean).x[0:nxb], strati_2D[iout,0:nxb], strati_2D[0,0:nxb], color=colors[iout])
ax[0].plot(out_2D_ds.sel(y=ymean).x[0:nxb], strati_2D[iout,0:nxb], color='darkgrey')
ymin = strati_2D[:,nxb-1].min()
ymax = strati_2D[:,nxb-1].max()
ax[0].set_ylim((ymin,ymax))
for iwell in range(0,nxb, 4):
for iout in range(nout-1, -1, -nfreq_reflector):
ax[1].fill_between((iwell, iwell+1), (strati_2D[iout,iwell],strati_2D[iout,iwell]), (strati_2D[0,iwell],strati_2D[0,iwell]), color=colors[iout])
ax[1].plot((iwell, iwell+1), (strati_2D[iout,iwell],strati_2D[iout,iwell]), color='darkgrey')
```
We display the resulting stratigraphic column showing erosion rate estimated from layers thickness as a function of time. This is equivalent to assuming that we can measure the thickness of all preserved layers and assess their age with infinite precition
Function to compute sedimentation rate in a series of wells located in the basin
```
def compute_well_strati (ds):
ntime, nwell = ds.wells__strati.shape
strati = ds.wells__strati.values
sedim_rate = np.empty((ntime-1, nwell))
dt = (ds.time[1:].values - ds.time[:-1].values)
for jout in range(1,ntime):
strati[:jout-1,:] = strati[:jout-1,:] + ds.wells__rate.isel(time=jout).values*dt[jout-1]
for iout in range(ntime-2, -1, -1):
strati[iout,:] = np.minimum(strati[iout,:], strati[iout+1,:])
for well in range(nwell):
sedim_rate[:,well] = (strati[1:,well] - strati[:-1,well])/dt
return sedim_rate
sedim = compute_well_strati(out_2D_ds.isel(batch=ibatch))
```
Compute fluxes out of the system, out of the mountain, channel mobility and maximum topography as a function of time for display/comparison with well deposition rate
```
u2D = out_2D_ds.dualuplift__uplift_rate.isel(batch=ibatch).values
topo = out_2D_ds.topography__elevation.isel(batch=ibatch).values
area = out_2D_ds.drainage__area.isel(batch=ibatch).values
flux_out_2D = np.sum(np.sum(u2D[1:,:,:],1),1)-np.sum(np.sum(topo[1:,:,:] - topo[:-1,:,:], 1), 1)/(out_2D_ds.out.values[1:] - out_2D_ds.out.values[:-1])
flux_out_mountain = np.sum(np.sum(u2D[1:,:,nxb:],1),1)-np.sum(np.sum(topo[1:,:,nxb:] - topo[:-1,:,nxb:], 1), 1)/(out_2D_ds.out.values[1:] - out_2D_ds.out.values[:-1])
channel_mobility = np.sum(np.abs(area[1:,:, int(nxb/2)]-area[:-1,:, int(nxb/2)]),1)/(out_2D_ds.out.values[1:] - out_2D_ds.out.values[:-1])
topo_2D = topo.max(1).max(1)
fig, ax = plt.subplots(nrows = 1, ncols = nwell+4, sharex=False, sharey=True, figsize=(32,16))
precip = out_2D_ds.forcing__rate.isel(batch=ibatch)
tmax = out_2D_ds.time.values.max()
time = tmax - out_2D_ds.time.values
out = tmax - out_2D_ds.out.values
for well in range(nwell):
kwell = well + 1
ax[kwell].plot(precip/precip.max()*sedim[:,well].max(), time, alpha=0.5)
ax[kwell].plot(sedim[:,well], time[:-1])
ax[kwell].set_ylim(tmax,0)
ax[kwell].set_title("Well "+str(kwell))
ax[0].plot(precip/precip.max()*flux_out_2D.max(), time, alpha=0.5)
ax[0].plot(flux_out_2D, out[:-1])
ax[0].set_ylim(tmax,0)
ax[0].set_title("Flux out")
ax[-3].plot(precip/precip.max()*channel_mobility.max(), time, alpha=0.5)
ax[-3].plot(channel_mobility, out[:-1])
ax[-3].set_ylim(tmax,0)
ax[-3].set_title("Channel mobility")
ax[-2].plot(precip/precip.max()*flux_out_mountain.max(), time, alpha=0.5)
ax[-2].plot(flux_out_mountain, out[:-1])
ax[-2].set_ylim(tmax,0)
ax[-2].set_title("Flux mountain")
ax[-1].plot(precip/precip.max()*topo_2D.max(), time, alpha=0.5)
ax[-1].plot(topo_2D, out)
ax[-1].set_ylim(tmax,0)
ax[-1].set_title("Topo")
ax[0].set_ylabel("Time b.p. (yr)");
import Charlie_Model
Charlie_Model.marine.visualize(show_inputs=True)
```
We now prepare a setup consisting of a basement geometry made of a steep ramp down next to a less steep ramp up.
We also transform the flux output into an output for the marine model.
We display both.
We also prepare a sea level array to transform the periodic climate fluctuations (forcing) into a sea level signal. We change the sign of the climate signal (high precipitation assumed during cold period and thus low sea level) but this could be reversed, depending on the region of Earth that is modeled.
```
length = 1e6
spacing = length/nx
br = -np.ones((ntime, nx))*6e3
nxflat = int(nx/5)
br[:,:nxflat] = np.linspace(0,-6.e3,nxflat)
br[:,nxflat:] = np.linspace(-6.e3,-5.e3,nx-nxflat)
bedrock_elev_array = xr.DataArray(br, dims=['time', 'x'])
initial_bedrock = bedrock_elev_array[0, :]
qs_array = xr.DataArray(np.where(out_2D_ds.flux__out.isel(batch=ibatch).values>0,
out_2D_ds.flux__out.isel(batch=ibatch).values,0), dims=['time'])
sea_level = xr.DataArray(-4*out_2D_ds.forcing__rate.isel(batch=ibatch).values, dims=['time'])
fig, ax = plt.subplots(nrows = 1, ncols = 2, sharex=False, sharey=False, figsize=(32,10))
ax[0].plot(initial_bedrock)
ax[1].plot(qs_array)
noutp = nout
```
Now we prepare the model setup and run it.
```
in_ds = xs.create_setup(
...: model=Charlie_Model.marine,
...: clocks={
...: 'time': np.linspace(0, 1e7, ntime),
...: 'otime': np.linspace(0, 1e7, noutp)
...: },
...: master_clock='time',
...: input_vars={
...: 'grid': {'length': length, 'spacing': spacing},
'init': {'init_br': initial_bedrock},
'erode': {
'k_factor': 0.2,
'k_depth_scale': 100.,
's_crit': 0.05,
'travel_dist': 200000.,
'sed_porosity': 0.56,
'sed_porosity_depth_scale': 2830.,
'sea_level': sea_level,
'qs_in': qs_array,
'basin_width': 1e5
},
'profile': {
'br': bedrock_elev_array
},
},
output_vars={'profile__z': 'otime', 'profile__br': 'otime', 'profile__h': 'otime'}
)
zgroup_marine = zarr.group("out_Marine.zarr", overwrite=True)
with xs.monitoring.ProgressBar():
out_ds = in_ds.xsimlab.run(model=Charlie_Model.marine, store=zgroup_marine)
```
We compute the 1D stratigraphy
```
strati = np.zeros((noutp,nx))
for iout in range(noutp):
strati[iout,:] = out_ds.profile__z.isel(otime=iout)
for iout in range(noutp-2, -1, -1):
strati[iout,:] = np.minimum(strati[iout,:], strati[iout+1,:])
```
And plot it
```
fig, ax = plt.subplots(nrows = 2, ncols = 1, sharex=False, sharey=False, figsize=(32,20))
colors = plt.cm.rainbow(np.linspace(0,1,noutp))
for iout in range(noutp-1, -1, -5):
ax[0].fill_between(out_ds.x, out_ds.profile__br[iout,:], strati[iout,:], color=colors[iout])
ax[0].plot(out_ds.x, strati[iout,:], color='darkgrey')
for iout in range(noutp-1, -1, -2):
ax[1].fill_between(out_ds.x, out_ds.profile__br[iout,:], strati[iout,:], color=colors[iout])
ax[1].plot(out_ds.x, strati[iout,:], color='darkgrey')
ax[1].set_xlim((0, 200e3))
ax[1].set_ylim((-1e3, 0));
```
| github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.

# Register model and deploy locally
This example shows how to deploy a web service in step-by-step fashion:
1. Register model
2. Deploy the image as a web service in a local Docker container.
3. Quickly test changes to your entry script by reloading the local service.
4. Optionally, you can also make changes to model, conda or extra_docker_file_steps and update local service
## Prerequisites
If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, make sure you go through the [configuration](../../../configuration.ipynb) Notebook first if you haven't.
```
# Check core SDK version number
import azureml.core
print("SDK version:", azureml.core.VERSION)
```
## Initialize Workspace
Initialize a workspace object from persisted configuration.
```
from azureml.core import Workspace
ws = Workspace.from_config()
print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n')
```
## Register Model
You can add tags and descriptions to your models. we are using `sklearn_regression_model.pkl` file in the current directory as a model with the name `sklearn_regression_model_local` in the workspace.
Using tags, you can track useful information such as the name and version of the machine learning library used to train the model, framework, category, target customer etc. Note that tags must be alphanumeric.
```
from azureml.core.model import Model
model = Model.register(model_path="sklearn_regression_model.pkl",
model_name="sklearn_regression_model_local",
tags={'area': "diabetes", 'type': "regression"},
description="Ridge regression model to predict diabetes",
workspace=ws)
```
## Create Environment
```
from azureml.core.conda_dependencies import CondaDependencies
from azureml.core.environment import Environment
environment = Environment("LocalDeploy")
environment.python.conda_dependencies = CondaDependencies("myenv.yml")
```
## Create Inference Configuration
```
from azureml.core.model import InferenceConfig
inference_config = InferenceConfig(entry_script="score.py",
environment=environment)
```
## Model Profiling
Profile your model to understand how much CPU and memory the service, created as a result of its deployment, will need. Profiling returns information such as CPU usage, memory usage, and response latency. It also provides a CPU and memory recommendation based on the resource usage. You can profile your model (or more precisely the service built based on your model) on any CPU and/or memory combination where 0.1 <= CPU <= 3.5 and 0.1GB <= memory <= 15GB. If you do not provide a CPU and/or memory requirement, we will test it on the default configuration of 3.5 CPU and 15GB memory.
In order to profile your model you will need:
- a registered model
- an entry script
- an inference configuration
- a single column tabular dataset, where each row contains a string representing sample request data sent to the service.
At this point we only support profiling of services that expect their request data to be a string, for example: string serialized json, text, string serialized image, etc. The content of each row of the dataset (string) will be put into the body of the HTTP request and sent to the service encapsulating the model for scoring.
Below is an example of how you can construct an input dataset to profile a service which expects its incoming requests to contain serialized json. In this case we created a dataset based one hundred instances of the same request data. In real world scenarios however, we suggest that you use larger datasets with various inputs, especially if your model resource usage/behavior is input dependent.
```
import json
from azureml.core import Datastore
from azureml.core.dataset import Dataset
from azureml.data import dataset_type_definitions
# create a string that can be put in the body of the request
serialized_input_json = json.dumps({
'data': [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
]
})
dataset_content = []
for i in range(100):
dataset_content.append(serialized_input_json)
dataset_content = '\n'.join(dataset_content)
file_name = 'sample_request_data_diabetes.txt'
f = open(file_name, 'w')
f.write(dataset_content)
f.close()
# upload the txt file created above to the Datastore and create a dataset from it
data_store = Datastore.get_default(ws)
data_store.upload_files(['./' + file_name], target_path='sample_request_data_diabetes')
datastore_path = [(data_store, 'sample_request_data_diabetes' +'/' + file_name)]
sample_request_data_diabetes = Dataset.Tabular.from_delimited_files(
datastore_path,
separator='\n',
infer_column_types=True,
header=dataset_type_definitions.PromoteHeadersBehavior.NO_HEADERS)
sample_request_data_diabetes = sample_request_data_diabetes.register(workspace=ws,
name='sample_request_data_diabetes',
create_new_version=True)
```
Now that we have an input dataset we are ready to go ahead with profiling. In this case we are testing the previously introduced sklearn regression model on 1 CPU and 0.5 GB memory. The memory usage and recommendation presented in the result is measured in Gigabytes. The CPU usage and recommendation is measured in CPU cores.
```
from datetime import datetime
from azureml.core import Environment
from azureml.core.conda_dependencies import CondaDependencies
from azureml.core.model import Model, InferenceConfig
environment = Environment('my-sklearn-environment')
environment.python.conda_dependencies = CondaDependencies.create(pip_packages=[
'azureml-defaults',
'inference-schema[numpy-support]',
'joblib',
'numpy',
'scikit-learn'
])
inference_config = InferenceConfig(entry_script='score.py', environment=environment)
# if cpu and memory_in_gb parameters are not provided
# the model will be profiled on default configuration of
# 3.5CPU and 15GB memory
profile = Model.profile(ws,
'profile-%s' % datetime.now().strftime('%m%d%Y-%H%M%S'),
[model],
inference_config,
input_dataset=sample_request_data_diabetes,
cpu=1.0,
memory_in_gb=0.5)
profile.wait_for_completion(True)
details = profile.get_details()
```
## Deploy Model as a Local Docker Web Service
*Make sure you have Docker installed and running.*
Note that the service creation can take few minutes.
NOTE:
The Docker image runs as a Linux container. If you are running Docker for Windows, you need to ensure the Linux Engine is running:
# PowerShell command to switch to Linux engine
& 'C:\Program Files\Docker\Docker\DockerCli.exe' -SwitchLinuxEngine
```
from azureml.core.webservice import LocalWebservice
# This is optional, if not provided Docker will choose a random unused port.
deployment_config = LocalWebservice.deploy_configuration(port=6789)
local_service = Model.deploy(ws, "test", [model], inference_config, deployment_config)
local_service.wait_for_deployment()
print('Local service port: {}'.format(local_service.port))
```
## Check Status and Get Container Logs
```
print(local_service.get_logs())
```
## Test Web Service
Call the web service with some input data to get a prediction.
```
import json
sample_input = json.dumps({
'data': [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
]
})
sample_input = bytes(sample_input, encoding='utf-8')
local_service.run(input_data=sample_input)
```
## Reload Service
You can update your score.py file and then call `reload()` to quickly restart the service. This will only reload your execution script and dependency files, it will not rebuild the underlying Docker image. As a result, `reload()` is fast, but if you do need to rebuild the image -- to add a new Conda or pip package, for instance -- you will have to call `update()`, instead (see below).
```
%%writefile score.py
import os
import pickle
import json
import numpy as np
from sklearn.externals import joblib
from sklearn.linear_model import Ridge
from inference_schema.schema_decorators import input_schema, output_schema
from inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType
def init():
global model
# AZUREML_MODEL_DIR is an environment variable created during deployment.
# It is the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION)
# For multiple models, it points to the folder containing all deployed models (./azureml-models)
model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'sklearn_regression_model.pkl')
# deserialize the model file back into a sklearn model
model = joblib.load(model_path)
input_sample = np.array([[10,9,8,7,6,5,4,3,2,1]])
output_sample = np.array([3726.995])
@input_schema('data', NumpyParameterType(input_sample))
@output_schema(NumpyParameterType(output_sample))
def run(data):
try:
result = model.predict(data)
# you can return any datatype as long as it is JSON-serializable
return 'hello from updated score.py'
except Exception as e:
error = str(e)
return error
local_service.reload()
print("--------------------------------------------------------------")
# After calling reload(), run() will return the updated message.
local_service.run(input_data=sample_input)
```
## Update Service
If you want to change your model(s), Conda dependencies, or deployment configuration, call `update()` to rebuild the Docker image.
```python
local_service.update(models=[SomeOtherModelObject],
inference_config=inference_config,
deployment_config=local_config)
```
## Delete Service
```
local_service.delete()
```
| github_jupyter |
# Regression and Other Stories: Simulation
Simulation of probability models. See Chapter 5 in Regression and Other Stories.
```
import arviz as az
from bambi import Model
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
```
### Simulate how many girls in 400 births?
```
n_girls = stats.binom(400, .488).rvs(1)
print(n_girls)
```
### Repeat simulation 1000 times
```
# With scipy.stats we do not need a loop to conduct 1000 simulations, but instead can specify it by changing the argument
# to rvs
n_sims = 1000
n_girls = stats.binom(400, .488).rvs(n_sims)
```
### Plot
```
az.plot_dist(n_girls);
```
### Accounting for twins
```
birth_types = pd.Series(["fraternal twin","identical twin","single birth"]) \
.sample(n=400,replace=True, weights=(1/125, 1/300, 1-1/125-1/300))
birth_types.value_counts()
```
### Plot
```
# For this smaller dataset we'll use pandas apply. For seriously large datasets consider ufuncs or other optimizations
# outside of the scope of this
def birthtype(birth_type):
if birth_type == "single birth":
counts = stats.binom(1, 0.488).rvs(1)
elif birth_type == "identical twin":
counts = 2*stats.binom(1, 0.495).rvs(1)
elif birth_type == "fraternal twin":
counts = stats.binom(2, 0.495).rvs(1)
return counts.squeeze()
girls = birth_types.apply(birthtype)
girls.head()
az.plot_dist(n_girls, kind="hist");
```
### Simulation of continuous and mixed discrete/continuous models
```
n_sims = 1000
y1 = stats.norm(3, .5).rvs(n_sims)
y2 = np.exp(y1)
y3 = stats.binom(20, .6).rvs(n_sims)
y4 = stats.poisson(5).rvs(n_sims)
```
### Plot
```
fig, axes = plt.subplots(2,2, figsize=(8,8), constrained_layout=True)
axes[0][0].hist(y1, bins = np.arange(y1.min(), y1.max() + .2, .2))
axes[0][0].set_title("1000 draws from a normal dist. \n with mean 3, sd .5")
axes[0][1].hist(y2, bins = np.arange(0, y2.max() + 5, 5))
axes[0][1].set_title("1000 draws from corresponding \n lognormal dist")
axes[1][0].hist(y3, bins = np.arange(-.5, 20.5, 1))
axes[1][0].set_title("1000 draws from binomial distt with \n 20 tries probability .6")
axes[1][1].hist(y4, bins = np.arange(-.5, y4.max() + 1, 1))
axes[1][1].set_title("1000 draws from the Poisson dist \n with mean 5");
```
### Generate the height of one randomly chosen adult
```
male = stats.binom(1, .48).rvs(1)
height = np.where(male ==1, stats.norm(69.1, 2.9).rvs(1), stats.norm(63.7, 2.7).rvs(1))
male, height
```
### Select 10 adults at random
```
N = 10
male = stats.binom(1, .48).rvs(N)
height = np.where(male==1, stats.norm(69.1, 2.9).rvs(N), stats.norm(63.7, 2.7).rvs(N))
avg_height = height.mean()
avg_height
```
### Repeat the simulation 1000 times
```
n_sims = 1000
avg_height = np.empty(n_sims)
for i in range(n_sims):
N=10
male = stats.binom(1, .48).rvs(N)
height = np.where(male==1, stats.norm(69.1, 2.9).rvs(N), stats.norm(63.7, 2.7).rvs(N))
avg_height[i] = height.mean()
ax = az.plot_dist(avg_height, kind="hist")
ax.set_title("Dist of average height of 10 adults");
```
### The maximum height of the 10 people
```
def height_sim(n):
male = stats.binom(1, .48).rvs(N)
height = np.where(male==1, stats.norm(69.1, 2.9).rvs(N), stats.norm(63.7, 2.7).rvs(N))
max_height = height.max()
return max_height
max_height = np.array([height_sim(10) for _ in range(1000)])
az.plot_dist(max_height, kind="hist");
```
| github_jupyter |
# First steps
Programming is about getting the computer to do the calculation for you. This is needed when the calculation is long and has many repetitive steps. It does *not* mean that you can get the computer to understand things for you: usually you need to understand the steps before telling the computer what to do!
Using a computer, particularly for mathematical or scientific purposes, involves a lot more than programming. There is also
* *Algorithmic thinking*: understanding how to convert the solution to a problem into a sequence of steps that can be followed without further explanation.
* *Efficient implementation* and *complexity*: there are many ways to solve a given problem, which will give equivalent answers in principle. In reality, some solutions will solve some problems to a reasonable accuracy in reasonable time, and it can be important to be able to check which solutions work in which cases.
* *Effective implementation*: solving a problem on a computer *once* is great. Being able to re-use your solution on many problems is much better. Being able to give your code to anybody else, and it working for them, or saying *why* it won't work, without further input from you, is best.
* *Reproducible science*: in principle, any scientific result should be able to be checked by somebody else. With complex scientific code, presenting and communicating its contents so that others can reproduce results is important and not always easy.
First, we will get the computer to do *something*, and later worry about doing it efficiently and effectively. Your time is more valuable than the computer's (literally: compare the [hourly cost of computer time through eg Amazon](https://aws.amazon.com/ec2/pricing/), typically *much* less than $5 per hour, against the minimum wage). We want the computer doing the work, and only when that wastes your time should you worry about the speed of the calculation.
# How to use these notes
## The material
The four essential sections are on the basics, programs, loops and flow control, and basic plotting. You should work through the notes by typing in the commands as they appear, ensuring that you understand what's going on, and seeing where you make mistakes. At the end of each section, try the exercises that you think you can tackle. Also look back at previous exercises and see if you can solve them more straightforwardly with your additional knowledge.
The section on classes should be read before reading the other sections: the details of creating your own classes won't be needed for later sections, but some understanding is important. The section on scientific Python is then the most important and should be explored in detail. At this point you should be able to tackle most of the exercises.
The sections on symbolic Python and statistics should then be covered to get an overview of how Python can be used in these areas. The section on LaTeX is not directly related to programming but is essential for writing mathematical documents. Further sections are useful as your codes get more complex, but initially are less important.
## How to work when coding
When working on code it is often very useful to work in pairs, or groups. Talk about what you're doing, and why you're doing it. When something goes wrong, check with other people, or [explain to them what you're trying to do (rubber duck debugging)](https://en.wikipedia.org/wiki/Rubber_duck_debugging). When working on exercises, [use pair programming techniques](http://www.wikihow.com/Pair-Program). If there's more than one way of doing something, try them all and see which you think is best, and discuss why.
There is no "one right way" to code, but well documented, easy to understand, clearly written code that someone else can follow as well is always a good start.
# Python
To introduce programming we will use the Python programming language. It's a good general purpose language with lots of tools and libraries available, and it's free. It's a solid choice for learning programming, and for testing new code.
## Using Python on University machines
A number of Python tools are available on a standard university desktop machine. We will mostly be using Python through spyder, which allows us to write, run, test and debug python code in one place. To launch spyder, either type `spyder` in the search bar, or go to `Start`, then `All Programs`, then `Programming Languages`, then `Anaconda`, then choose `spyder`.
## Using Python on your own machine
As Python is free you can install and run it on any machine (or tablet, or phone) you like. In fact, many will have Python already installed, for the use of other software. However, for programming, it is best to have an installation that all works together, which you can easily experiment with, and which won't break other programs if you change something. For these reasons, we recommend you install the [anaconda distribution](http://docs.continuum.io/anaconda/).
### Anaconda
If you have enough bandwidth and time (you will be downloading about 1G of software) then you can use the [Anaconda graphical installer](https://www.continuum.io/downloads). There are two versions of Python: a Python `2.X` and a Python `3.X`. There are small differences between the two. Everything we show here will work on either version. We will be using the `3.X` version.
The Anaconda package installs both the essential Python package and a large amount of useful Python software. It will put a launcher icon on your desktop. Clicking on the launcher will bring up a window listing a number of applications: we will be using `spyder` as seen below.
### miniconda
If you do not want to download all the Python packages, but only the essential ones, there is a smaller version of Anaconda, called miniconda. First, [download the miniconda package](http://conda.pydata.org/miniconda.html) for your computer. Again, we will be using the `3.X` version.
The miniconda package installs the basic Python and little else. There are a number of useful packages that we will use. You can install those using the `conda` app (either via the launcher, or via the command line). But before doing that, it is best to create an environment to install them in, which you can modify without causing problems.
### Environments
Packages may rely on other packages, and may rely on *specific versions* of other packages in order to work. This can lead to "dependency hell", when you need (for different purposes) package `A` and package `B` which rely on conflicting versions of package `C`.
The answer to this is *environments*, which allow you to organize your different packages to minimize conflicts. Environments are like folders, and you have one for each project you are working on. That way, you ensure that updating or installing packages for one project does not cause problems for a different project.
To get the most out of environments, we need to use the command line, or terminal.
#### Terminals
A *terminal*, or a [*command prompt window*](http://windows.microsoft.com/en-gb/windows-vista/open-a-command-prompt-window), is a window where commands can be typed in to directly run commands or affect files. On Windows you select the `Command Prompt` from the Accessories menu. On Mac or Linux system you open a terminal or an XTerm. Inside the terminal you can change directories using the `cd` command, and run commands associated with Anaconda or miniconda using the `conda` command.
#### Creating the environment
We will create a single environment called `labs`. If you are running on a Mac or on Linux, open a terminal. If on Windows, use a command prompt. Then type
```bash
conda create -n labs python=3
```
This creates the new environment, and installs the basic `python` package in the `python 3.X` flavour. It does not activate the environment. In order to work within this environment, if using Windows type
```bash
activate labs
```
If using Mac or Linux type
```bash
source activate labs
```
Then any command launched from the terminal or command prompt will use the packages in this environment.
### Packages
After creating the environment, and activating it, the key packages that need installing (if using miniconda; they are all installed with the full Anaconda) are:
* `ipython`
* `numpy`
* `matplotlib`
* `scipy`
* `spyder`
* `spyder-app`
* `sympy`
Other packages that will be useful are
* `jupyter`
* `nose`
* `numba`
* `pandas`
The command to install new packages is `conda install`. So, to install the packages above type (or copy and paste) first
```bash
activate labs
```
if on Windows, or
```bash
source activate labs
```
if on Mac or Linux, and then type
```bash
conda install ipython numpy matplotlib scipy spyder spyder-app sympy \
jupyter nose numba pandas
```
**Note**: the '`\`' backslash character should continue an overly long line: if you are typing and not copying and pasting this should be unnecessary.
This will download and install a lot of additional packages that are needed; just agree and continue.
# Spyder
There are many ways of writing and running Python code. If you open a terminal (on Mac or Linux; on Windows, this would be a Command Prompt) you can type `python` or `ipython` to launch a very bare bones *console*. This allows you to enter code which it will then run.
More helpful alternatives are *Integrated Development Environments* (IDEs) or the *notebook*. The [Jupyter notebook](https://jupyter.org/) (previously called the [IPython notebook](http://ipython.org/notebook.html)) is browser based and very powerful for exploratory computing. To run, type `jupyter notebook` in the terminal prompt.
However, when just getting started, or when writing large codes, IDEs are a better alternative. A simple IDE is `spyder` which we will use here. To launch, either select `spyder` from the appropriate menu, or type `spyder` at the terminal prompt.
You should then see a screen something like the figure (without the annotations).

The four essential parts of the screen are outlined.
1. The console (bottom right, marked in blue). You can work *interactively* here. Code run, either interactively or from the editor, will output any results here. Error messages will be reported here. There are two types of console: a Python console, and an IPython console. Both will run Python code, but the IPython console is easier to use.
2. The editor (left, marked in red). You can write code to be saved to file or run here. This will suggest problems with syntax and has features to help debug and give additional information.
3. The inspector (top right, marked in green). Can display detailed help on specific objects (or functions, or...) - the *Object inspector*, or can display detailed information on the variables that are currently defined - the *Variable inspector*. Extremely useful when debugging.
4. The working directory (marked in yellow). When running a code this is the first place that `spyder` looks. You should ensure that the working directory is set to the location where the file is.
For further information on using and setting up `spyder`, see [this tutorial](http://www.southampton.ac.uk/~fangohr/blog/spyder-the-python-ide.html).
## Tab completion
A crucial feature of IPython and spyder that saves time and reduces errors is *tab completion*. When typing anything, try pressing the tab key. This will either automatically complete the name of the variable (or function, or class), or will present a list of options. This is one way of finding out what functions are available - press tab and it will list them all! By typing the first few characters and then pressing tab, you can rapidly narrow down the options.
## Help
There are many ways of getting help. The most useful are:
* Type `help(<thing>)`. Works in the console.
* Type `<thing>?` or `<thing>??`. Works in the console.
* Type the name in the Object Inspector. Works in spyder only.
* Google it. Pay particular attention to the online documentation and sites such as stackoverflow.
# Reading list
There's a lot of material related to Python online and in the library. None are essential, but lots may be useful. The particular books recommended as a first look are
* Langtangen, *A Primer on Scientific Programming with Python*. Detailed, aimed more towards mathematicians than many others.
* Newman, *Computational Physics*. Really aimed at teaching numerical algorithms rather than programming, but there's lots of useful examples at a good level.
* Scopatz & Huff, *Effective Computation in Physics*. Covers a lot more material than just Python, not exactly aimed at mathematics, but essential background for computational research in the sciences.
* Saha, *Doing Math with Python*. Covers more symbolic mathematics and assumes more Python background, but has lots of excellent exercises at the right level.
# Versions
These notes have been constructed using the following versions of Python and related packages:
```
%load_ext watermark
%watermark -v -m -g -p numpy,scipy,matplotlib,sympy
```
| github_jupyter |
# Credit Card Fraud Detection using Machine Learning
### Import libraries
```
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from catboost import CatBoostClassifier
import keras
from keras.models import Sequential
from keras.layers import Dense, InputLayer, Dropout, Flatten, Activation, Input
from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (10, 10)
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
```
### Import dataset (https://www.kaggle.com/mlg-ulb/creditcardfraud)
```
df = pd.read_csv('../creditcard.csv')
df = df.dropna()
df = df.drop('Time', axis = 1)
```
### Investigate Class Sizes
```
groups = df.groupby('Class')
fraud = (groups.get_group(1).shape[0] / df.shape[0]) * 100
non_fraud = (groups.get_group(0).shape[0] / df.shape[0]) * 100
print('Percent Fraud: ' + str(fraud) + '%')
print('Percent Not Fraud ' + str(non_fraud) + '%')
```
### Split data into a train and holdout set
```
df_size = df.shape[0]
test_size = int(df_size * .3)
train_size = df_size - test_size
train_df = df.head(train_size)
test_df = df.tail(test_size)
X_train = train_df.drop('Class', axis = 1)
Y_train = train_df['Class']
X_test = test_df.drop('Class', axis = 1)
Y_test = test_df['Class']
```
### Apply a standard scalar to our data
```
for feat in X_train.columns.values:
ss = StandardScaler()
X_train[feat] = ss.fit_transform(X_train[feat].values.reshape(-1,1))
X_test[feat] = ss.transform(X_test[feat].values.reshape(-1,1))
```
### Fit Random Forest Classifier
```
rf = RandomForestClassifier()
rf.fit(X_train, Y_train)
probabilities = rf.predict_proba(X_test)
y_pred_rf = probabilities[:,1]
```
### Evaluate Performance
```
fpr_rf, tpr_rf, thresholds_rf = roc_curve(Y_test, y_pred_rf)
auc_rf = auc(fpr_rf, tpr_rf)
plt.plot(100*fpr_rf, 100*tpr_rf, label= 'Random Forest (area = {:.3f})'.format(auc_rf), linewidth=2, color = colors[0])
plt.xlabel('False positives [%]')
plt.ylabel('True positives [%]')
plt.xlim([0,30])
plt.ylim([60,100])
plt.grid(True)
ax = plt.gca()
ax.set_aspect('equal')
plt.title('Random Forest Model Performance')
plt.legend(loc='best')
```
### Fit CatBoost Classifier
```
cat = CatBoostClassifier()
cat.fit(X_train, Y_train)
y_pred_cat = cat.predict(X_test, prediction_type='RawFormulaVal')
```
### Evaluate performacne
```
fpr_cat, tpr_cat, thresholds_cat = roc_curve(Y_test, y_pred_cat)
auc_cat = auc(fpr_cat, tpr_cat)
plt.plot(100*fpr_cat, 100*tpr_cat, label= 'CatBoost (area = {:.3f})'.format(auc_cat), linewidth=2, color = colors[1])
plt.xlabel('False positives [%]')
plt.ylabel('True positives [%]')
plt.xlim([0,30])
plt.ylim([60,100])
plt.grid(True)
ax = plt.gca()
ax.set_aspect('equal')
plt.title('CatBoost Model Performance')
plt.legend(loc='best')
```
### Design and fit Deep Neural Network
```
#Design and compile model
DNN = Sequential()
DNN.add(Input(shape=(X_train.shape[1],)))
DNN.add(Dense(100, activation='relu'))
DNN.add(Dropout(0.5))
DNN.add(Dense(100, activation='relu'))
DNN.add(Dropout(0.5))
DNN.add(Dense(10, activation='relu'))
DNN.add(Dense(1, activation='sigmoid'))
DNN.compile(loss='binary_crossentropy', optimizer='adam', metrics = keras.metrics.AUC(name='auc'))
#fit model
DNN.fit(X_train, Y_train, epochs=10)
#generate prediction probabilities on test data
y_pred_DNN = DNN.predict(X_test).ravel()
```
### Evaluate Performance
```
fpr_DNN, tpr_DNN, thresholds_DNN = roc_curve(Y_test, y_pred_DNN)
auc_DNN = auc(fpr_DNN, tpr_DNN)
plt.plot(100*fpr_DNN, 100*tpr_DNN, label= 'DNN (area = {:.3f})'.format(auc_DNN), linewidth=2, color = colors[2])
plt.xlabel('False positives [%]')
plt.ylabel('True positives [%]')
plt.xlim([0,30])
plt.ylim([60,100])
plt.grid(True)
ax = plt.gca()
ax.set_aspect('equal')
plt.title('Deep Neural Network Model Performance')
plt.legend(loc='best')
```
### Fit Isolation Forest
```
iforest = IsolationForest()
iforest.fit(X_train)
y_pred_iforest = - iforest.decision_function(X_test)
```
### Evaulate Performance
```
fpr_iforest, tpr_iforest, thresholds__iforest = roc_curve(Y_test, y_pred_iforest)
auc_iforest = auc(fpr_iforest, tpr_iforest)
plt.plot(100*fpr_iforest, 100*tpr_iforest, label= 'iForest (area = {:.3f})'.format(auc_iforest), linewidth=2, color = colors[3])
plt.xlabel('False positives [%]')
plt.ylabel('True positives [%]')
plt.xlim([0,30])
plt.ylim([60,100])
plt.grid(True)
ax = plt.gca()
ax.set_aspect('equal')
plt.title('Isolation Forest Model Performance')
plt.legend(loc='best')
```
### Compare performance across all models
```
plt.plot(100*fpr_rf, 100*tpr_rf, label= 'Random Forest (area = {:.3f})'.format(auc_rf), linewidth=2, color = colors[0])
plt.plot(100*fpr_cat, 100*tpr_cat, label= 'CatBoost (area = {:.3f})'.format(auc_cat), linewidth=2, color = colors[1])
plt.plot(100*fpr_DNN, 100*tpr_DNN, label= 'DNN (area = {:.3f})'.format(auc_DNN), linewidth=2, color = colors[2])
plt.plot(100*fpr_iforest, 100*tpr_iforest, label= 'iForest (area = {:.3f})'.format(auc_iforest), linewidth=2, color = colors[3])
plt.xlabel('False positives [%]')
plt.ylabel('True positives [%]')
plt.xlim([0,30])
plt.ylim([60,100])
plt.grid(True)
ax = plt.gca()
ax.set_aspect('equal')
plt.title('Model Comparison')
plt.legend(loc='best')
```
| github_jupyter |
<center>
<img src="https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" />
</center>
# **SpaceX Falcon 9 first stage Landing Prediction**
# Lab 1: Collecting the data
Estimated time needed: **45** minutes
In this capstone, we will predict if the Falcon 9 first stage will land successfully. SpaceX advertises Falcon 9 rocket launches on its website with a cost of 62 million dollars; other providers cost upward of 165 million dollars each, much of the savings is because SpaceX can reuse the first stage. Therefore if we can determine if the first stage will land, we can determine the cost of a launch. This information can be used if an alternate company wants to bid against SpaceX for a rocket launch. In this lab, you will collect and make sure the data is in the correct format from an API. The following is an example of a successful and launch.

Several examples of an unsuccessful landing are shown here:

Most unsuccessful landings are planned. Space X performs a controlled landing in the oceans.
## Objectives
In this lab, you will make a get request to the SpaceX API. You will also do some basic data wrangling and formating.
* Request to the SpaceX API
* Clean the requested data
***
## Import Libraries and Define Auxiliary Functions
We will import the following libraries into the lab
```
# Requests allows us to make HTTP requests which we will use to get data from an API
import requests
# Pandas is a software library written for the Python programming language for data manipulation and analysis.
import pandas as pd
# NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays
import numpy as np
# Datetime is a library that allows us to represent dates
import datetime
# Setting this option will print all collumns of a dataframe
pd.set_option('display.max_columns', None)
# Setting this option will print all of the data in a feature
pd.set_option('display.max_colwidth', None)
```
Below we will define a series of helper functions that will help us use the API to extract information using identification numbers in the launch data.
From the <code>rocket</code> column we would like to learn the booster name.
```
# Takes the dataset and uses the rocket column to call the API and append the data to the list
def getBoosterVersion(data):
for x in data['rocket']:
response = requests.get("https://api.spacexdata.com/v4/rockets/"+str(x)).json()
BoosterVersion.append(response['name'])
```
From the <code>launchpad</code> we would like to know the name of the launch site being used, the logitude, and the latitude.
```
# Takes the dataset and uses the launchpad column to call the API and append the data to the list
def getLaunchSite(data):
for x in data['launchpad']:
response = requests.get("https://api.spacexdata.com/v4/launchpads/"+str(x)).json()
Longitude.append(response['longitude'])
Latitude.append(response['latitude'])
LaunchSite.append(response['name'])
```
From the <code>payload</code> we would like to learn the mass of the payload and the orbit that it is going to.
```
# Takes the dataset and uses the payloads column to call the API and append the data to the lists
def getPayloadData(data):
for load in data['payloads']:
response = requests.get("https://api.spacexdata.com/v4/payloads/"+load).json()
PayloadMass.append(response['mass_kg'])
Orbit.append(response['orbit'])
```
From <code>cores</code> we would like to learn the outcome of the landing, the type of the landing, number of flights with that core, whether gridfins were used, wheter the core is reused, wheter legs were used, the landing pad used, the block of the core which is a number used to seperate version of cores, the number of times this specific core has been reused, and the serial of the core.
```
# Takes the dataset and uses the cores column to call the API and append the data to the lists
def getCoreData(data):
for core in data['cores']:
if core['core'] != None:
response = requests.get("https://api.spacexdata.com/v4/cores/"+core['core']).json()
Block.append(response['block'])
ReusedCount.append(response['reuse_count'])
Serial.append(response['serial'])
else:
Block.append(None)
ReusedCount.append(None)
Serial.append(None)
Outcome.append(str(core['landing_success'])+' '+str(core['landing_type']))
Flights.append(core['flight'])
GridFins.append(core['gridfins'])
Reused.append(core['reused'])
Legs.append(core['legs'])
LandingPad.append(core['landpad'])
```
Now let's start requesting rocket launch data from SpaceX API with the following URL:
```
spacex_url="https://api.spacexdata.com/v4/launches/past"
response = requests.get(spacex_url)
```
Check the content of the response
```
print(response.content)
```
You should see the response contains massive information about SpaceX launches. Next, let's try to discover some more relevant information for this project.
### Task 1: Request and parse the SpaceX launch data using the GET request
To make the requested JSON results more consistent, we will use the following static response object for this project:
```
static_json_url='https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/API_call_spacex_api.json'
```
We should see that the request was successfull with the 200 status response code
```
response.status_code
```
Now we decode the response content as a Json using <code>.json()</code> and turn it into a Pandas dataframe using <code>.json_normalize()</code>
```
# Use json_normalize meethod to convert the json result into a dataframe
data = pd.json_normalize(response.json())
data
```
Using the dataframe <code>data</code> print the first 5 rows
```
# Get the head of the dataframe
data.head(5)
```
You will notice that a lot of the data are IDs. For example the rocket column has no information about the rocket just an identification number.
We will now use the API again to get information about the launches using the IDs given for each launch. Specifically we will be using columns <code>rocket</code>, <code>payloads</code>, <code>launchpad</code>, and <code>cores</code>.
```
# Lets take a subset of our dataframe keeping only the features we want and the flight number, and date_utc.
data = data[['rocket', 'payloads', 'launchpad', 'cores', 'flight_number', 'date_utc']]
# We will remove rows with multiple cores because those are falcon rockets with 2 extra rocket boosters and rows that have multiple payloads in a single rocket.
data = data[data['cores'].map(len)==1]
data = data[data['payloads'].map(len)==1]
# Since payloads and cores are lists of size 1 we will also extract the single value in the list and replace the feature.
data['cores'] = data['cores'].map(lambda x : x[0])
data['payloads'] = data['payloads'].map(lambda x : x[0])
# We also want to convert the date_utc to a datetime datatype and then extracting the date leaving the time
data['date'] = pd.to_datetime(data['date_utc']).dt.date
# Using the date we will restrict the dates of the launches
data = data[data['date'] <= datetime.date(2020, 11, 13)]
```
* From the <code>rocket</code> we would like to learn the booster name
* From the <code>payload</code> we would like to learn the mass of the payload and the orbit that it is going to
* From the <code>launchpad</code> we would like to know the name of the launch site being used, the longitude, and the latitude.
* From <code>cores</code> we would like to learn the outcome of the landing, the type of the landing, number of flights with that core, whether gridfins were used, whether the core is reused, whether legs were used, the landing pad used, the block of the core which is a number used to seperate version of cores, the number of times this specific core has been reused, and the serial of the core.
The data from these requests will be stored in lists and will be used to create a new dataframe.
```
#Global variables
BoosterVersion = []
PayloadMass = []
Orbit = []
LaunchSite = []
Outcome = []
Flights = []
GridFins = []
Reused = []
Legs = []
LandingPad = []
Block = []
ReusedCount = []
Serial = []
Longitude = []
Latitude = []
```
These functions will apply the outputs globally to the above variables. Let's take a looks at <code>BoosterVersion</code> variable. Before we apply <code>getBoosterVersion</code> the list is empty:
```
BoosterVersion
```
Now, let's apply <code> getBoosterVersion</code> function method to get the booster version
```
# Call getBoosterVersion
getBoosterVersion(data)
```
the list has now been update
```
BoosterVersion[0:5]
```
we can apply the rest of the functions here:
```
# Call getLaunchSite
getLaunchSite(data)
# Call getPayloadData
getPayloadData(data)
# Call getCoreData
getCoreData(data)
```
Finally lets construct our dataset using the data we have obtained. We we combine the columns into a dictionary.
```
launch_dict = {'FlightNumber': list(data['flight_number']),
'Date': list(data['date']),
'BoosterVersion':BoosterVersion,
'PayloadMass':PayloadMass,
'Orbit':Orbit,
'LaunchSite':LaunchSite,
'Outcome':Outcome,
'Flights':Flights,
'GridFins':GridFins,
'Reused':Reused,
'Legs':Legs,
'LandingPad':LandingPad,
'Block':Block,
'ReusedCount':ReusedCount,
'Serial':Serial,
'Longitude': Longitude,
'Latitude': Latitude}
```
Then, we need to create a Pandas data frame from the dictionary launch_dict.
```
# Create a data from launch_dict
df = pd.DataFrame.from_dict(launch_dict)
```
Show the summary of the dataframe
```
# Show the head of the dataframe
df.head()
```
### Task 2: Filter the dataframe to only include `Falcon 9` launches
Finally we will remove the Falcon 1 launches keeping only the Falcon 9 launches. Filter the data dataframe using the <code>BoosterVersion</code> column to only keep the Falcon 9 launches. Save the filtered data to a new dataframe called <code>data_falcon9</code>.
```
# Hint data['BoosterVersion']!='Falcon 1'
data_falcon9 = df[df['BoosterVersion']!='Falcon 1']
```
Now that we have removed some values we should reset the FlgihtNumber column
```
data_falcon9.loc[:,'FlightNumber'] = list(range(1, data_falcon9.shape[0]+1))
data_falcon9
```
## Data Wrangling
We can see below that some of the rows are missing values in our dataset.
```
data_falcon9.isnull().sum()
```
Before we can continue we must deal with these missing values. The <code>LandingPad</code> column will retain None values to represent when landing pads were not used.
### Task 3: Dealing with Missing Values
Calculate below the mean for the <code>PayloadMass</code> using the <code>.mean()</code>. Then use the mean and the <code>.replace()</code> function to replace `np.nan` values in the data with the mean you calculated.
```
# Calculate the mean value of PayloadMass column
PayloadMassAvg = data_falcon9['PayloadMass'].mean()
PayloadMassAvg
# Replace the np.nan values with its mean value
data_falcon9['PayloadMass'].replace(np.nan, PayloadMassAvg, inplace=True)
data_falcon9.isnull().sum()
```
You should see the number of missing values of the <code>PayLoadMass</code> change to zero.
Now we should have no missing values in our dataset except for in <code>LandingPad</code>.
We can now export it to a <b>CSV</b> for the next section,but to make the answers consistent, in the next lab we will provide data in a pre-selected date range.
<code>data_falcon9.to_csv('dataset_part\_1.csv', index=False)</code>
## Authors
<a href="https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDS0321ENSkillsNetwork26802033-2021-01-01">Joseph Santarcangelo</a> has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.
## Change Log
| Date (YYYY-MM-DD) | Version | Changed By | Change Description |
| ----------------- | ------- | ---------- | ----------------------------------- |
| 2020-09-20 | 1.1 | Joseph | get result each time you run |
| 2020-09-20 | 1.1 | Azim | Created Part 1 Lab using SpaceX API |
| 2020-09-20 | 1.0 | Joseph | Modified Multiple Areas |
Copyright © 2021 IBM Corporation. All rights reserved.
| github_jupyter |
# INF-285 / ILI-285
## Desafío 4
### SCT 2020-1
# Instrucciones
- El desafío es individual, por lo cual se considera que todo el código entregado es de elaboración propia y no ha sido compartido de forma alguna.
- Las consultas sobre el desafío se deben realizar por medio de la plataforma Aula. **No está permitido publicar código en consultas de Aula**.
- El desafío debe ser realizado en Jupyter Notebook (Python3) utilizando este archivo como base.
- Debe utilizar arreglos de ```NumPy``` junto a las funciones y bibliotecas que se ponen a disposición en este archivo.
- Se debe respetar las firmas de las funciones, sus parámetros y retornos. Para eso se incluye un detalle de cada función tanto de las entregadas como las que deberá implementar. En caso de no seguir estas instrucciones, el desafío no podrá evaluarse.
- Se evaluará la correcta utilización de librerias ```NumPy```, ```SciPy```, entre otras, así como la correcta implementación de algoritmos de forma vectorizada.
- Evitar la impresión de mensajes salvo que se solicite en el enunciado.
- El archivo de entrega debe denominarse **ROL-desafio-numero.ipynb**. **De no respetarse este formato existirá un descuento de 50 puntos**
- La fecha de entrega es el **30 de julio a las 10:00 hrs**, posteriormente existirá un descuento lineal hasta las 11:00 hrs del mismo día.
# Introducción
En este desafío vamos a comparar el rendimiento de la interpolación polinomial utilizando **Intepolación de Lagrange** e **Interpolación Baricéntrica**. Recordar que estamos buscando un polinomio interpolador de la forma:
\begin{equation}
P(x) = a_0 + a_1x + a_2x^2 + \cdots + a_{n-1}x^{n-1}+a_{n}x^{n}= \sum_{i=0}^{n}a_ix^i,
\end{equation}
que se construye conociendo el conjunto de puntos $S=\{(x_0, y_0),(x_1, y_1), \dots, (x_n, y_n)\}$.
## Interpolación de Lagrange
El polinomio interpolador de Lagrange se define como:
\begin{equation*}
P(x) = y_{0}L_{0}(x) + y_{1}L_{1}(x) + \dots + y_{n} L_{n}(x) = \displaystyle \sum_{k=0}^{n} y_{k} L_{k}(x),
\end{equation*}
con
\begin{equation*}
L_k(x) = \frac{l_k(x)}{l_k(x_k)} \quad \text{y} \quad l_k(x) = \prod_{i=0, i\neq k}^{n}(x-x_i)= (x-x_1)(x-x_2)\cdots(x-x_{k-1})(x-x_{k+1})\cdots(x-x_n).
\end{equation*}
## Interpolación Baricéntrica
El polinomio interpolador utilizando **Interpolación Baricéntrica** se calcula de la siguiente manera:
\begin{equation*}
P(x)=l(x)\,\sum_{k=0}^n y_k\,\dfrac{w_k}{(x-x_k)}
=\dfrac{\displaystyle{\sum_{k=0}^n} y_k\dfrac{w_k}{(x-x_k)}}
{\displaystyle{\sum_{k=0}^n} \dfrac{w_k}{(x-x_k)}},
\end{equation*}
donde $l(x)=\displaystyle{\prod_{i=0}^n(x-x_i)}$ y $w_k=\dfrac{1}{l_k(x_k)}$.
```
import time
import numpy as np
import matplotlib.pyplot as plt
```
# Implementación
Implemente la función ```lagrange(x_i, y_i)``` que recibe como parámetros los puntos de interpolación $x_i, y_i$ y retorna el polinomio interpolador $L(x)$.
Asegúrese que su polinomio pueda evaluar arreglos de ```NumPy```.
```
def lagrange(x_i, y_i):
"""
Compute Interpolating Polynomial using Lagrange
Parameters
-----------
x_i : (n, ) array
Data x_i to interpolate
y_i : (n, ) array
Data y_i to interpolate
Returns
-------
L : Lambda function
Lagrange interpolating polynomial
"""
...
```
Implemente la función ```barycentric(x_i, y_i)``` que recibe como parámetros los puntos de interpolación $x_i, y_i$ y retorna el polinomio interpolador $B(x)$.
Asegúrese que su polinomio pueda evaluar arreglos de ```NumPy```.
```
def barycentric(x_i, y_i):
"""
Compute Interpolating Polynomial using Barycentric interpolation
Parameters
-----------
x_i : (n, ) array
Data x_i to interpolate
y_i : (n, ) array
Data y_i to interpolate
Returns
-------
B : Lambda function
Barycentric interpolation
"""
...
```
# Pruebas
Para que pueda probar sus funciones se ponen a disposición las siguientes funciones:
```
f1 = lambda x: 2 * x + 3
f2 = lambda x: np.sin(x) ** 3
f3 = lambda x: np.exp(x)
f4 = lambda x: np.exp(-x ** 2)
f5 = lambda x: np.sinc(x)
f6 = lambda x: 1 + x * 0
f7 = lambda x: 1 / (1 + 25 * x ** 2)
```
## Datos a interpolar
Acá puede seleccionar la función de la celda anterior que estime conveniente para probar su interpolación.
```
f = f5
```
Se generarán puntos equispaciados $x_i$ en un intervalo indicado y luego se evaluaran dichos puntos en una función $f$ para generar puntos $y_i$.
```
N_i = 11
x_a, x_b = -2 * np.pi, 2 * np.pi
x_i = np.linspace(x_a, x_b, N_i)
y_i = f(x_i)
```
## Interpolación
Para probar su interpolación, utilice las siguientes celdas.
```
Pl = lagrange(x_i, y_i)
Pb = barycentric(x_i, y_i)
```
# Visualización
Utilice este código para visualizar su interpolación.
```
N_e = 200
x_e = np.linspace(x_a, x_b, N_e)
y_e = f(x_e)
plt.figure(figsize=(12, 6))
plt.plot(x_e, y_e, 'b-', label=r"$f(x)$")
plt.plot(x_i, y_i, 'rd', label="Puntos para interpolar")
plt.plot(x_e, Pl(x_e), 'm--', label=r'$P_L(x)$')
plt.plot(x_e, Pb(x_e), 'k-.', label=r'$P_B(x)$')
plt.grid(True)
plt.legend()
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.show()
```
## Comparar tiempo de evaluacion
Diseñe un experimento de manera que pueda mostrar la complejidad computacional en la **evaluación** de sus interpoladores. Recuerde que la complejidad de evaluar un polinomio utilizando Lagrange debería ser del orden $O(n^2)$ mientras que al usar Interpolación Baricéntrica $O(n)$.
```
x_a, x_b = -2 * np.pi, 2 * np.pi # Interpolation domain
N_exp = 5
Nt = 2 ** np.arange(3, 9)
N = Nt.shape[-1]
times_el = np.zeros(N)
times_eb = np.zeros(N)
# Evaluation time
```
# Visualización tiempos
Puede utilizar este código para visualizar los tiempos de evaluación.
```
plt.figure(figsize=(12, 6))
plt.plot(Nt, times_el, 'rx', label="Lagrange")
plt.plot(Nt, times_eb, 'gd', label="Barycentric")
plt.plot(Nt, 1e-4 * Nt, label=r"$O(n)$") # Puede ajustar el coeficiente 1e-4
plt.plot(Nt, 1e-4 * Nt ** 2, label=r"$O(n^2)$") # Puede ajustar el coeficiente 1e-4
plt.xscale('log')
plt.yscale('log')
plt.ylabel("Time [s]")
plt.xlabel("Number of evaluation points")
plt.grid(True)
plt.legend()
plt.show()
```
| github_jupyter |
```
import networkx as nx
import pygraphviz
#path_to_dag = '/home/makrai/project/hypernym18-SemEval/top500words.dot'
path_to_dag = '1A_UMBC_tokenized.txt_100_cbow.vec.gz_True_200_0.3_unit_True_vocabulary_filtered.alph.reduced2_more_permissive.dot'
dag = nx.drawing.nx_agraph.read_dot(path_to_dag)
#nx.write_gpickle(dag, '/home/makrai/project/hypernym18-SemEval/top500words.gpickle')
deepest_occurrence = {}
attributes_for_nodes = {}
for n in dag.nodes(data=True):
words = n[1]['label'].split('|')[1].split('\\n')
node_id = int(n[1]['label'].split('|')[0])
attributes_for_nodes[node_id] = n[1]['label'].split('|')[2].split('\\n')
for w in words:
if not w in deepest_occurrence or deepest_occurrence[w][1] > len(words):
deepest_occurrence[w] = (node_id, len(words))
print(deepest_occurrence['dog'])
print(attributes_for_nodes[deepest_occurrence['dog'][0]])
print(deepest_occurrence['poodle'])
print(attributes_for_nodes[deepest_occurrence['poodle'][0]])
dog_location = deepest_occurrence['dog'][0]
poodle_location = deepest_occurrence['poodle'][0]
all_paths = nx.all_simple_paths(dag,'node{}'.format(dog_location), 'node{}'.format(poodle_location))
print(list(all_paths))
def generate_file_names(dataset_dir, dataset_id):
dataset_mapping = {
'1A':['english', 'UMBC'],
'1B':['italian', 'it_itwac'],
'1C':['spanish', 'es_1Billion'],
'2A':['medical', 'med_pubmed'],
'2B':['music', 'music_bioreviews']
}
data_file = '{}/training/data/{}.{}.training.data.txt'.format(
dataset_dir,
dataset_id,
dataset_mapping[dataset_id][0]
)
gold_file = '{}/training/gold/{}.{}.training.gold.txt'.format(
dataset_dir,
dataset_id,
dataset_mapping[dataset_id][0]
)
vocab_file='{}/vocabulary/{}.{}.vocabulary.txt'.format(
dataset_dir,
dataset_id,
dataset_mapping[dataset_id][0]
)
return data_file, gold_file, vocab_file
dataset_dir = '/home/berend/datasets/semeval2018/SemEval18-Task9'
dataset_id = path_to_dag[0:2]
train_data_file, train_gold_file, vocab = generate_file_names(dataset_dir, dataset_id)
dev_data_file, dev_gold_file = train_data_file.replace('training', 'trial'), train_gold_file.replace('training', 'trial')
test_data_file = train_data_file.replace('training', 'test')
train_queries = [l.split('\t')[0].replace(' ', '_') for l in open(train_data_file)] # do we want to consider category as well?
train_golds = [
[x.replace(' ', '_') for x in line.strip().split('\t')] for line in open(train_gold_file)
]
dev_queries = [l.split('\t')[0].replace(' ', '_') for l in open(dev_data_file)]
dev_golds = [
[x.replace(' ', '_') for x in line.strip().split('\t')] for line in open(dev_gold_file)
]
test_queries = [l.split('\t')[0].replace(' ', '_') for l in open(test_data_file)]
dag_reversed = dag.reverse()
shortest_path_lengths = []
hypernym_pairs_included = []
paths = []
for query, hypernyms in zip(train_queries, train_golds):
if query in deepest_occurrence:
query_location = deepest_occurrence[query][0]
for gold in hypernyms:
if not gold in deepest_occurrence:
continue
hypernym_pairs_included.append((query, gold))
gold_location = deepest_occurrence[gold][0]
if gold_location == query_location:
shortest_path_lengths.append(0)
paths.append([query_location])
else:
all_paths = list(nx.all_simple_paths(dag_reversed, 'node{}'.format(query_location), 'node{}'.format(gold_location)))
paths.append(all_paths)
if len(all_paths) == 0:
shortest_path_lengths.append(-1)
else:
shortest_path_lengths.append(min([len(p)-1 for p in all_paths]))
from collections import Counter
print(Counter([spl for spl in shortest_path_lengths]))
```
| github_jupyter |
```
import os, sys
import warnings
import random
import time
from vizdoom import *
import numpy as np
from skimage import transform, util, color
from collections import deque
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
%cd ..\..
%matplotlib inline
warnings.filterwarnings('ignore')
im_size = [200,200,4] # 200x200 image x 4 frames per input
action_size = 3 # 3 possible actions: left, right, shoot
learning_rate = 0.0002 # Alpha (aka learning rate)
total_episodes = 500 # Total episodes for training
max_steps = 100 # Max possible steps in an episode
batch_size = 64
save_frequency = 100 # Number of episodes before saving checkpoint
explore_start = 1.0 # exploration probability at start
explore_stop = 0.01 # minimum exploration probability
decay_rate = 0.0001 # exponential decay rate for exploration prob
gamma = 0.95 # Discounting rate
pretrain_length = batch_size # Number of experiences stored in the Memory when initialized for the first time
que_length = 1000000 # Number of experiences the Memory can keep
training = True
trained_model = 'checkpoint400.pth.tar'
def createEnvironment():
game = DoomGame()
game.load_config("scenarios/basic.cfg")
game.init()
left = [1, 0, 0]
right = [0, 1, 0]
shoot = [0, 0, 1]
actions = [left, right, shoot]
return game, actions
def processImg(img):
# img = np.swapaxes(img, 0, 2)
# img = color.rgb2gray(img)
img = img[70:-10, :]
img = img / 255
img = transform.resize(img, (200, 200))
return img
```
game, actions = createEnvironment()
img = processImg(game.get_state().screen_buffer)
img.shape
plt.imshow(img)
plt.show()
```
stack_size = 4
stacked_frames = deque([np.zeros((200,200), dtype=np.int) for i in range(stack_size)], maxlen=4)
def stackFrames(stacked_frames, stateim, is_new_episode):
frame = processImg(stateim)
if is_new_episode:
stacked_frames = deque([np.zeros((200,200), dtype=np.int) for i in range(stack_size)], maxlen=4)
for _ in range(stack_size):
stacked_frames.append(frame)
stacked_state = np.stack(stacked_frames, axis=2)
else:
stacked_frames.append(frame)
stacked_state = np.stack(stacked_frames, axis=2)
return stacked_state, stacked_frames
class DQN(nn.Module):
def __init__(self, img_size):
self.img_size = img_size
super().__init__()
self.conv1 = nn.Conv2d(4, 32, kernel_size=8, stride=2, padding=1)
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2, padding=1)
self.bn2 = nn.BatchNorm2d(64)
self.conv3 = nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1)
self.bn3 = nn.BatchNorm2d(128)
self.fc1 = nn.Linear(24*24*128, 512)
self.fc2 = nn.Linear(512, 3)
def forward(self, x):
x = F.elu(self.bn1(self.conv1(x)))
x = F.elu(self.bn2(self.conv2(x)))
x = F.elu(self.bn3(self.conv3(x)))
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = F.elu(self.fc2(x))
return x
class NNet():
def __init__(self):
self.nnet = DQN(200).cuda()
def train(self, memory, batch_size):
optimizer = optim.Adam(self.nnet.parameters(), lr=learning_rate)
batch = memory.sample(batch_size)
states_mb = torch.FloatTensor([each[0] for each in batch]).contiguous().cuda()
actions_mb = torch.FloatTensor([each[1] for each in batch]).contiguous().cuda()
rewards_mb = torch.FloatTensor([each[2] for each in batch]).contiguous().cuda()
next_states_mb = torch.FloatTensor([each[3] for each in batch]).contiguous().cuda()
dones_mb = np.array([each[4] for each in batch])
target_Qs_batch = []
Qs_next_state = self.nnet(next_states_mb.transpose(1,3))
for i in range(0, len(batch)):
terminal = dones_mb[i]
if terminal:
target_Qs_batch.append(rewards_mb[i])
else:
# print(Qs_next_state.shape)
# print(torch.max(Qs_next_state[i], 0))
# print(torch.max(Qs_next_state[i], 1))
Q_target = rewards_mb[i] + gamma*torch.max(Qs_next_state[i])
target_Qs_batch.append(Q_target)
targets_mb = torch.FloatTensor([each for each in target_Qs_batch]).contiguous().cuda()
states_mb, targets_mb = Variable(states_mb), Variable(targets_mb)
x = self.nnet(states_mb.transpose(1,3))
loss = self.loss(targets_mb, x, actions_mb)
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss
def predict(self, frames):
frames = torch.FloatTensor(frames)
frames = frames.contiguous().cuda().unsqueeze(0)
with torch.no_grad():
frames = Variable(frames)
self.nnet.eval()
x = self.nnet(frames.transpose(1,3))
return x.data.cpu().numpy()[0]
def save_checkpoint(self, folder='checkpoint', filename='checkpoint.pth.tar'):
filepath = os.path.join(folder, filename)
if not os.path.exists(folder):
print("Checkpoint Directory does not exist! Making directory {}".format(folder))
os.mkdir(folder)
else:
print("Saving Checkpoint")
torch.save({
'state_dict' : self.nnet.state_dict(),
}, filepath)
def load_checkpoint(self, folder='DQNcheckpoint', filename='checkpoint.pth.tar'):
# https://github.com/pytorch/examples/blob/master/imagenet/main.py#L98
filepath = os.path.join(folder, filename)
if not os.path.exists(filepath):
raise("No model in path {}".format(filepath))
checkpoint = torch.load(filepath)
self.nnet.load_state_dict(checkpoint['state_dict'])
def loss(self, target_Qs, output, actions_):
Qs = torch.sum(output*actions_, dim=1)
# loss = (target_Qs-Qs)**2
return torch.mean((target_Qs-Qs)**2)
class Memory():
def __init__(self, quelength):
self.buffer = deque(maxlen=quelength)
def add(self, experience):
self.buffer.append(experience)
def sample(self, batch_size):
buffer_size = len(self.buffer)
index = np.random.choice(np.arange(buffer_size), batch_size, replace=False)
return [self.buffer[i] for i in index]
game, possible_actions = createEnvironment()
memory = Memory(que_length)
game.new_episode()
if training:
for i in range(pretrain_length):
if i == 0:
state = game.get_state().screen_buffer
state, stacked_frames = stackFrames(stacked_frames, state, is_new_episode=True)
action = random.choice(possible_actions)
reward = game.make_action(action)
done = game.is_episode_finished()
if done:
next_state = np.zeros(state.shape)
memory.add((state, action, reward, next_state, done))
game.new_episode()
state = game.get_state().screen_buffer
state, stacked_frames = stackFrames(stacked_frames, state, is_new_episode=True)
else:
next_state = game.get_state().screen_buffer
next_state, stacked_frames = stackFrames(stacked_frames, next_state, is_new_episode=False)
experience = state, action, reward, next_state, done
memory.add(experience)
state = next_state
nnet = NNet()
def predict(explore_start, explore_stop, decay_rate, decay_step, state, possible_actions):
exp_exp_tradeoff = np.random.rand()
explore_probability = explore_stop + (explore_start - explore_stop) * np.exp(-decay_rate * decay_step)
if explore_probability > exp_exp_tradeoff:
action = random.choice(possible_actions)
else:
Qs = nnet.predict(state)
choice = np.argmax(Qs)
action = possible_actions[int(choice)]
return action, explore_probability
```
def run():
game, actions = createEnvironment()
mem = deque([], maxlen=que_length)
for episode in range(total_episodes):
state = game.get_state()
is_new_episode = True
for step in range(max_steps):
state_im = stackFrames(state.screen_buffer)
exp_exp_tradeoff = random.uniform(0,1)
if exp_exp_tradeoff > epsilon:
action = nnet.predict(state_im)
else:
action = random.choice(actions)
reward = game.make_action(action)
new_s = game.get_state()
new_im = rescaleAndGray(new_s.screen_buffer)
mem.append((state_im, action, reward, new_im))
state = new_s
Q_target = mem[mem.index(state_im)][2] + gamma*
episode += 1
epsilon = min_epsilon + (max_epsilon - min_epsilon)*np.exp(-decay_rate*episode)
```
if training:
decay_step = 0
game.init()
for episode in range(total_episodes):
if episode > 0:
print(f"Episode: {episode}, Total Reward: {np.sum(episode_rewards)}, Loss: {loss}, Explore: {exploration_probability}")
step = 0
episode_rewards = []
game.new_episode()
state = game.get_state().screen_buffer
state, stacked_frames = stackFrames(stacked_frames, state, True)
while step < max_steps:
step += 1
decay_step += 1
action, exploration_probability = predict(explore_start, explore_stop, decay_rate, decay_step, state, possible_actions)
reward = game.make_action(action)
done = game.is_episode_finished()
episode_rewards.append(reward)
if done:
next_state = np.zeros((im_size[0], im_size[1]), dtype=np.int)
next_state, stacked_frames = stackFrames(stacked_frames, next_state, False)
step = max_steps
total_reward = np.sum(episode_rewards)
# print(f"Episode: {episode}, Total Reward: {total_reward}, Loss: {loss}, Explore: {exploration_probability}")
experience = state, action, reward, next_state, done
memory.add(experience)
else:
next_state = game.get_state().screen_buffer
next_state, stacked_frames = stackFrames(stacked_frames, next_state, False)
experience = state, action, reward, next_state, done
memory.add(experience)
state = next_state
loss = nnet.train(memory, batch_size=batch_size)
if episode % save_frequency == 0:
nnet.save_checkpoint(filename=f'checkpoint{episode}.pth.tar')
nnet.save_checkpoint(filename='final.pth.tar')
nnet.load_checkpoint(filename=trained_model)
game.init()
done = False
game.new_episode()
state = game.get_state().screen_buffer
state, stacked_frames = stackFrames(stacked_frames, state, True)
for _ in range(100):
Qs = nnet.predict(state)
choice = np.argmax(Qs)
action = possible_actions[int(choice)]
game.make_action(action)
done = game.is_episode_finished()
score = game.get_total_reward()
if done:
# inp = input('Enter anything to replay, or nothing to end')
# if not inp:
game.new_episode()
state = game.get_state().screen_buffer
state, stacked_frames = stackFrames(stacked_frames, state, True)
else:
next_state = game.get_state().screen_buffer
next_state, stacked_frames = stackFrames(stacked_frames, next_state, False)
state = next_state
score = game.get_total_reward()
print(f'Score: {score}')
game.close()
```
| github_jupyter |
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-59152712-8');
</script>
# Start-to-Finish Example: `GiRaFFE_NRPy` 1D tests
### Authors: Patrick Nelson & Terrence Pierre Jacques
### Adapted from [Start-to-Finish Example: Head-On Black Hole Collision](../Tutorial-Start_to_Finish-BSSNCurvilinear-Two_BHs_Collide.ipynb)
## This module compiles and runs code tests for all 1D initial data options available in GiRaFFE-NRPy+, evolving one-dimensional GRFFE waves.
### NRPy+ Source Code for this module:
* Main python module for all 1D initial data: [GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_1D_tests.py](../../edit/in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_1D_tests.py) __Options:__
1. [Fast Wave](Tutorial-GiRaFFEfood_NRPy_1D_tests-fast_wave.ipynb)
1. [Alfven Wave](Tutorial-GiRaFFEfood_NRPy_1D_alfven_wave.ipynb)
1. [Degenerate Alfven Wave](Tutorial-GiRaFFEfood_NRPy_1D_tests-degen_Alfven_wave.ipynb)
1. [Three Alfven Waves](Tutorial-GiRaFFEfood_NRPy_1D_tests-three_waves.ipynb)
1. [FFE Breakdown](Tutorial-GiRaFFEfood_NRPy_1D_tests-FFE_breakdown.ipynb)
* [GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Afield_flux.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Afield_flux.py) [\[**tutorial**\]](Tutorial-GiRaFFE_NRPy_staggered-Afield_flux.ipynb) Generates the expressions to find the flux term of the induction equation.
* [GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_A2B.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_A2B.py) [\[**tutorial**\]](Tutorial-GiRaFFE_NRPy_staggered-A2B.ipynb) Generates the driver to compute the magnetic field from the vector potential/
* [GiRaFFE_NRPy/GiRaFFE_NRPy_BCs.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_BCs.py) [\[**tutorial**\]](Tutorial-GiRaFFE_NRPy-BCs.ipynb) Generates the code to apply boundary conditions to the vector potential, scalar potential, and three-velocity.
* [GiRaFFE_NRPy/GiRaFFE_NRPy_C2P_P2C.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_C2P_P2C.py) [\[**tutorial**\]](Tutorial-GiRaFFE_NRPy-C2P_P2C.ipynb) Generates the conservative-to-primitive and primitive-to-conservative solvers.
* [GiRaFFE_NRPy/GiRaFFE_NRPy_Metric_Face_Values.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_Metric_Face_Values.py) [\[**tutorial**\]](Tutorial-GiRaFFE_NRPy-Metric_Face_Values.ipynb) Generates code to interpolate metric gridfunctions to cell faces.
* [GiRaFFE_NRPy/GiRaFFE_NRPy_PPM.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_PPM.py) [\[**tutorial**\]](Tutorial-GiRaFFE_NRPy-PPM.ipynb) Genearates code to reconstruct primitive variables on cell faces.
* [GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Source_Terms.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Source_Terms.py) [\[**tutorial**\]](Tutorial-GiRaFFE_NRPy_staggered-Source_Terms.ipynb) Generates the expressions to find the flux term of the Poynting flux evolution equation.
* [GiRaFFE_NRPy/Stilde_flux.py](../../edit/in_progress/GiRaFFE_NRPy/Stilde_flux.py) [\[**tutorial**\]](Tutorial-GiRaFFE_NRPy-Stilde_flux.ipynb) Generates the expressions to find the flux term of the Poynting flux evolution equation.
* [../GRFFE/equations.py](../../edit/GRFFE/equations.py) [\[**tutorial**\]](../Tutorial-GRFFE_Equations-Cartesian.ipynb) Generates code necessary to compute the source terms.
* [../GRHD/equations.py](../../edit/GRHD/equations.py) [\[**tutorial**\]](../Tutorial-GRHD_Equations-Cartesian.ipynb) Generates code necessary to compute the source terms.
Here we use NRPy+ to generate the C source code necessary to set up initial data for an Alfvén wave (see [the original GiRaFFE paper](https://arxiv.org/pdf/1704.00599.pdf)). Then we use it to generate the RHS expressions for [Method of Lines](https://reference.wolfram.com/language/tutorial/NDSolveMethodOfLines.html) time integration based on the [explicit Runge-Kutta fourth-order scheme](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods) (RK4).
<a id='toc'></a>
# Table of Contents
$$\label{toc}$$
This notebook is organized as follows
1. [Step 1](#initializenrpy): Set core NRPy+ parameters for numerical grids
1. [Step 2](#grffe): Output C code for GRFFE evolution
1. [Step 2.a](#mol): Output macros for Method of Lines timestepping
1. [Step 3](#gf_id): Import `GiRaFFEfood_NRPy` initial data modules
1. [Step 4](#cparams): Output C codes needed for declaring and setting Cparameters; also set `free_parameters.h`
1. [Step 5](#mainc): `GiRaFFE_NRPy_standalone.c`: The Main C Code
1. [Step 6](#compileexec): Compile and execute C codes
1. [Step 7](#plots): Data Visualization
1. [Step 8](#latex_pdf_output): Output this notebook to $\LaTeX$-formatted PDF file
<a id='setup'></a>
# Step 1: Set up core functions and parameters for solving GRFFE equations \[Back to [top](#toc)\]
$$\label{setup}$$
```
import shutil, os, sys # Standard Python modules for multiplatform OS-level functions
# First, we'll add the parent directory to the list of directories Python will check for modules.
nrpy_dir_path = os.path.join("..")
if nrpy_dir_path not in sys.path:
sys.path.append(nrpy_dir_path)
# Step P1: Import needed NRPy+ core modules:
from outputC import outCfunction, lhrh # NRPy+: Core C code output module
import sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends
import finite_difference as fin # NRPy+: Finite difference C code generation module
import NRPy_param_funcs as par # NRPy+: Parameter interface
import grid as gri # NRPy+: Functions having to do with numerical grids
import indexedexp as ixp # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface
# Step P2: Create C code output directory:
Ccodesdir = os.path.join("GiRaFFE_staggered_1D_Tests_standalone_Ccodes/")
# First remove C code output directory if it exists
# Courtesy https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty
# !rm -r ScalarWaveCurvilinear_Playground_Ccodes
shutil.rmtree(Ccodesdir, ignore_errors=True)
# Then create a fresh directory
cmd.mkdir(Ccodesdir)
# Step P3: Create executable output directory:
outdir = os.path.join(Ccodesdir,"output/")
cmd.mkdir(outdir)
# Step P5: Set timestepping algorithm (we adopt the Method of Lines)
REAL = "double" # Best to use double here.
default_CFL_FACTOR= 0.5 # (GETS OVERWRITTEN WHEN EXECUTED.) In pure axisymmetry (symmetry_axes = 2 below) 1.0 works fine. Otherwise 0.5 or lower.
# Step P6: Set the finite differencing order to 2.
par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER",4)
thismodule = "Start_to_Finish-GiRaFFE_NRPy-1D_tests"
TINYDOUBLE = par.Cparameters("REAL", thismodule, "TINYDOUBLE", 1e-100)
import GiRaFFE_NRPy.GiRaFFE_NRPy_Main_Driver_staggered as md
# par.set_paramsvals_value("GiRaFFE_NRPy.GiRaFFE_NRPy_C2P_P2C::enforce_speed_limit_StildeD = False")
par.set_paramsvals_value("GiRaFFE_NRPy.GiRaFFE_NRPy_C2P_P2C::enforce_current_sheet_prescription = False")
```
<a id='grffe'></a>
# Step 2: Output C code for GRFFE evolution \[Back to [top](#toc)\]
$$\label{grffe}$$
We will first write the C codes needed for GRFFE evolution. We have already written a module to generate all these codes and call the functions in the appropriate order, so we will import that here. We will take the slightly unusual step of doing this before we generate the initial data functions because the main driver module will register all the gridfunctions we need. It will also generate functions that, in addition to their normal spot in the MoL timestepping, will need to be called during the initial data step to make sure all the variables are appropriately filled in.
All of this is handled with a single call to `GiRaFFE_NRPy_Main_Driver_generate_all()`, which will register gridfunctions, write all the C code kernels, and write the C code functions to call those.
```
md.GiRaFFE_NRPy_Main_Driver_generate_all(Ccodesdir)
```
<a id='mol'></a>
## Step 2.a: Output macros for Method of Lines timestepping \[Back to [top](#toc)\]
$$\label{mol}$$
Now, we generate the code to implement the method of lines using the fourth-order Runge-Kutta algorithm.
```
RK_method = "RK4"
# Step 3: Generate Runge-Kutta-based (RK-based) timestepping code.
# As described above the Table of Contents, this is a 3-step process:
# 3.A: Evaluate RHSs (RHS_string)
# 3.B: Apply boundary conditions (post_RHS_string, pt 1)
import MoLtimestepping.C_Code_Generation as MoL
from MoLtimestepping.RK_Butcher_Table_Dictionary import Butcher_dict
RK_order = Butcher_dict[RK_method][1]
cmd.mkdir(os.path.join(Ccodesdir,"MoLtimestepping/"))
MoL.MoL_C_Code_Generation(RK_method,
RHS_string = """
GiRaFFE_NRPy_RHSs(¶ms,auxevol_gfs,RK_INPUT_GFS,RK_OUTPUT_GFS);""",
post_RHS_string = """
GiRaFFE_NRPy_post_step(¶ms,xx,auxevol_gfs,RK_OUTPUT_GFS,n+1);\n""",
outdir = os.path.join(Ccodesdir,"MoLtimestepping/"))
```
<a id='gf_id'></a>
# Step 3: Import `GiRaFFEfood_NRPy` initial data modules \[Back to [top](#toc)\]
$$\label{gf_id}$$
With the preliminaries out of the way, we will write the C functions to set up initial data. There are two categories of initial data that must be set: the spacetime metric variables, and the GRFFE plasma variables. We will set up the spacetime first, namely the Minkowski spacetime.
```
gammaDD = ixp.zerorank2(DIM=3)
for i in range(3):
for j in range(3):
if i==j:
gammaDD[i][j] = sp.sympify(1) # else: leave as zero
betaU = ixp.zerorank1() # All should be 0
alpha = sp.sympify(1)
# Description and options for this initial data
desc = "Generate a flat spacetime metric."
loopopts_id ="AllPoints" # we don't need to read coordinates for flat spacetime.
# For testing: Also set inverse metric:
gammaUU, unused_gammaDET = ixp.symm_matrix_inverter3x3(gammaDD)
name = "set_initial_spacetime_metric_data"
values_to_print = [
lhrh(lhs=gri.gfaccess("auxevol_gfs","gammaDD00"),rhs=gammaDD[0][0]),
lhrh(lhs=gri.gfaccess("auxevol_gfs","gammaDD01"),rhs=gammaDD[0][1]),
lhrh(lhs=gri.gfaccess("auxevol_gfs","gammaDD02"),rhs=gammaDD[0][2]),
lhrh(lhs=gri.gfaccess("auxevol_gfs","gammaDD11"),rhs=gammaDD[1][1]),
lhrh(lhs=gri.gfaccess("auxevol_gfs","gammaDD12"),rhs=gammaDD[1][2]),
lhrh(lhs=gri.gfaccess("auxevol_gfs","gammaDD22"),rhs=gammaDD[2][2]),
lhrh(lhs=gri.gfaccess("auxevol_gfs","betaU0"),rhs=betaU[0]),
lhrh(lhs=gri.gfaccess("auxevol_gfs","betaU1"),rhs=betaU[1]),
lhrh(lhs=gri.gfaccess("auxevol_gfs","betaU2"),rhs=betaU[2]),
lhrh(lhs=gri.gfaccess("auxevol_gfs","alpha"),rhs=alpha)
]
outCfunction(
outfile = os.path.join(Ccodesdir,name+".h"), desc=desc, name=name,
params ="const paramstruct *params,REAL *xx[3],REAL *auxevol_gfs",
body = fin.FD_outputC("returnstring",values_to_print,params="outCverbose=False").replace("IDX4","IDX4S"),
loopopts = loopopts_id)
```
Now, we will write out the initials data function for the GRFFE variables.
```
initial_data_dir = os.path.join(Ccodesdir,"InitialData/")
cmd.mkdir(initial_data_dir)
ID_opts = ["AlfvenWave", "ThreeAlfvenWaves", "DegenAlfvenWave", "FastWave", "FFEBD"]
for initial_data in ID_opts:
if initial_data=="AlfvenWave":
import GiRaFFEfood_NRPy.GiRaFFEfood_NRPy_1D_tests as gid
gid.GiRaFFEfood_NRPy_1D_tests(stagger = True)
desc = "Generate Alfven wave 1D initial data for GiRaFFEfood_NRPy."
elif initial_data=="ThreeAlfvenWaves":
import GiRaFFEfood_NRPy.GiRaFFEfood_NRPy_1D_tests_three_waves as gid
gid.GiRaFFEfood_NRPy_1D_tests_three_waves(stagger = True)
desc = "Generate three Alfven wave 1D initial data for GiRaFFEfood_NRPy."
elif initial_data=="DegenAlfvenWave":
import GiRaFFEfood_NRPy.GiRaFFEfood_NRPy_1D_tests_degen_Alfven_wave as gid
gid.GiRaFFEfood_NRPy_1D_tests_degen_Alfven_wave(stagger = True)
desc = "Generate degenerate Alfven wave 1D initial data for GiRaFFEfood_NRPy."
elif initial_data=="FastWave":
import GiRaFFEfood_NRPy.GiRaFFEfood_NRPy_1D_tests_fast_wave as gid
gid.GiRaFFEfood_NRPy_1D_tests_fast_wave(stagger = True)
desc = "Generate fast wave 1D initial data for GiRaFFEfood_NRPy."
elif initial_data=="FFEBD":
import GiRaFFEfood_NRPy.GiRaFFEfood_NRPy_1D_tests_FFE_breakdown as gid
gid.GiRaFFEfood_NRPy_1D_tests_FFE_breakdown(stagger = True)
desc = "Generate FFE breakdown 1D initial data for GiRaFFEfood_NRPy."
name = initial_data
values_to_print = [\
lhrh(lhs=gri.gfaccess("out_gfs","AD0"),rhs=gid.AD[0]),\
lhrh(lhs=gri.gfaccess("out_gfs","AD1"),rhs=gid.AD[1]),\
lhrh(lhs=gri.gfaccess("out_gfs","AD2"),rhs=gid.AD[2]),\
lhrh(lhs=gri.gfaccess("auxevol_gfs","ValenciavU0"),rhs=gid.ValenciavU[0]),\
lhrh(lhs=gri.gfaccess("auxevol_gfs","ValenciavU1"),rhs=gid.ValenciavU[1]),\
lhrh(lhs=gri.gfaccess("auxevol_gfs","ValenciavU2"),rhs=gid.ValenciavU[2]),\
lhrh(lhs=gri.gfaccess("auxevol_gfs","BU0"),rhs=gid.BU[0]),\
lhrh(lhs=gri.gfaccess("auxevol_gfs","BU1"),rhs=gid.BU[1]),\
lhrh(lhs=gri.gfaccess("auxevol_gfs","BU2"),rhs=gid.BU[2]),\
lhrh(lhs=gri.gfaccess("out_gfs","psi6Phi"),rhs=sp.sympify(0))\
]
outCfunction(
outfile = os.path.join(initial_data_dir,name+".c"), desc=desc, name=name,
params ="const paramstruct *params, REAL *xx[3], REAL *auxevol_gfs, REAL *out_gfs",
body = fin.FD_outputC("returnstring",values_to_print,params="outCverbose=False").replace("IDX4","IDX4S"),
rel_path_to_Cparams='../',
loopopts ="AllPoints,Read_xxs")
inital_data_body = """
const char *option1 = "AlfvenWave";
const char *option2 = "ThreeAlfvenWaves";
const char *option3 = "DegenAlfvenWave";
const char *option4 = "FastWave";
const char *option5 = "FFEBD";
if (strcmp(initial_data_option, option1) == 0) {
AlfvenWave(params, xx, auxevol_gfs, out_gfs);
}
else if (strcmp(initial_data_option, option2) == 0) {
ThreeAlfvenWaves(params, xx, auxevol_gfs, out_gfs);
}
else if (strcmp(initial_data_option, option3) == 0) {
DegenAlfvenWave(params, xx, auxevol_gfs, out_gfs);
}
else if (strcmp(initial_data_option, option4) == 0) {
FastWave(params, xx, auxevol_gfs, out_gfs);
}
else if (strcmp(initial_data_option, option5) == 0) {
FFEBD(params, xx, auxevol_gfs, out_gfs);
}
else {
printf("ERROR: Invalid choice of initial data.");
exit(1);
}
"""
name = "initial_data"
desc = "Main initial data function."
includes = ["AlfvenWave.c", "ThreeAlfvenWaves.c", "DegenAlfvenWave.c", "FastWave.c", "FFEBD.c"]
outCfunction(
outfile = os.path.join(initial_data_dir,name+".h"), desc=desc, name=name,
params ="const char *initial_data_option, const paramstruct *restrict params,REAL *xx[3],REAL *restrict auxevol_gfs,REAL *restrict out_gfs",
body = inital_data_body,
includes = includes,
prefunc="#include <string.h>",
rel_path_to_Cparams='../',
loopopts ="")
```
<a id='cparams'></a>
# Step 4: Output C codes needed for declaring and setting Cparameters; also set `free_parameters.h` \[Back to [top](#toc)\]
$$\label{cparams}$$
Based on declared NRPy+ Cparameters, first we generate `declare_Cparameters_struct.h`, `set_Cparameters_default.h`, and `set_Cparameters[-SIMD].h`.
Then we output `free_parameters.h`, which sets initial data parameters, as well as grid domain & reference metric parameters, applying `domain_size` and `sinh_width`/`SymTP_bScale` (if applicable) as set above
```
# Step 3.e: Output C codes needed for declaring and setting Cparameters; also set free_parameters.h
# Step 3.e.i: Generate declare_Cparameters_struct.h, set_Cparameters_default.h, and set_Cparameters[-SIMD].h
par.generate_Cparameters_Ccodes(os.path.join(Ccodesdir))
# Step 3.e.ii: Set free_parameters.h
with open(os.path.join(Ccodesdir,"free_parameters.h"),"w") as file:
file.write("""// Override parameter defaults with values based on command line arguments and NGHOSTS.
params.Nxx0 = atoi(argv[1]);
params.Nxx1 = atoi(argv[2]);
params.Nxx2 = atoi(argv[3]);
params.Nxx_plus_2NGHOSTS0 = params.Nxx0 + 2*NGHOSTS;
params.Nxx_plus_2NGHOSTS1 = params.Nxx1 + 2*NGHOSTS;
params.Nxx_plus_2NGHOSTS2 = params.Nxx2 + 2*NGHOSTS;
// Step 0d: Set up space and time coordinates
// Step 0d.i: Declare \Delta x^i=dxx{0,1,2} and invdxx{0,1,2}, as well as xxmin[3] and xxmax[3]:
const REAL xxmin[3] = {-1.3255,-0.085,-0.085};
const REAL xxmax[3] = { 1.6745, 0.115, 0.115};
params.dxx0 = (xxmax[0] - xxmin[0]) / ((REAL)params.Nxx0+1);
params.dxx1 = (xxmax[1] - xxmin[1]) / ((REAL)params.Nxx1+1);
params.dxx2 = (xxmax[2] - xxmin[2]) / ((REAL)params.Nxx2+1);
printf("dxx0,dxx1,dxx2 = %.5e,%.5e,%.5e\\n",params.dxx0,params.dxx1,params.dxx2);
params.invdx0 = 1.0 / params.dxx0;
params.invdx1 = 1.0 / params.dxx1;
params.invdx2 = 1.0 / params.dxx2;
const int poison_grids = 0;
// Standard GRFFE parameters:
params.GAMMA_SPEED_LIMIT = 2000.0;
params.diss_strength = 0.1;
""")
```
<a id='bc_functs'></a>
# Step 4: Set up boundary condition functions for chosen singular, curvilinear coordinate system \[Back to [top](#toc)\]
$$\label{bc_functs}$$
Next apply singular, curvilinear coordinate boundary conditions [as documented in the corresponding NRPy+ tutorial notebook](Tutorial-Start_to_Finish-Curvilinear_BCs.ipynb)
...But, for the moment, we're actually just using this because it writes the file `gridfunction_defines.h`.
```
import CurviBoundaryConditions.CurviBoundaryConditions as cbcs
cbcs.Set_up_CurviBoundaryConditions(os.path.join(Ccodesdir,"boundary_conditions/"),Cparamspath=os.path.join("../"),enable_copy_of_static_Ccodes=False)
```
<a id='mainc'></a>
# Step 5: `GiRaFFE_NRPy_standalone.c`: The Main C Code \[Back to [top](#toc)\]
$$\label{mainc}$$
```
# Part P0: Define REAL, set the number of ghost cells NGHOSTS (from NRPy+'s FD_CENTDERIVS_ORDER),
# and set the CFL_FACTOR (which can be overwritten at the command line)
with open(os.path.join(Ccodesdir,"GiRaFFE_NRPy_REAL__NGHOSTS__CFL_FACTOR.h"), "w") as file:
file.write("""
// Part P0.a: Set the number of ghost cells, from NRPy+'s FD_CENTDERIVS_ORDER
#define NGHOSTS """+str(3)+"""
#define NGHOSTS_A2B """+str(2)+"""
// Part P0.b: Set the numerical precision (REAL) to double, ensuring all floating point
// numbers are stored to at least ~16 significant digits
#define REAL """+REAL+"""
// Part P0.c: Set the CFL Factor. Can be overwritten at command line.
REAL CFL_FACTOR = """+str(default_CFL_FACTOR)+";")
%%writefile $Ccodesdir/GiRaFFE_NRPy_standalone.c
// Step P0: Define REAL and NGHOSTS; and declare CFL_FACTOR. This header is generated in NRPy+.
#include "GiRaFFE_NRPy_REAL__NGHOSTS__CFL_FACTOR.h"
#include "declare_Cparameters_struct.h"
const int NSKIP_1D_OUTPUT = 1;
// Step P1: Import needed header files
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "time.h"
#include "stdint.h" // Needed for Windows GCC 6.x compatibility
#ifndef M_PI
#define M_PI 3.141592653589793238462643383279502884L
#endif
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.707106781186547524400844362104849039L
#endif
// Step P2: Declare the IDX4S(gf,i,j,k) macro, which enables us to store 4-dimensions of
// data in a 1D array. In this case, consecutive values of "i"
// (all other indices held to a fixed value) are consecutive in memory, where
// consecutive values of "j" (fixing all other indices) are separated by
// Nxx_plus_2NGHOSTS0 elements in memory. Similarly, consecutive values of
// "k" are separated by Nxx_plus_2NGHOSTS0*Nxx_plus_2NGHOSTS1 in memory, etc.
#define IDX4S(g,i,j,k) \
( (i) + Nxx_plus_2NGHOSTS0 * ( (j) + Nxx_plus_2NGHOSTS1 * ( (k) + Nxx_plus_2NGHOSTS2 * (g) ) ) )
#define IDX4ptS(g,idx) ( (idx) + (Nxx_plus_2NGHOSTS0*Nxx_plus_2NGHOSTS1*Nxx_plus_2NGHOSTS2) * (g) )
#define IDX3S(i,j,k) ( (i) + Nxx_plus_2NGHOSTS0 * ( (j) + Nxx_plus_2NGHOSTS1 * ( (k) ) ) )
#define LOOP_REGION(i0min,i0max, i1min,i1max, i2min,i2max) \
for(int i2=i2min;i2<i2max;i2++) for(int i1=i1min;i1<i1max;i1++) for(int i0=i0min;i0<i0max;i0++)
#define LOOP_ALL_GFS_GPS(ii) _Pragma("omp parallel for") \
for(int (ii)=0;(ii)<Nxx_plus_2NGHOSTS_tot*NUM_EVOL_GFS;(ii)++)
// Step P3: Set gridfunction macros
#include "boundary_conditions/gridfunction_defines.h"
// Step P4: Include the RHS, BC, and primitive recovery functions
#include "GiRaFFE_NRPy_Main_Driver.h"
// Step P5: Include the initial data functions
#include "set_initial_spacetime_metric_data.h"
#include "InitialData/initial_data.h"
// main() function:
// Step 0: Read command-line input, set up grid structure, allocate memory for gridfunctions, set up coordinates
// Step 1: Set up scalar wave initial data
// Step 2: Evolve scalar wave initial data forward in time using Method of Lines with RK4 algorithm,
// applying quadratic extrapolation outer boundary conditions.
// Step 3: Output relative error between numerical and exact solution.
// Step 4: Free all allocated memory
int main(int argc, const char *argv[]) {
paramstruct params;
#include "set_Cparameters_default.h"
// Step 0a: Read command-line input, error out if nonconformant
if(argc != 5 || atoi(argv[1]) < NGHOSTS || atoi(argv[2]) < NGHOSTS || atoi(argv[3]) < NGHOSTS) {
printf("Error: Expected three command-line arguments: ./GiRaFFE_NRPy_standalone [Nx] [Ny] [Nz],\n");
printf("where Nx is the number of grid points in the x direction, and so forth.\n");
printf("Nx,Ny,Nz MUST BE larger than NGHOSTS (= %d)\n",NGHOSTS);
exit(1);
}
// Step 0c: Set free parameters, overwriting Cparameters defaults
// by hand or with command-line input, as desired.
#include "free_parameters.h"
#include "set_Cparameters-nopointer.h"
// ... and then set up the numerical grid structure in time:
const REAL t_final = 2.0;
const REAL CFL_FACTOR = 0.5; // Set the CFL Factor
// Step 0c: Allocate memory for gridfunctions
const int Nxx_plus_2NGHOSTS_tot = Nxx_plus_2NGHOSTS0*Nxx_plus_2NGHOSTS1*Nxx_plus_2NGHOSTS2;
// Step 0k: Allocate memory for gridfunctions
#include "MoLtimestepping/RK_Allocate_Memory.h"
REAL *restrict auxevol_gfs = (REAL *)malloc(sizeof(REAL) * NUM_AUXEVOL_GFS * Nxx_plus_2NGHOSTS_tot);
REAL *evol_gfs_exact = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot);
REAL *auxevol_gfs_exact = (REAL *)malloc(sizeof(REAL) * NUM_AUXEVOL_GFS * Nxx_plus_2NGHOSTS_tot);
// For debugging, it can be useful to set everything to NaN initially.
if(poison_grids) {
for(int ii=0;ii<NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot;ii++) {
y_n_gfs[ii] = 1.0/0.0;
y_nplus1_running_total_gfs[ii] = 1.0/0.0;
//k_odd_gfs[ii] = 1.0/0.0;
//k_even_gfs[ii] = 1.0/0.0;
diagnostic_output_gfs[ii] = 1.0/0.0;
evol_gfs_exact[ii] = 1.0/0.0;
}
for(int ii=0;ii<NUM_AUXEVOL_GFS * Nxx_plus_2NGHOSTS_tot;ii++) {
auxevol_gfs[ii] = 1.0/0.0;
auxevol_gfs_exact[ii] = 1.0/0.0;
}
}
// Step 0d: Set up coordinates: Set dx, and then dt based on dx_min and CFL condition
// This is probably already defined above, but just in case...
#ifndef MIN
#define MIN(A, B) ( ((A) < (B)) ? (A) : (B) )
#endif
REAL dt = CFL_FACTOR * MIN(dxx0,MIN(dxx1,dxx2)); // CFL condition
int Nt = (int)(t_final / dt + 0.5); // The number of points in time.
//Add 0.5 to account for C rounding down integers.
// Step 0e: Set up cell-centered Cartesian coordinate grids
REAL *xx[3];
xx[0] = (REAL *)malloc(sizeof(REAL)*Nxx_plus_2NGHOSTS0);
xx[1] = (REAL *)malloc(sizeof(REAL)*Nxx_plus_2NGHOSTS1);
xx[2] = (REAL *)malloc(sizeof(REAL)*Nxx_plus_2NGHOSTS2);
for(int j=0;j<Nxx_plus_2NGHOSTS0;j++) xx[0][j] = xxmin[0] + (j-NGHOSTS+1)*dxx0;
for(int j=0;j<Nxx_plus_2NGHOSTS1;j++) xx[1][j] = xxmin[1] + (j-NGHOSTS+1)*dxx1;
for(int j=0;j<Nxx_plus_2NGHOSTS2;j++) xx[2][j] = xxmin[2] + (j-NGHOSTS+1)*dxx2;
// Step 1: Set up initial data to be exact solution at time=0:
REAL time = 0.0;
set_initial_spacetime_metric_data(¶ms, xx, auxevol_gfs);
const char *initial_data_option = argv[4];
initial_data(initial_data_option, ¶ms, xx, auxevol_gfs, y_n_gfs);
// Fill in the remaining quantities
GiRaFFE_compute_B_and_Bstagger_from_A(¶ms,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*GAMMADD00GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*GAMMADD01GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*GAMMADD02GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*GAMMADD11GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*GAMMADD12GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*GAMMADD22GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*PSI6_TEMPGF, /* Temporary storage,overwritten */
y_n_gfs+Nxx_plus_2NGHOSTS_tot*AD0GF,
y_n_gfs+Nxx_plus_2NGHOSTS_tot*AD1GF,
y_n_gfs+Nxx_plus_2NGHOSTS_tot*AD2GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*BU0GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*BU1GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*BU2GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*BSTAGGERU0GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*BSTAGGERU1GF,
auxevol_gfs+Nxx_plus_2NGHOSTS_tot*BSTAGGERU2GF);
//override_BU_with_old_GiRaFFE(¶ms,auxevol_gfs,0);
GiRaFFE_NRPy_prims_to_cons(¶ms,auxevol_gfs,y_n_gfs);
// Extra stack, useful for debugging:
GiRaFFE_NRPy_cons_to_prims(¶ms,xx,auxevol_gfs,y_n_gfs);
for(int n=0;n<=Nt;n++) { // Main loop to progress forward in time.
//for(int n=0;n<=1;n++) { // Main loop to progress forward in time.
// Step 1a: Set current time to correct value & compute exact solution
time = ((REAL)n)*dt;
/* Step 2: Validation: Output relative error between numerical and exact solution, */
if(time == 0.0 || time == 0.5 || time == 1.0 || time == 2.0 || time == 0.02 || time == 0.56) {
// Step 2c: Output relative error between exact & numerical at center of grid.
const int i0mid=Nxx_plus_2NGHOSTS0/2;
const int i1mid=Nxx_plus_2NGHOSTS1/2;
const int i2mid=Nxx_plus_2NGHOSTS2/2;
char filename[100];
sprintf(filename,"out%d__%s-%08d.txt", Nxx0, initial_data_option, n);
FILE *out2D = fopen(filename, "w");
for(int i0=0;i0<Nxx_plus_2NGHOSTS0;i0++) {
const int idx = IDX3S(i0,i1mid,i2mid);
fprintf(out2D,"%.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e\n",
xx[0][i0],
auxevol_gfs[IDX4ptS(BU0GF,idx)],auxevol_gfs[IDX4ptS(BU1GF,idx)],auxevol_gfs[IDX4ptS(BU2GF,idx)],
y_n_gfs[IDX4ptS(AD0GF,idx)],y_n_gfs[IDX4ptS(AD1GF,idx)],y_n_gfs[IDX4ptS(AD2GF,idx)],
y_n_gfs[IDX4ptS(STILDED0GF,idx)],y_n_gfs[IDX4ptS(STILDED1GF,idx)],y_n_gfs[IDX4ptS(STILDED2GF,idx)],
auxevol_gfs[IDX4ptS(VALENCIAVU0GF,idx)],auxevol_gfs[IDX4ptS(VALENCIAVU1GF,idx)],auxevol_gfs[IDX4ptS(VALENCIAVU2GF,idx)],
y_n_gfs[IDX4ptS(PSI6PHIGF,idx)], time);
}
fclose(out2D);
// For convergence testing, we'll shift the grid x -> x-1 and output initial data again, giving the exact solution.
LOOP_REGION(0,Nxx_plus_2NGHOSTS0,0,1,0,1) {
xx[0][i0] += -mu_AW*time;
//xx[0][i0] += -time;
}
set_initial_spacetime_metric_data(¶ms,xx,auxevol_gfs_exact);
initial_data(initial_data_option, ¶ms,xx,auxevol_gfs_exact,evol_gfs_exact);
// Fill in the remaining quantities
//driver_A_to_B(¶ms,evol_gfs_exact,auxevol_gfs_exact);
GiRaFFE_NRPy_prims_to_cons(¶ms,auxevol_gfs_exact,evol_gfs_exact);
// And now, we'll set the grid back to rights.
LOOP_REGION(0,Nxx_plus_2NGHOSTS0,0,1,0,1) {
xx[0][i0] -= -mu_AW*time;
//xx[0][i0] -= -time;
}
sprintf(filename,"out%d-%08d_exact.txt",Nxx0,n);
FILE *out2D_exact = fopen(filename, "w");
for(int i0=0;i0<Nxx_plus_2NGHOSTS0;i0++) {
const int idx = IDX3S(i0,i1mid,i2mid);
fprintf(out2D_exact,"%.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e %.16e\n",
xx[0][i0],
auxevol_gfs_exact[IDX4ptS(BU0GF,idx)],auxevol_gfs_exact[IDX4ptS(BU1GF,idx)],auxevol_gfs_exact[IDX4ptS(BU2GF,idx)],
evol_gfs_exact[IDX4ptS(AD0GF,idx)],evol_gfs_exact[IDX4ptS(AD1GF,idx)],evol_gfs_exact[IDX4ptS(AD2GF,idx)],
evol_gfs_exact[IDX4ptS(STILDED0GF,idx)],evol_gfs_exact[IDX4ptS(STILDED1GF,idx)],evol_gfs_exact[IDX4ptS(STILDED2GF,idx)],
auxevol_gfs_exact[IDX4ptS(VALENCIAVU0GF,idx)],auxevol_gfs_exact[IDX4ptS(VALENCIAVU1GF,idx)],auxevol_gfs_exact[IDX4ptS(VALENCIAVU2GF,idx)],
evol_gfs_exact[IDX4ptS(PSI6PHIGF,idx)]);
}
fclose(out2D_exact);
}
// Step 3: Evolve scalar wave initial data forward in time using Method of Lines with RK4 algorithm,
// applying quadratic extrapolation outer boundary conditions.
// Step 3.b: Step forward one timestep (t -> t+dt) in time using
// chosen RK-like MoL timestepping algorithm
#include "MoLtimestepping/RK_MoL.h"
} // End main loop to progress forward in time.
// Step 4: Free all allocated memory
#include "MoLtimestepping/RK_Free_Memory.h"
free(auxevol_gfs);
free(auxevol_gfs_exact);
free(evol_gfs_exact);
for(int i=0;i<3;i++) free(xx[i]);
return 0;
}
```
<a id='compileexec'></a>
# Step 6: Compile generated C codes & perform GRFFE simulations \[Back to [top](#toc)\]
$$\label{compileexec}$$
To aid in the cross-platform-compatible (with Windows, MacOS, & Linux) compilation and execution, we make use of `cmdline_helper` [(**Tutorial**)](Tutorial-cmdline_helper.ipynb).
```
cmd.C_compile(os.path.join(Ccodesdir,"GiRaFFE_NRPy_standalone.c"),
os.path.join(Ccodesdir,"output","GiRaFFE_NRPy_standalone"),compile_mode="optimized")
# Change to output directory
os.chdir(outdir)
# Clean up existing output files
cmd.delete_existing_files("out*.txt")
cmd.delete_existing_files("out*.png")
# ID options are: "AlfvenWave", "ThreeAlfvenWaves", "DegenAlfvenWave", "FastWave", "FFEBD"
for opt in ID_opts:
cmd.Execute("GiRaFFE_NRPy_standalone", "299 4 4 "+opt, "out_298"+opt+".txt")
# cmd.Execute("GiRaFFE_NRPy_standalone", "1280 9 9 "+opt, "out_1280"+opt+".txt")
# cmd.Execute("GiRaFFE_NRPy_standalone", "1280 32 32 "+opt, "out_"+opt+".txt")
# cmd.Execute("GiRaFFE_NRPy_standalone", "149 9 9 AlfvenWave","out149.txt")
# Return to root directory
os.chdir(os.path.join("../../"))
```
<a id='plots'></a>
# Step 7: Data Visualization \[Back to [top](#toc)\]
$$\label{plots}$$
Now we plot the data and recreate figure 1 from the [GiRaFFE paper](https://arxiv.org/pdf/1704.00599.pdf). We reconstruct the electric field via
$$
E_i = -\epsilon_{ijk}v^j B^k
$$
the `calc_E` function below. We also calculate the FFE condition $B^2 - E^2$ below using the `calc_Bsquared_minus_Esquared` function.
```
eDDD = ixp.LeviCivitaSymbol_dim3_rank3()
def calc_E(data):
VU0 = data[:, 10]
VU1 = data[:, 11]
VU2 = data[:, 12]
BU0 = data[:, 1]
BU1 = data[:, 2]
BU2 = data[:, 3]
VU = [VU0, VU1, VU2]
BU = [BU0, BU1, BU2]
ED = np.zeros((VU0.size, 3))
for i in range(3):
for j in range(3):
for k in range(3):
ED[:,i] = ED[:,i] - eDDD[i][j][k]*VU[j]*BU[k]
return ED
def calc_Bsquared_minus_Esquared(data):
EU = calc_E(data)
BU0 = data[:, 1]
BU1 = data[:, 2]
BU2 = data[:, 3]
return (BU0**2 + BU1**2 + BU2**2) - (EU[:,0]**2 + EU[:,1]**2 + EU[:,2]**2)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib as mpl
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13
labels = ["x","BU0","BU1","BU2","AD0","AD1","AD2","StildeD0","StildeD1","StildeD2","ValenciavU0","ValenciavU1","ValenciavU2", "psi6Phi"]
fig = plt.figure(figsize=(6, 15))
# spec = mpl.gridspec.GridSpec(ncols=6, nrows=2,wspace=0.65, hspace=0.4) # 6 columns evenly divides both 2 & 3
# ax1 = fig.add_subplot(spec[0,0:2]) # row 0 with axes spanning 2 cols on evens
# ax2 = fig.add_subplot(spec[0,2:4])
# ax3 = fig.add_subplot(spec[0,4:])
# ax4 = fig.add_subplot(spec[1,1:3]) # row 0 with axes spanning 2 cols on odds
# ax5 = fig.add_subplot(spec[1,3:5])
gs = gridspec.GridSpec(nrows=5, ncols=1, hspace=0.5)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])
ax3 = fig.add_subplot(gs[2, 0])
ax4 = fig.add_subplot(gs[3, 0])
ax5 = fig.add_subplot(gs[4, 0])
Data_num_Fast_A = np.loadtxt(os.path.join(Ccodesdir,"output","out299__FastWave-00000000.txt"))
Data_num_Fast_B = np.loadtxt(os.path.join(Ccodesdir,"output","out299__FastWave-00000100.txt"))
E_Fast_A = calc_E(Data_num_Fast_A)
E_Fast_B = calc_E(Data_num_Fast_B)
ax1.scatter(Data_num_Fast_A[:,0], np.abs(E_Fast_A[:,2]), s=1,label = 't = 0')
ax1.plot(Data_num_Fast_B[:,0], np.abs(E_Fast_B[:,2]), 'k-', label = 't = 0.5')
ax1.set_xlim(-0.5, 1.5)
ax1.set_ylim(0.6)
ax1.text(0.95, 0.01, 'Fast Wave',
verticalalignment='bottom', horizontalalignment='right',
transform=ax1.transAxes,
color='black', fontsize=14)
ax1.set_xlabel('x')
ax1.set_ylabel(r'$|E^z|$')
ax1.legend()
Data_num_Alf_A = np.loadtxt(os.path.join(Ccodesdir,"output","out299__AlfvenWave-00000000.txt"))
Data_num_Alf_B = np.loadtxt(os.path.join(Ccodesdir,"output","out299__AlfvenWave-00000400.txt"))
ax2.scatter(Data_num_Alf_A[:,0], Data_num_Alf_A[:,3], s=1, label = 't = 0')
ax2.plot(Data_num_Alf_B[:,0], Data_num_Alf_B[:,3], 'k-', label = 't = 2.0')
ax2.set_xlim(-1.5, 1.5)
ax2.set_ylim(1.1)
ax2.text(0.95, 0.01, 'Alfven Wave',
verticalalignment='bottom', horizontalalignment='right',
transform=ax2.transAxes,
color='black', fontsize=14)
ax2.set_xlabel('x')
ax2.set_ylabel(r'$B^z$')
ax2.legend(loc='center right')
Data_num_DegenAlf_A = np.loadtxt(os.path.join(Ccodesdir,"output","out299__DegenAlfvenWave-00000000.txt"))
Data_num_DegenAlf_B = np.loadtxt(os.path.join(Ccodesdir,"output","out299__DegenAlfvenWave-00000200.txt"))
E_DegenAlf_A = calc_E(Data_num_DegenAlf_A)
E_DegenAlf_B = calc_E(Data_num_DegenAlf_B)
ax3.scatter(Data_num_DegenAlf_A[:,0], E_DegenAlf_A[:,1], s=1, label = 't = 0')
ax3.plot(Data_num_DegenAlf_B[:,0], E_DegenAlf_B[:,1], 'k-', label = 't = 1.0')
ax3.set_xlim(-1.5, 1.5)
ax3.set_ylim(-1.35)
ax3.text(0.95, 0.01, 'Deg. Alfven Wave',
verticalalignment='bottom', horizontalalignment='right',
transform=ax3.transAxes,
color='black', fontsize=14)
ax3.set_xlabel('x')
ax3.set_ylabel(r'$E^y$')
ax3.legend()
# Data_num_ThreeAlf_A = np.loadtxt(os.path.join(Ccodesdir,"output","out149__ThreeAlfvenWaves-00000000.txt"))
Data_num_ThreeAlf_B = np.loadtxt(os.path.join(Ccodesdir,"output","out299__ThreeAlfvenWaves-00000112.txt"))
# ax2.plot(Data_num_ThreeAlf_A[:,0], Data_num_ThreeAlf_A[:,2], 'k-')
ax4.scatter(Data_num_ThreeAlf_B[:,0], Data_num_ThreeAlf_B[:,2], s=1, label = 't = 0.56')
ax4.set_xlim(-1.0, 1.0)
# ax4.set_ylim()
ax4.text(0.95, 0.01, 'Three Waves',
verticalalignment='bottom', horizontalalignment='right',
transform=ax4.transAxes,
color='black', fontsize=14)
ax4.set_xlabel('x')
ax4.set_ylabel(r'$B^y$')
ax4.legend(loc='center')
Data_num_FFEBD_A = np.loadtxt(os.path.join(Ccodesdir,"output","out299__FFEBD-00000000.txt"))
Data_num_FFEBD_B = np.loadtxt(os.path.join(Ccodesdir,"output","out299__FFEBD-00000004.txt"))
B2mE2_A = calc_Bsquared_minus_Esquared(Data_num_FFEBD_A)
B2mE2_B = calc_Bsquared_minus_Esquared(Data_num_FFEBD_B)
ax5.scatter(Data_num_FFEBD_A[:,0], B2mE2_A, s=1, label = 't = 0')
ax5.plot(Data_num_FFEBD_B[:,0], B2mE2_B, 'k-', label = 't = 0.02')
ax5.set_xlim(-0.4, 0.6)
ax5.text(0.95, 0.01, 'FFE Breakdown',
verticalalignment='bottom', horizontalalignment='right',
transform=ax5.transAxes,
color='black', fontsize=14)
ax5.set_xlabel('x')
ax5.set_ylabel(r'$B^2 - E^2$')
ax5.legend()
plt.savefig(os.path.join(Ccodesdir,"output","NRPy-GiRaFFE"), dpi=800, bbox_inches="tight")
plt.close(fig)
img1 = plt.imread(os.path.join(Ccodesdir,"output","NRPy-GiRaFFE.png"))
img2 = plt.imread(os.path.join("GiRaFFE_NRPy/example_par_files/figure1_GiRaFFE_paper.png"))
NUM_ROWS = 1
IMGs_IN_ROW = 2
f, ax = plt.subplots(NUM_ROWS, IMGs_IN_ROW, figsize=(28,18))
plt.subplots_adjust(wspace=0.05)
plt.axis('off')
ax[0].imshow(img1)
ax[1].imshow(img2)
ax[0].set_title('image 1')
ax[1].set_title('image 2')
# title = 'side by side view of images'
# f.suptitle(title, fontsize=16)
plt.tight_layout()
# plt.xticks([])
# plt.yticks([])
plt.show()
```
<a id='latex_pdf_output'></a>
# Step 8: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](#toc)\]
$$\label{latex_pdf_output}$$
The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename
[Tutorial-Start_to_Finish-GiRaFFE_NRPy-1D_tests-staggered.pdf](Tutorial-Start_to_Finish-GiRaFFE_NRPy-1D_tests-staggered.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.)
```
import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface
cmd.output_Jupyter_notebook_to_LaTeXed_PDF("Tutorial-Start_to_Finish-GiRaFFE_NRPy-1D_tests-staggered",location_of_template_file=os.path.join(".."))
```
| github_jupyter |
# Image features exercise
*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*
We have seen that we can achieve reasonable performance on an image classification task by training a linear classifier on the pixels of the input image. In this exercise we will show that we can improve our classification performance by training linear classifiers not on raw pixels but on features that are computed from the raw pixels.
All of your work for this exercise will be done in this notebook.
```
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading extenrnal modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
```
## Load data
Similar to previous exercises, we will load CIFAR-10 data from disk.
```
from cs231n.features import color_histogram_hsv, hog_feature
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000):
# Load the raw CIFAR-10 data
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
# Cleaning up variables to prevent loading data multiple times (which may cause memory issue)
try:
del X_train, y_train
del X_test, y_test
print('Clear previously loaded data.')
except:
pass
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# Subsample the data
mask = list(range(num_training, num_training + num_validation))
X_val = X_train[mask]
y_val = y_train[mask]
mask = list(range(num_training))
X_train = X_train[mask]
y_train = y_train[mask]
mask = list(range(num_test))
X_test = X_test[mask]
y_test = y_test[mask]
return X_train, y_train, X_val, y_val, X_test, y_test
X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data()
```
## Extract Features
For each image we will compute a Histogram of Oriented
Gradients (HOG) as well as a color histogram using the hue channel in HSV
color space. We form our final feature vector for each image by concatenating
the HOG and color histogram feature vectors.
Roughly speaking, HOG should capture the texture of the image while ignoring
color information, and the color histogram represents the color of the input
image while ignoring texture. As a result, we expect that using both together
ought to work better than using either alone. Verifying this assumption would
be a good thing to try for your own interest.
The `hog_feature` and `color_histogram_hsv` functions both operate on a single
image and return a feature vector for that image. The extract_features
function takes a set of images and a list of feature functions and evaluates
each feature function on each image, storing the results in a matrix where
each column is the concatenation of all feature vectors for a single image.
```
from cs231n.features import *
num_color_bins = 10 # Number of bins in the color histogram
feature_fns = [hog_feature, lambda img: color_histogram_hsv(img, nbin=num_color_bins)]
X_train_feats = extract_features(X_train, feature_fns, verbose=True)
X_val_feats = extract_features(X_val, feature_fns)
X_test_feats = extract_features(X_test, feature_fns)
# Preprocessing: Subtract the mean feature
mean_feat = np.mean(X_train_feats, axis=0, keepdims=True)
X_train_feats -= mean_feat
X_val_feats -= mean_feat
X_test_feats -= mean_feat
# Preprocessing: Divide by standard deviation. This ensures that each feature
# has roughly the same scale.
std_feat = np.std(X_train_feats, axis=0, keepdims=True)
X_train_feats /= std_feat
X_val_feats /= std_feat
X_test_feats /= std_feat
# Preprocessing: Add a bias dimension
X_train_feats = np.hstack([X_train_feats, np.ones((X_train_feats.shape[0], 1))])
X_val_feats = np.hstack([X_val_feats, np.ones((X_val_feats.shape[0], 1))])
X_test_feats = np.hstack([X_test_feats, np.ones((X_test_feats.shape[0], 1))])
```
## Train SVM on features
Using the multiclass SVM code developed earlier in the assignment, train SVMs on top of the features extracted above; this should achieve better results than training SVMs directly on top of raw pixels.
```
# Use the validation set to tune the learning rate and regularization strength
from cs231n.classifiers.linear_classifier import LinearSVM
learning_rates = [1e-3, 1e-2]
regularization_strengths = [0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
results = {}
best_val = -1
best_svm = None
################################################################################
# TODO: #
# Use the validation set to set the learning rate and regularization strength. #
# This should be identical to the validation that you did for the SVM; save #
# the best trained classifer in best_svm. You might also want to play #
# with different numbers of bins in the color histogram. If you are careful #
# you should be able to get accuracy of near 0.44 on the validation set. #
################################################################################
np.random.seed(0)
grid_search = [ (lr,reg) for lr in learning_rates for reg in regularization_strengths ]
for lr, reg in grid_search:
# Create SVM model
svm = LinearSVM()
# Train phase
svm.train(X_train_feats, y_train, learning_rate=lr, reg=reg, num_iters=2000,
batch_size=200, verbose=False)
y_train_pred = svm.predict(X_train_feats)
# Train accuracy
train_accuracy = np.mean( y_train_pred == y_train )
# Validation phase
y_val_pred = svm.predict(X_val_feats)
# Validation accuracy
val_accuracy = np.mean( y_val_pred == y_val )
results[lr,reg] = (train_accuracy,val_accuracy)
# Save best model
if val_accuracy > best_val:
best_val = val_accuracy
best_svm = svm
################################################################################
# END OF YOUR CODE #
################################################################################
# Print out results.
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print('lr %e reg %e train accuracy: %f val accuracy: %f' % (
lr, reg, train_accuracy, val_accuracy))
print('best validation accuracy achieved during cross-validation: %f' % best_val)
# Evaluate your trained SVM on the test set
y_test_pred = best_svm.predict(X_test_feats)
test_accuracy = np.mean(y_test == y_test_pred)
print(test_accuracy)
# An important way to gain intuition about how an algorithm works is to
# visualize the mistakes that it makes. In this visualization, we show examples
# of images that are misclassified by our current system. The first column
# shows images that our system labeled as "plane" but whose true label is
# something other than "plane".
examples_per_class = 8
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
for cls, cls_name in enumerate(classes):
idxs = np.where((y_test != cls) & (y_test_pred == cls))[0]
idxs = np.random.choice(idxs, examples_per_class, replace=False)
for i, idx in enumerate(idxs):
plt.subplot(examples_per_class, len(classes), i * len(classes) + cls + 1)
plt.imshow(X_test[idx].astype('uint8'))
plt.axis('off')
if i == 0:
plt.title(cls_name)
plt.show()
```
### Inline question 1:
Describe the misclassification results that you see. Do they make sense?
$\color{blue}{\textit Your Answer:}$
## Neural Network on image features
Earlier in this assigment we saw that training a two-layer neural network on raw pixels achieved better classification performance than linear classifiers on raw pixels. In this notebook we have seen that linear classifiers on image features outperform linear classifiers on raw pixels.
For completeness, we should also try training a neural network on image features. This approach should outperform all previous approaches: you should easily be able to achieve over 55% classification accuracy on the test set; our best model achieves about 60% classification accuracy.
```
# Preprocessing: Remove the bias dimension
# Make sure to run this cell only ONCE
print(X_train_feats.shape)
X_train_feats = X_train_feats[:, :-1]
X_val_feats = X_val_feats[:, :-1]
X_test_feats = X_test_feats[:, :-1]
print(X_train_feats.shape)
from cs231n.classifiers.neural_net import TwoLayerNet
input_dim = X_train_feats.shape[1]
hidden_dim = 500
num_classes = 10
#net = TwoLayerNet(input_dim, hidden_dim, num_classes)
best_net = None
best_val = -1
################################################################################
# TODO: Train a two-layer neural network on image features. You may want to #
# cross-validate various parameters as in previous sections. Store your best #
# model in the best_net variable. #
################################################################################
def generate_random_hyperparams(lr_min, lr_max, reg_min, reg_max, h_min, h_max):
lr = 10**np.random.uniform(lr_min,lr_max)
reg = 10**np.random.uniform(reg_min,reg_max)
hidden = np.random.randint(h_min, h_max)
return lr, reg, hidden
# Use of random search for hyperparameter search
for i in range(20):
lr, reg, hidden_dim = generate_random_hyperparams(-1, 0, -7, -4, 10, 500)
# Create a two-layer network
net = TwoLayerNet(input_dim, hidden_dim, num_classes)
# Train the network
stats = net.train(X_train_feats, y_train, X_val_feats, y_val,
num_iters=3000, batch_size=200,
learning_rate=lr, learning_rate_decay=0.95,
reg=reg, verbose=False)
# Predict on the training set
train_accuracy = (net.predict(X_train_feats) == y_train).mean()
# Predict on the validation set
val_accuracy = (net.predict(X_val_feats) == y_val).mean()
# Save best values
if val_accuracy > best_val:
best_val = val_accuracy
best_net = net
# Print results
print('lr %e reg %e hid %d train accuracy: %f val accuracy: %f' % (
lr, reg, hidden_dim, train_accuracy, val_accuracy))
print('best validation accuracy achieved: %f' % best_val)
################################################################################
# END OF YOUR CODE #
################################################################################
# Run your best neural net classifier on the test set. You should be able
# to get more than 55% accuracy.
test_acc = (best_net.predict(X_test_feats) == y_test).mean()
print(test_acc)
```
| github_jupyter |
# Le Bloc Note pour rapporter
Dans un notebook jupyter on peut rédiger des commentaires en langage naturel, intégrer des liens hypertextes et des images dans des cellules de type **`Markdown`**.
***
> Ce document est un notebook jupyter, pour bien vous familiariser avec cet environnement regardez cette rapide [Introduction](Introduction-Le_BN_pour_explorer.ipynb).
***
**Markdown** est un langage de description à balisage plus léger que HTML et donc plus rapide pour rédiger et publier un document sur le Web.
Aussi, il est de plus en plus utilisé : incontournable sur [GitHub](https://github.com/ "lien GitHub"), les forums d'[OpenClassroom](https://OpenClassroom.fr/ "lien OpenClassroom"), de [Stack Overflow](https://fr.wikipedia.org/wiki/Stack_Overflow "lien Wikipedia Stack Overflow")...
L'idée est de pouvoir mettre en forme du texte sans avoir besoin de recourir à la souris : en même temps que l'on écrit du contenu on indique par des symboles codifiés comment il faut l'afficher...
> <h3 class='fa fa-cogs' style="color: darkorange"> A faire vous-même </h3>
>
> Pour afficher le résultat du code **Markdown** proposé, basculer le type de la cellule de **`Code`** vers **`Markdown`**, puis appuyer sur le bouton <button class='fa fa-step-forward icon-step-forward btn btn-xs btn-default'></button> ou sur les touches **`<Maj+Entree>`** .
## Les titres :
```
# Titre de niveau 1
## Titre de niveau 2
### Titre de niveau 3
#### Titre de niveau 4
##### Titre de niveau 5
```
## Le corps de texte :
```
Sed quid est quod in hac causa maxime homines admirentur et reprehendant meum consilium, cum ego idem antea multa decreverim, que magis ad hominis dignitatem quam ad rei publicae necessitatem pertinerent ?
Supplicationem quindecim dierum decrevi sententia mea.
Rei publicae satis erat tot dierum quot C. Mario ; dis immortalibus non erat exigua eadem gratulatio quae ex maximis bellis.
Ergo ille cumulus dierum hominis est dignitati tributus.
Et prima post Osdroenam quam, ut dictum est, ab hac descriptione discrevimus, Commagena, nunc Euphratensis, clementer adsurgit, Hierapoli, vetere Nino et Samosata civitatibus amplis inlustris.
```
### Retour à la ligne et paragraphes
> <h3 class='fa fa-cogs' style="color: darkorange"> A faire vous-même </h3>
>
> Dans le [lorem ipsum](https://fr.wikipedia.org/wiki/Faux-texte "lien wikipedia") ci-dessus, insérer deux espaces à la fin d'une phrase pour forcer le retour à la ligne et insérer une ligne vide pour former des paragraphes.
### Italique
```
_Texte_ avec *emphase* en Italique
```
### Gras
```
__Texte__ plus **important** en Gras
```
### Gras et italique combinés
```
**_Texte_** à la fois en **gras** et en *italique*
```
### Barré
```
Texte barré ~~à supprimer~~
```
> <h3 class='fa fa-cogs' style="color: darkorange"> A faire vous-même </h3>
>
> Dans le [lorem ipsum](https://fr.wikipedia.org/wiki/Faux-texte "lien wikipedia") ci-dessus, formater certains éléments pour les afficher soit en *italique*, en **gras** ou ~~barré~~.
> <u>Remarque</u> : pour souligner un élément il faudra utiliser un code HTML.
## Les listes :
### Non ordonnée
```
* Un élement de ma liste ;
* Un autre élément de ma liste ;
* Un élément de ma sous-liste ;
* Un autre élément de ma sous-liste ;
* Encore un autre élément de ma liste.
```
> Remarque : On peut aussi utiliser un `+` ou `-` à la place de l'`*`.
### Ordonnée
```
1. Le premier élement de ma liste ;
1. Le second élément de ma liste ;
1. Le premier élément de ma sous-liste ;
1. Le second élément de ma sous-liste ;
1. Le troisième élément de ma liste.
```
## Les citations :
```
> une citation est un paragraphe ouvert par un chevron fermant
```
## Les traits horizontaux de séparation
```
***
---
```
## Tableau :
```
| Tables | Are | Cool |
|----------|:-------------:|-----:|
| col 1 is | left-aligned | 1600 |
| col 2 is | centered | 12 |
| col 3 is | right-aligned | 1 |
```
> <h3 class='fa fa-cogs' style="color: darkorange"> A faire vous-même </h3>
>
> On peut avantageusement utiliser un générateur de tableau comme : https://www.tablesgenerator.com/markdown_tables
## Image :
```

```
> Pour afficher une image, il faut commencer par un point d’exclamation. Puis indiquer le texte alternatif entre crochets. Ce dernier sera affiché si l’image n’est pas chargée et lu par les moteurs de recherche. Terminer par l’URL de l’image entre parenthèses. Cette URL peut être un lien absolu vers le web ou un chemin relatif de ce type : /dossier_images/nom_de_mon_image.jpg. Après le lien vers l’image, il est possible d’ajouter un titre lu par les navigateurs textuels et affiché au survol de l’image par les autres.
```

```
> Il n'est pas possible de gérer simplement la taille d'affichage d'une image en Markdown. Il faut soit dimensionner correctement l'image en amont, soit utiliser un code HTML adapté.
Pour compléter concernant les images, il est aussi possible d’insérer une image dans une cellule Markdown par le menu ``Edit>Insert Image`` ou tout simplement en glissant/déposant le fichier image depuis votre explorateur vers la cellule Markdown du Notebook.
La syntaxe générée automatiquement est alors de la forme ````
Inutile d’ajouter le fichier image dans le dossier du Notebook car il lui est alors « attaché ».
```
Insérer une image dans cette cellule...
```
## Lien hypertexte :
### Isolé :
```
http://ecmorlaix.fr/
```
### Inclu dans un paragraphe :
```
Le portail de l'[ECA.M](http://ecmorlaix.fr/ "Lien vers le portail des Etablissement Catholiques Associés de Morlaix")
```
### Sur une image :
```
[](http://ecmorlaix.fr/ "Lien vers le portail des Etablissement Catholiques Associés de Morlaix")
```
Il est également possible de faire des liens par références pour rendre le code Markdown plus lisible :
```
Je reçoit 10 fois plus de trafic de [Google] [1] que de [Yahoo] [2] ou [MSN] [3].
[1]: http://google.com/ "Google"
[2]: http://search.yahoo.com/ "Yahoo Search"
[3]: http://search.msn.com/ "MSN Search"
```
# Code :
### Elément de code en ligne
```
Texte avec un `élément de code`.
```
### Bloc de code
```
```python
# Voici un bout de code en Python
from numpy import *
from numpy.random import *
int(rint(rand()*5+1))
```
```
## Ressources :
* https://blog.wax-o.com/2014/04/tutoriel-un-guide-pour-bien-commencer-avec-markdown/
* https://fr.wikipedia.org/wiki/Markdown
* https://openclassrooms.com/courses/redigez-en-markdown
* Traduction française de la syntaxe complète de Markdown : https://michelf.ca/projets/php-markdown/syntaxe/
* Un éditeur de Markdown en ligne : https://stackedit.io/
* Une extension de navigateur pour rédiger des mails : https://markdown-here.com/
## A vous de jouer :
> <h3 class='fa fa-cogs' style="color: darkorange"> A faire vous-même </h3>
>
> Saisir votre texte balisé en code Markdown dans la cellule suivante, jupyter affichera le résultat mis en forme automatiquement...
***
> **Félicitations !** Vous êtes parvenu au bout des activités de ce bloc note.
> Vous êtes maintenant capable de rédiger en **Markdown** dans l'environnement interactif jupyter notebook.
> Pour explorer plus avant d'autres fonctionnalités de jupyter notebook repassez par le [Sommaire](index.ipynb).
***
<a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="Licence Creative Commons" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />Ce document est mis à disposition selon les termes de la <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">Licence Creative Commons Attribution - Partage dans les Mêmes Conditions 4.0 International</a>.
Pour toute question, suggestion ou commentaire : <a href="mailto:eric.madec@ecmorlaix.fr">eric.madec@ecmorlaix.fr</a>
| github_jupyter |
# A - Using TorchText with Your Own Datasets
In this series we have used the IMDb dataset included as a dataset in TorchText. TorchText has many canonical datasets included for classification, language modelling, sequence tagging, etc. However, frequently you'll be wanting to use your own datasets. Luckily, TorchText has functions to help you to this.
Recall in the series, we:
- defined the `Field`s
- loaded the dataset
- created the splits
As a reminder, the code is shown below:
```python
TEXT = data.Field()
LABEL = data.LabelField()
train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)
train_data, valid_data = train_data.split()
```
There are three data formats TorchText can read: `json`, `tsv` (tab separated values) and`csv` (comma separated values).
**In my opinion, the best formatting for TorchText is `json`, which I'll explain later on.**
## Reading JSON
Starting with `json`, your data must be in the `json lines` format, i.e. it must be something like:
```
{"name": "John", "location": "United Kingdom", "age": 42, "quote": ["i", "love", "the", "united kingdom"]}
{"name": "Mary", "location": "United States", "age": 36, "quote": ["i", "want", "more", "telescopes"]}
```
That is, each line is a `json` object. See `data/train.json` for an example.
We then define the fields:
```
from torchtext import data
from torchtext import datasets
NAME = data.Field()
SAYING = data.Field()
PLACE = data.Field()
```
Next, we must tell TorchText which fields apply to which elements of the `json` object.
For `json` data, we must create a dictionary where:
- the key matches the key of the `json` object
- the value is a tuple where:
- the first element becomes the batch object's attribute name
- the second element is the name of the `Field`
What do we mean when we say "becomes the batch object's attribute name"? Recall in the previous exercises where we accessed the `TEXT` and `LABEL` fields in the train/evaluation loop by using `batch.text` and `batch.label`. Here, to access the name we use `batch.n`, to access the location we use `batch.p`, etc.
A few notes:
* The order of the keys in the `fields` dictionary does not matter, as long as its keys match the `json` data keys.
- The `Field` name does not have to match the key in the `json` object, e.g. we use `PLACE` for the `"location"` field.
- When dealing with `json` data, not all of the keys have to be used, e.g. we did not use the `"age"` field.
- Also, if the values of `json` field are a string then the `Fields` tokenization is applied (default is to split the string on spaces), however if the values are a list then no tokenization is applied. Usually it is a good idea for the data to already be tokenized into a list, this saves time as you don't have to wait for TorchText to do it.
- The value of the `json` fields do not have to be the same type. Some examples can have their `"quote"` as a string, and some as a list. The tokenization will only get applied to the ones with their `"quote"` as a string.
- If you are using a `json` field, every single example must have an instance of that field, e.g. in this example all examples must have a name, location and quote. However, as we are not using the age field, it does not matter if an example does not have it.
```
fields = {'name': ('n', NAME), 'location': ('p', PLACE), 'quote': ('s', SAYING)}
```
We then create our datasets (`train_data` and `test_data`) with the `TabularDataset.splits` function.
The `path` argument specifices the top level folder common among both datasets, and the `train` and `test` arguments specify the filename of each dataset, e.g. here the train dataset is located at `data/train.json`.
We tell the function we are using `json` data, and pass in our `fields` dictionary defined previously.
```
train_data, test_data = data.TabularDataset.splits(
path = 'data',
train = 'train.json',
test = 'test.json',
format = 'json',
fields = fields
)
```
If you already had a validation dataset, the location of this can be passed as the `validation` argument.
```
train_data, valid_data, test_data = data.TabularDataset.splits(
path = 'data',
train = 'train.json',
validation = 'valid.json',
test = 'test.json',
format = 'json',
fields = fields
)
```
We can then view an example to make sure it has worked correctly.
Notice how the field names (`n`, `p` and `s`) match up with what was defined in the `fields` dictionary.
Also notice how the word `"United Kingdom"` in `p` has been split by the tokenization, whereas the `"united kingdom"` in `s` has not. This is due to what was mentioned previously, where TorchText assumes that any `json` fields that are lists are already tokenized and no further tokenization is applied.
```
print(vars(train_data[0]))
```
We can now use `train_data`, `test_data` and `valid_data` to build a vocabulary and create iterators, as in the other notebooks. We can access all attributes by using `batch.n`, `batch.p` and `batch.s` for the names, places and sayings, respectively.
## Reading CSV/TSV
`csv` and `tsv` are very similar, except csv has elements separated by commas and tsv by tabs.
Using the same example above, our `tsv` data will be in the form of:
```
name location age quote
John United Kingdom 42 i love the united kingdom
Mary United States 36 i want more telescopes
```
That is, on each row the elements are separated by tabs and we have one example per row. The first row is usually a header (i.e. the name of each of the columns), but your data could have no header.
You cannot have lists within `tsv` or `csv` data.
The way the fields are defined is a bit different to `json`. We now use a list of tuples, where each element is also a tuple. The first element of these inner tuples will become the batch object's attribute name, second element is the `Field` name.
Unlike the `json` data, the tuples have to be in the same order that they are within the `tsv` data. Due to this, when skipping a column of data a tuple of `None`s needs to be used, if not then our `SAYING` field will be applied to the `age` column of the `tsv` data and the `quote` column will not be used.
However, if you only wanted to use the `name` and `age` column, you could just use two tuples as they are the first two columns.
We change our `TabularDataset` to read the correct `.tsv` files, and change the `format` argument to `'tsv'`.
If your data has a header, which ours does, it must be skipped by passing `skip_header = True`. If not, TorchText will think the header is an example. By default, `skip_header` will be `False`.
```
fields = [('n', NAME), ('p', PLACE), (None, None), ('s', SAYING)]
train_data, valid_data, test_data = data.TabularDataset.splits(
path = 'data',
train = 'train.tsv',
validation = 'valid.tsv',
test = 'test.tsv',
format = 'tsv',
fields = fields,
skip_header = True
)
print(vars(train_data[0]))
```
Finally, we'll cover `csv` files.
This is pretty much the exact same as the `tsv` files, expect with the `format` argument set to `'csv'`.
```
fields = [('n', NAME), ('p', PLACE), (None, None), ('s', SAYING)]
train_data, valid_data, test_data = data.TabularDataset.splits(
path = 'data',
train = 'train.csv',
validation = 'valid.csv',
test = 'test.csv',
format = 'csv',
fields = fields,
skip_header = True
)
print(vars(train_data[0]))
```
## Why JSON over CSV/TSV?
1. Your `csv` or `tsv` data cannot be stored lists. This means data cannot be already be tokenized, thus everytime you run your Python script that reads this data via TorchText, it has to be tokenized. Using advanced tokenizers, such as the `spaCy` tokenizer, takes a non-negligible amount of time. Thus, it is better to tokenize your datasets and store them in the `json lines` format.
2. If tabs appear in your `tsv` data, or commas appear in your `csv` data, TorchText will think they are delimiters between columns. This will cause your data to be parsed incorrectly. Worst of all TorchText will not alert you to this as it cannot tell the difference between a tab/comma in a field and a tab/comma as a delimiter. As `json` data is essentially a dictionary, you access the data within the fields via its key, so do not have to worry about "surprise" delimiters.
## Iterators
Using any of the above datasets, we can then build the vocab and create the iterators.
```
NAME.build_vocab(train_data)
SAYING.build_vocab(train_data)
PLACE.build_vocab(train_data)
```
Then, we can create the iterators after defining our batch size and device.
By default, the train data is shuffled each epoch, but the validation/test data is sorted. However, TorchText doesn't know what to use to sort our data and it would throw an error if we don't tell it.
There are two ways to handle this, you can either tell the iterator not to sort the validation/test data by passing `sort = False`, or you can tell it how to sort the data by passing a `sort_key`. A sort key is a function that returns a key on which to sort the data on. For example, `lambda x: x.s` will sort the examples by their `s` attribute, i.e their quote. Ideally, you want to use a sort key as the `BucketIterator` will then be able to sort your examples and then minimize the amount of padding within each batch.
We can then iterate over our iterator to get batches of data. Note how by default TorchText has the batch dimension second.
```
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
BATCH_SIZE = 1
train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits(
(train_data, valid_data, test_data),
sort = False, #don't sort test/validation data
batch_size=BATCH_SIZE,
device=device)
train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits(
(train_data, valid_data, test_data),
sort_key = lambda x: x.s, #sort by s attribute (quote)
batch_size=BATCH_SIZE,
device=device)
print('Train:')
for batch in train_iterator:
print(batch)
print('Valid:')
for batch in valid_iterator:
print(batch)
print('Test:')
for batch in test_iterator:
print(batch)
```
| github_jupyter |
# Shapelets and the Shapelet Transform with sktime
Introduced in [1], a shapelet is a time series subsequences that is identified as being representative of class membership. Shapelets are a powerful approach for measuring _phase-independent_ similarity between time series; they can occur at any point within a series and offer _interpretable_ results for how matches occur. The original research extracted shapelets to build a decision tree classifier.
The example below illustrates how leaf shape can be represented as a one-dimensional time series (blue line) to distinguish between two species.[2]
<img src = "img/leaf_types.png">
<img src = "img/verdena_shapelet.png">
The highlighted red subsection of the time series (i.e., "subsequences") above is the shapelet that distinguishes *Verbena urticifolia* from *Urtica dioica*.
## The Shapelet Transform
Much research emphasis has been placed on shapelet-based approaches for time series classification (TSC) since the original research was proposed. The current state-of-the-art for shapelets is the **shapelet transform** (ST) [3, 4]. The transform improves upon the original use of shapelets by separating shapelet extraction from the classification algorithm, allowing interpretable phase-independent classification of time series with any standard classification algorithm (such as random/rotation forest, neural networks, nearest neighbour classifications, ensembles of all, etc.). To facilitate this, rather than recursively assessing data for the best shapelet, the transform evaluates candidate shapelets in a single procedure to rank them based on information gain. Then, given a set of _k_ shapelets, a time series can be transformed into _k_ features by calculating the distance from the series to each shapelet. By transforming a dataset in this manner any vector-based classification algorithm can be applied to a shapelet-transformed time series problem while the interpretability of shapelets is maintained through the ranked list of the _best_ shapelets during transformation.
Shapelets can provide interpretable results, as seen in the figure below:
<img src = "img/leaves_shapelets.png">
The shapelet has "discovered" where the two plant species distinctly differ. *Urtica dioica* has a stem that connects to the leaf at almost 90 degrees, whereas the stem of *Verbena urticifolia* connects to the leaf at a wider angle.
Having found shapelet, its distance to the nearest matching subsequence in all objects in the database can be recorded. Finally, a simple decision tree classifier can be built to determine whether an object $Q$ has a subsequence within a certain distance from shapelet $I$.
<img src = "img/shapelet_classifier.png">
#### References
[1] Ye, Lexiang, and Eamonn Keogh. "Time series shapelets: a novel technique that allows accurate, interpretable and fast classification." Data mining and knowledge discovery 22, no. 1-2 (2011): 149-182.
[2] Ye, Lexiang, and Eamonn Keogh. "Time series shapelets: a new primitive for data mining." In Proceedings of the 15th ACM SIGKDD international conference on Knowledge discovery and data mining, pp. 947-956. 2009.
[3] Lines, Jason, Luke M. Davis, Jon Hills, and Anthony Bagnall. "A shapelet transform for time series classification." In Proceedings of the 18th ACM SIGKDD international conference on Knowledge discovery and data mining, pp. 289-297. ACM, 2012.
[4] Hills, Jon, Jason Lines, Edgaras Baranauskas, James Mapp, and Anthony Bagnall. "Classification of time series by shapelet transformation." Data Mining and Knowledge Discovery 28, no. 4 (2014): 851-881.
[5] Bostrom, Aaron, and Anthony Bagnall. "Binary shapelet transform for multiclass time series classification." In Transactions on Large-Scale Data-and Knowledge-Centered Systems XXXII, pp. 24-46. Springer, Berlin, Heidelberg, 2017.
## Example: The Shapelet Transform in sktime
The following workbook demonstrates a full workflow of using the shapelet transform in `sktime` with a `scikit-learn` classifier with the [OSU Leaf](http://www.timeseriesclassification.com/description.php?Dataset=OSULeaf) dataset, which consists of one dimensional outlines of six leaf classes: *Acer Circinatum*, *Acer Glabrum*, *Acer Macrophyllum*, *Acer Negundo*, *Quercus Garryana* and *Quercus Kelloggii*.
```
from sktime.datasets import load_osuleaf
from sktime.transformations.panel.shapelets import ContractedShapeletTransform
train_x, train_y = load_osuleaf(split="train", return_X_y=True)
test_x, test_y = load_osuleaf(split="test", return_X_y=True)
# How long (in minutes) to extract shapelets for.
# This is a simple lower-bound initially;
# once time is up, no further shapelets will be assessed
time_contract_in_mins = 1
# The initial number of shapelet candidates to assess per training series.
# If all series are visited and time remains on the contract then another
# pass of the data will occur
initial_num_shapelets_per_case = 10
# Whether or not to print on-going information about shapelet extraction.
# Useful for demo/debugging
verbose = 2
st = ContractedShapeletTransform(
time_contract_in_mins=time_contract_in_mins,
num_candidates_to_sample_per_case=initial_num_shapelets_per_case,
verbose=verbose,
)
st.fit(train_x, train_y)
%matplotlib inline
import matplotlib.pyplot as plt
# for each extracted shapelet (in descending order of quality/information gain)
for s in st.shapelets[0:5]:
# summary info about the shapelet
print(s)
# plot the series that the shapelet was extracted from
plt.plot(train_x.iloc[s.series_id, 0], "gray")
# overlay the shapelet onto the full series
plt.plot(
list(range(s.start_pos, (s.start_pos + s.length))),
train_x.iloc[s.series_id, 0][s.start_pos : s.start_pos + s.length],
"r",
linewidth=3.0,
)
plt.show()
# for each extracted shapelet (in descending order of quality/information gain)
for i in range(0, min(len(st.shapelets), 5)):
s = st.shapelets[i]
# summary info about the shapelet
print("#" + str(i) + ": " + str(s))
# overlay shapelets
plt.plot(
list(range(s.start_pos, (s.start_pos + s.length))),
train_x.iloc[s.series_id, 0][s.start_pos : s.start_pos + s.length],
)
plt.show()
import time
from sklearn.ensemble.forest import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sktime.datasets import load_osuleaf
train_x, train_y = load_osuleaf(split="train", return_X_y=True)
test_x, test_y = load_osuleaf(split="test", return_X_y=True)
# example pipeline with 1 minute time limit
pipeline = Pipeline(
[
(
"st",
ContractedShapeletTransform(
time_contract_in_mins=time_contract_in_mins,
num_candidates_to_sample_per_case=10,
verbose=False,
),
),
("rf", RandomForestClassifier(n_estimators=100)),
]
)
start = time.time()
pipeline.fit(train_x, train_y)
end_build = time.time()
preds = pipeline.predict(test_x)
end_test = time.time()
print("Results:")
print("Correct:")
correct = sum(preds == test_y)
print("\t" + str(correct) + "/" + str(len(test_y)))
print("\t" + str(correct / len(test_y)))
print("\nTiming:")
print("\tTo build: " + str(end_build - start) + " secs")
print("\tTo predict: " + str(end_test - end_build) + " secs")
```
| github_jupyter |
# Explore Weather Trends
## Purpose
This project from Udacity's Data Analyst Nanodegree Program analyzes local and global temperature data and compares the temperature trends in selected cities with overall global temperature trends.
## Dataset
There are three tables in the database provided in the Udacity's workspace:
- `city_list` - This contains a list of cities and countries in the database.
- `city_data` - This contains the average temperatures for each city by year (ºC).
- `global_data` - This contains the average global temperatures by year (ºC).
Data for analysis is extracted using the following SQL query:
```
SELECT city.year,
city.city,
city.avg_temp as city_avg_temp,
global.avg_temp as glob_avg_temp
FROM city_data city, global_data global
WHERE city.year = global.year AND
city in ('Prague', 'Johannesburg', 'New York',
'Shanghai', 'Sydney', 'Rio De Janeiro')
```
An advantage of this solution is just one file to work with, a disadvantage is a need to reconstruct the global temperature data as multiple cities are compared.
Data is downloaded from Udacity's workspace and uploaded to GitHub for further processing.
```
# Import dependencies
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Download data
data_url = 'https://raw.githubusercontent.com/lustraka/Data_Analysis_Workouts/main/Explore_Weather_Trends/temp_data.csv'
data = pd.read_csv(data_url)
print(data.head())
# `series` dictionary holds average temperature series for the globe and selected cities
series = {'globe' : data.groupby('year').glob_avg_temp.first()}
for city in data.city.unique():
series[city] = data.loc[data.city == city, ['year', 'city_avg_temp']].set_index('year').squeeze()
```
## Visualization
The temperature trends are visualized in line graphs that are most commonly used to plot contiuous data. Because the points are physically connected via the line, it implies a connection between points.
To smooth out the lines and make trends more observable, the chart plots the *moving average* over a decade using `.rolling(10).mean()` method of the Pandas' Series object.
## Prague
The line chart below compares average temperatures in Prague with the global temperatures.
```
fig, ax = plt.subplots(figsize=(10,6))
ct = data.loc[data.city == 'Prague', ['year', 'city_avg_temp']].set_index('year').squeeze()
ax.plot(series['globe'].rolling(10).mean(), label='global')
ax.plot(series['Prague'].rolling(10).mean(), label='local')
ax.set_title('Prague')
ax.set_xlabel('year')
ax.set_ylabel('temperature [°C]')
ax.legend()
plt.show()
```
**Observations**:
- The average temperature in Prague has nearly the same level as the global average temperature.
- Also the trend of Prague's temperature is similar to the global temperature trend.
- First 40 years of 19th century was unusually cold.
- From the beginning of 20th century the average temperature is growing and this trend is accelerating in last 40 years.
## Multiple Cities
The line charts below compares average temperatures in Prague, Johannesburg, New York, Shanghai, Sydney, and Rio De Janeiro.
```
cities = data.city.unique()
cities.shape=(3,2)
fig, ax = plt.subplots(3, 2, figsize=(10,10), sharex='all', sharey='all')
glob_temp_moving = series['globe'].rolling(10).mean()
for c in [0,1]:
for r in [0,1,2]:
ax[r,c].plot(glob_temp_moving, label='global')
ax[r,c].plot(series[cities[r,c]].rolling(10).mean(), label='local')
ax[r,c].set_title(cities[r,c])
ax[r,c].set_xlabel('year')
ax[r,c].set_ylabel('temperature [°C]')
ax[r,c].legend()
plt.show()
# `stats` dictionary calculates same basic statistics of the dataset
stats = {}
for k,v in series.items():
stats[k] = [v.index[0], len(v), v.mean(), series['globe'].corr(v)]
# Statistical data is presented using a dataframe
pd.set_option('max_columns', None) # To print all columns
print(pd.DataFrame(stats, index=['First observation', 'Number of observations', 'Average temperature [°C]', 'Correlation']))
```
**Observations**:
- Out of the selected cities, Prague's average temperature (8.23 °C) is the closest to the global average temperature (8.36 °C).
- Prague and New York have the complete set of observations starting in year 1750.
- New York has a little higher average temperature than the globe, followed by Johannesburg, Shanghai, Sydney, and Rio de Janeiro, whose average temperature is 23.79 °C.
- Tempartures in all cities are highly correlated with global temperatures. Correlation of data starting around 1850 is higher, probably due to lesser accuracy of older data.
## References
- [Explainer: How do scientists measure global temperature?](https://www.carbonbrief.org/explainer-how-do-scientists-measure-global-temperature)
- [WEATHER IN HISTORY 1800 TO 1849 AD](https://premium.weatherweb.net/weather-in-history-1800-to-1849-ad/)
| github_jupyter |
# Approximating Likelihood Ratios with Calibrated Discriminative Classifiers: Signal Strength in Mixture Models
In this notebook, techniques described in the paper [Approximating Likelihood Ratios with Calibrated Discriminative Classifiers](https://arxiv.org/abs/1506.02169) (in particular section 3.4) are adapted to signal strength fits in models with multiple background components. Toy data is generated with `make_classification` for that purpose.
```
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
import xgboost as xgb
```
The central piece of this example can not be found in this notebook, but gets imported from [geeksw](https://github.com/guitargeek/geeksw/):
```
from geeksw.stats.likelihood import PairwiseLikelihoodRatioModel, minimize_likelihood
```
## Sample Generation
How many components will our toy model have? The first component will be defined as the signal component. The weights for the true mixture also have to be defined. The weights should be of length `n_classes - 1`, as the weight of the last component is inferred automatically from the normalization.
```
n_classes = 2
weights = [0.05]
n_events = 500000
```
Define the random statue for toy model and samle splitting:
```
random_state = 79
```
Generate events from toy model:
```
X, y = make_classification(n_samples=n_events,
n_features=20,
n_informative=5,
random_state=random_state,
n_classes=n_classes,
weights=weights)
```
I split the generated events in 3 parts:
1. __training__: will be used to train the classifiers for distinguishing one component from another
1. __calibration__: the likelihood ratios are calibrated by running the classifiers on this sample and histogramming of the predictions
1. __testing__: about 80 % of the generated events will be in this subsample. It is used to validate the calibration by repeadetly drawing random subsamples of __testing__ that are of the same size as the sample used for __calibration__, veryfinig the calibration is consitent on a statistical basis
```
X_train, X_, y_train, y_ = train_test_split(X, y, test_size=0.9, random_state=random_state)
X_calib, X_test, y_calib, y_test = train_test_split(X_, y_, test_size=0.9, random_state=random_state+99)
print("n_test: {0}".format(len(X_train)))
print("n_calib: {0}".format(len(X_calib)))
print("n_test: {0}".format(len(X_test)))
```
## Training the Classifiers and Make Pairwise Predictions
Let's train `(n**2 - n)/2` [xgboost](https://xgboost.readthedocs.io/en/latest/) classifiers for pairwise classification of the components. The number $n$ stands here for the number of components.
I use `binary:logitraw` to obtain the classifier score before the logistic transformtion as my model predictions. The logistic transformation is not necessary, as we will recalibrate the output anyway, and the score before the transformation behaves more Gaussian-like which is better for the later treatment.
```
params = dict(objective="binary:logitraw")
num_round = 100
models = [[None] * n_classes for i in range(n_classes)]
for i in range(n_classes):
for j in range(n_classes):
if i <= j:
continue
print(f"Training model {i} vs {j}...")
m = np.logical_or(y_train == i, y_train == j)
dtrain = xgb.DMatrix(X_train[m], label=np.array(y_train[m] == i, dtype=np.int))
models[i][j] = xgb.train(params, dtrain, num_round)
models[j][i] = models[i][j]
```
Now, let's run the models on all our samples:
```
preds_train = np.zeros((len(y_train), n_classes, n_classes))
preds_calib = np.zeros((len(y_calib), n_classes, n_classes))
preds_test = np.zeros((len(y_test), n_classes, n_classes))
dtrain = xgb.DMatrix(X_train)
dcalib = xgb.DMatrix(X_calib)
dtest = xgb.DMatrix(X_test)
for i in range(n_classes):
for j in range(n_classes):
if i == j:
continue
preds_train[:,i,j] = models[i][j].predict(dtrain)
preds_calib[:,i,j] = models[i][j].predict(dcalib)
preds_test[:,i,j] = models[i][j].predict(dtest)
if i < j:
preds_train[:,i,j] = -preds_train[:,i,j]
preds_calib[:,i,j] = -preds_calib[:,i,j]
preds_test[:,i,j] = -preds_test[:,i,j]
```
For every event, the predictions will be a symmetric square matrix of size `n_classes`, where the element `[i,j]` corresponds to the score of the event being in component `i` versus component `j`. The diagonal is zero, as we can't separate a component from itself. Here, as an example the scores for the first event in the testing sample:
```
preds_test[0]
```
As we anticipate, predictions from the _0 vs 1_ model are highest for the component 0, lowest for the component 1 and somewhere in between for the other components (if any).
```
for i in range(n_classes):
plt.hist(preds_test[:,0,1][y_test == i], bins=100, histtype="step", density=True, label="component "+str(i))
plt.xlabel("Score for 0 vs 1 model")
plt.legend()
plt.show()
```
## Precomputing the Likelihood Ratios
For the likelihood-free inference, in the case where our model parameter is only a factor in the weight of the signal component (also called the signal strength $\mu$), we need to compute the likelihood ratios that a given event is in one component versus another, so we can ultimately apply formula 3.5 from [the paper](https://arxiv.org/pdf/1506.02169.pdf).
If not for overtraining effects, one could simply use the classification scores after logistic transformation. In reality, we need to recalibrate. This can be done for example with kernel density estimates, histogram based methods or isotonic regression (as the substitute for the likelihood ratio increases monotonically).
I choose histogramming for the recalibration, as it seems to me this is most promising to also incorporate systematic uncertainties later. A natural next step would be for example to include the uncertainty due to limited statistics in the calibration sample, which could be accounted for with Poission errors in the number of entries.
### Finding the Binning of the Histograms
The usual question for histogram-based methods is the realization of the binning. The number of bins for each pairwise likelihood ratio is a free parameter of my approach. With the number of bins given, the location of their edges will be found by throwing decision trees at the scores. The dicision boundaries of these simple trees will then be used as the bin edges.
### The `PairwiseLikelihoodRatioModel` Class
This class is used for the transformation from the matrix with binary scores to likelihood ratios based on the histogram-based approach described above. It's `fit()` function takes the binary scores and true component indices for the calibration sample and fills the histograms. The `predict()` function takes just the binary score matrix, looks up the correcponding likelihood ratios in the histograms and returns them.
```
likelihood_model = PairwiseLikelihoodRatioModel(n_bins=40).train(preds_calib, y_calib)
```
### Evaluating the Likelihood Ratio for a Given Signal Strength
### Calibration Sample
Ok, let us start with the classic likelihood scan over the signal strength $\mu$.
For this, we will use the last method of the `PairwiseLikelihoodRatioModel` class, which is called `make_likelihood_function()`. You have to pass it a binary scores matrix and it will return a function. This function is the actual likelihood function for the observed scores, and you only need to pass it the signal strength $\mu$ to evaluatue it.
We will do the likelihood scan for the calibration sample, so we can cross-check if the calibration was performed correctly. If everything went well, the minimum should be exactly at 1.0.
```
mus = np.linspace(0.5, 1/0.5, 200)
res = np.zeros_like(mus)
func = likelihood_model.make_likelihood_function(preds_calib)
for k, m in enumerate(mus):
res[k] = func(m)
plt.plot(mus, res, label="calibration sample")
plt.ylabel("likelihood ratio")
plt.xlabel(r"$\mu$")
plt.legend()
plt.show()
print("best mu: " + str(minimize_likelihood(func)[0]))
```
If the minimum is not be at one, this can mean one of two things:
1. The classifiers were not fitting the likelihood ratios well
2. You did not choose enough bins for the decision trees in the likelihood model, therefore underfitting the likelihood ratio and introducing a bias
### Testing Sample
Finally, we will apply the model to some unseen testing samples. To generate these testing samples, we first draw a random number $n_i$ from a Poisson distribution with $\lambda$ = `len(X_calib)` and then take $n_i$ random events out of the testing sample.
For each drawn sample, we compute the signal strength and uncertainty by minimizing the log-likelihood.
```
n_samples = 10
fitted_mu = np.zeros(n_samples)
fitted_mu_err = np.zeros(n_samples)
is_in_confidence_interval = np.zeros(n_samples, dtype=np.bool)
for l in range(n_samples):
n_tot = np.random.poisson(lam=len(y_calib), size=1)[0]
selection_test = np.random.choice(np.arange(len(preds_test)), size=n_tot)
func = likelihood_model.make_likelihood_function(preds_test[selection_test])
best_mu, interval = minimize_likelihood(func)
fitted_mu[l] = best_mu
is_in_confidence_interval[l] = interval[1] > 1. and interval[0] < 1.
fitted_mu_err[l] = np.max(np.abs(interval - best_mu))
plt.hist(fitted_mu, bins=20, histtype="step")
plt.xlabel(r"$\mu$")
plt.show()
frac_in_cf = np.sum(is_in_confidence_interval)/len(is_in_confidence_interval)
print("fraction in confidence interval: {0:.2f} %".format(frac_in_cf * 100))
pulls = (fitted_mu - 1) / fitted_mu_err
print("mean of pull distribution: {0:.4f}".format(np.mean(pulls)))
print("std of pull distribution: {0:.4f}".format(np.std(pulls)))
```
If the behaviour of our likelihood substitute is correct, about 69 % of the experiments should have covered the true value with their confidence interval. The mean of the pull distribution should be zero and it's standard deviation one.
A bias in the pull distribution or other inconsistencies could either stem from the same issues which caused the best fit in the cross-check with the calibration sample to not be 1, or, in case the cross-check was successful, indicate an over-fitting of the calibration, i.e. too many bins in the histograms.
| github_jupyter |
# Regression with Amazon SageMaker XGBoost algorithm
_**Single machine training for regression with Amazon SageMaker XGBoost algorithm**_
---
---
## Contents
1. [Introduction](#Introduction)
2. [Setup](#Setup)
1. [Fetching the dataset](#Fetching-the-dataset)
2. [Data Ingestion](#Data-ingestion)
3. [Training the XGBoost model](#Training-the-XGBoost-model)
1. [Plotting evaluation metrics](#Plotting-evaluation-metrics)
4. [Set up hosting for the model](#Set-up-hosting-for-the-model)
1. [Import model into hosting](#Import-model-into-hosting)
2. [Create endpoint configuration](#Create-endpoint-configuration)
3. [Create endpoint](#Create-endpoint)
5. [Validate the model for use](#Validate-the-model-for-use)
---
## Introduction
This notebook demonstrates the use of Amazon SageMaker’s implementation of the XGBoost algorithm to train and host a regression model. We use the [Abalone data](https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression.html) originally from the [UCI data repository](https://archive.ics.uci.edu/ml/datasets/abalone). More details about the original dataset can be found [here](https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.names). In the libsvm converted [version](https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression.html), the nominal feature (Male/Female/Infant) has been converted into a real valued feature. Age of abalone is to be predicted from eight physical measurements.
---
## Setup
This notebook was created and tested on an ml.m4.4xlarge notebook instance.
Let's start by specifying:
1. 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.
1. 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 with a the appropriate full IAM role arn string(s).
```
%%time
import os
import boto3
import re
from sagemaker import get_execution_role
role = get_execution_role()
region = boto3.Session().region_name
bucket='<bucket-name>' # put your s3 bucket name here, and create s3 bucket
prefix = 'sagemaker/DEMO-xgboost-regression'
# customize to your bucket where you have stored the data
bucket_path = 'https://s3-{}.amazonaws.com/{}'.format(region,bucket)
```
### Fetching the dataset
Following methods split the data into train/test/validation datasets and upload files to S3.
```
%%time
import io
import boto3
import random
def data_split(FILE_DATA, FILE_TRAIN, FILE_VALIDATION, FILE_TEST, PERCENT_TRAIN, PERCENT_VALIDATION, PERCENT_TEST):
data = [l for l in open(FILE_DATA, 'r')]
train_file = open(FILE_TRAIN, 'w')
valid_file = open(FILE_VALIDATION, 'w')
tests_file = open(FILE_TEST, 'w')
num_of_data = len(data)
num_train = int((PERCENT_TRAIN/100.0)*num_of_data)
num_valid = int((PERCENT_VALIDATION/100.0)*num_of_data)
num_tests = int((PERCENT_TEST/100.0)*num_of_data)
data_fractions = [num_train, num_valid, num_tests]
split_data = [[],[],[]]
rand_data_ind = 0
for split_ind, fraction in enumerate(data_fractions):
for i in range(fraction):
rand_data_ind = random.randint(0, len(data)-1)
split_data[split_ind].append(data[rand_data_ind])
data.pop(rand_data_ind)
for l in split_data[0]:
train_file.write(l)
for l in split_data[1]:
valid_file.write(l)
for l in split_data[2]:
tests_file.write(l)
train_file.close()
valid_file.close()
tests_file.close()
def write_to_s3(fobj, bucket, key):
return boto3.Session(region_name=region).resource('s3').Bucket(bucket).Object(key).upload_fileobj(fobj)
def upload_to_s3(bucket, channel, filename):
fobj=open(filename, 'rb')
key = prefix+'/'+channel
url = 's3://{}/{}/{}'.format(bucket, key, filename)
print('Writing to {}'.format(url))
write_to_s3(fobj, bucket, key)
```
### Data ingestion
Next, we read the dataset from the existing repository into memory, for preprocessing prior to training. This processing could be done *in situ* by Amazon Athena, Apache Spark in Amazon EMR, Amazon Redshift, etc., assuming the dataset is present in the appropriate location. Then, the next step would be to transfer the data to S3 for use in training. For small datasets, such as this one, reading into memory isn't onerous, though it would be for larger datasets.
```
%%time
import urllib.request
# Load the dataset
FILE_DATA = 'abalone'
urllib.request.urlretrieve("https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/abalone", FILE_DATA)
#split the downloaded data into train/test/validation files
FILE_TRAIN = 'abalone.train'
FILE_VALIDATION = 'abalone.validation'
FILE_TEST = 'abalone.test'
PERCENT_TRAIN = 70
PERCENT_VALIDATION = 15
PERCENT_TEST = 15
data_split(FILE_DATA, FILE_TRAIN, FILE_VALIDATION, FILE_TEST, PERCENT_TRAIN, PERCENT_VALIDATION, PERCENT_TEST)
#upload the files to the S3 bucket
upload_to_s3(bucket, 'train', FILE_TRAIN)
upload_to_s3(bucket, 'validation', FILE_VALIDATION)
upload_to_s3(bucket, 'test', FILE_TEST)
```
## Training the XGBoost model
After setting training parameters, we kick off training, and poll for status until training is completed, which in this example, takes between 5 and 6 minutes.
```
from sagemaker.amazon.amazon_estimator import get_image_uri
container = get_image_uri(region, 'xgboost')
%%time
import boto3
from time import gmtime, strftime
job_name = 'DEMO-xgboost-regression-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print("Training job", job_name)
#Ensure that the training and validation data folders generated above are reflected in the "InputDataConfig" parameter below.
create_training_params = \
{
"AlgorithmSpecification": {
"TrainingImage": container,
"TrainingInputMode": "File"
},
"RoleArn": role,
"OutputDataConfig": {
"S3OutputPath": bucket_path + "/" + prefix + "/single-xgboost"
},
"ResourceConfig": {
"InstanceCount": 1,
"InstanceType": "ml.m4.4xlarge",
"VolumeSizeInGB": 5
},
"TrainingJobName": job_name,
"HyperParameters": {
"max_depth":"5",
"eta":"0.2",
"gamma":"4",
"min_child_weight":"6",
"subsample":"0.7",
"silent":"0",
"objective":"reg:linear",
"num_round":"50"
},
"StoppingCondition": {
"MaxRuntimeInSeconds": 3600
},
"InputDataConfig": [
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": bucket_path + "/" + prefix + '/train',
"S3DataDistributionType": "FullyReplicated"
}
},
"ContentType": "libsvm",
"CompressionType": "None"
},
{
"ChannelName": "validation",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": bucket_path + "/" + prefix + '/validation',
"S3DataDistributionType": "FullyReplicated"
}
},
"ContentType": "libsvm",
"CompressionType": "None"
}
]
}
client = boto3.client('sagemaker', region_name=region)
client.create_training_job(**create_training_params)
import time
status = client.describe_training_job(TrainingJobName=job_name)['TrainingJobStatus']
print(status)
while status !='Completed' and status!='Failed':
time.sleep(60)
status = client.describe_training_job(TrainingJobName=job_name)['TrainingJobStatus']
print(status)
```
Note that the "validation" channel has been initialized too. The SageMaker XGBoost algorithm actually calculates RMSE and writes it to the CloudWatch logs on the data passed to the "validation" channel.
### Plotting evaluation metrics
Evaluation metrics for the completed training job are available in CloudWatch. We can pull the area under curve metric for the validation data set and plot it to see the performance of the model over time.
```
%matplotlib inline
from sagemaker.analytics import TrainingJobAnalytics
metric_name = 'validation:rmse'
metrics_dataframe = TrainingJobAnalytics(training_job_name=job_name, metric_names=[metric_name]).dataframe()
plt = metrics_dataframe.plot(kind='line', figsize=(12,5), x='timestamp', y='value', style='b.', legend=False)
plt.set_ylabel(metric_name);
```
## Set up hosting for the model
In order to set up hosting, we have to import the model from training to hosting.
### Import model into hosting
Register the model with hosting. This allows the flexibility of importing models trained elsewhere.
```
%%time
import boto3
from time import gmtime, strftime
model_name=job_name + '-model'
print(model_name)
info = client.describe_training_job(TrainingJobName=job_name)
model_data = info['ModelArtifacts']['S3ModelArtifacts']
print(model_data)
primary_container = {
'Image': container,
'ModelDataUrl': model_data
}
create_model_response = client.create_model(
ModelName = model_name,
ExecutionRoleArn = role,
PrimaryContainer = primary_container)
print(create_model_response['ModelArn'])
```
### Create endpoint configuration
SageMaker supports configuring REST endpoints in hosting with multiple models, e.g. for A/B testing purposes. In order to support this, customers create an endpoint configuration, that describes the distribution of traffic across the models, whether split, shadowed, or sampled in some way. In addition, the endpoint configuration describes the instance type required for model deployment.
```
from time import gmtime, strftime
endpoint_config_name = 'DEMO-XGBoostEndpointConfig-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print(endpoint_config_name)
create_endpoint_config_response = client.create_endpoint_config(
EndpointConfigName = endpoint_config_name,
ProductionVariants=[{
'InstanceType':'ml.m4.xlarge',
'InitialVariantWeight':1,
'InitialInstanceCount':1,
'ModelName':model_name,
'VariantName':'AllTraffic'}])
print("Endpoint Config Arn: " + create_endpoint_config_response['EndpointConfigArn'])
```
### Create endpoint
Lastly, the customer creates the endpoint that serves up the 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 9-11 minutes to complete.
```
%%time
import time
endpoint_name = 'DEMO-XGBoostEndpoint-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print(endpoint_name)
create_endpoint_response = client.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=endpoint_config_name)
print(create_endpoint_response['EndpointArn'])
resp = client.describe_endpoint(EndpointName=endpoint_name)
status = resp['EndpointStatus']
print("Status: " + status)
while status=='Creating':
time.sleep(60)
resp = client.describe_endpoint(EndpointName=endpoint_name)
status = resp['EndpointStatus']
print("Status: " + status)
print("Arn: " + resp['EndpointArn'])
print("Status: " + status)
```
## Validate the model for use
Finally, the customer can now validate the model for use. They can obtain the endpoint from the client library using the result from previous operations, and generate classifications from the trained model using that endpoint.
```
runtime_client = boto3.client('runtime.sagemaker', region_name=region)
```
Start with a single prediction.
```
!head -1 abalone.test > abalone.single.test
%%time
import json
from itertools import islice
import math
import struct
file_name = 'abalone.single.test' #customize to your test file
with open(file_name, 'r') as f:
payload = f.read().strip()
response = runtime_client.invoke_endpoint(EndpointName=endpoint_name,
ContentType='text/x-libsvm',
Body=payload)
result = response['Body'].read()
result = result.decode("utf-8")
result = result.split(',')
result = [math.ceil(float(i)) for i in result]
label = payload.strip(' ').split()[0]
print ('Label: ',label,'\nPrediction: ', result[0])
```
OK, a single prediction works. Let's do a whole batch to see how good is the predictions accuracy.
```
import sys
import math
def do_predict(data, endpoint_name, content_type):
payload = '\n'.join(data)
response = runtime_client.invoke_endpoint(EndpointName=endpoint_name,
ContentType=content_type,
Body=payload)
result = response['Body'].read()
result = result.decode("utf-8")
result = result.split(',')
preds = [float((num)) for num in result]
preds = [math.ceil(num) for num in preds]
return preds
def batch_predict(data, batch_size, endpoint_name, content_type):
items = len(data)
arrs = []
for offset in range(0, items, batch_size):
if offset+batch_size < items:
results = do_predict(data[offset:(offset+batch_size)], endpoint_name, content_type)
arrs.extend(results)
else:
arrs.extend(do_predict(data[offset:items], endpoint_name, content_type))
sys.stdout.write('.')
return(arrs)
```
The following helps us calculate the Median Absolute Percent Error (MdAPE) on the batch dataset.
```
%%time
import json
import numpy as np
with open(FILE_TEST, 'r') as f:
payload = f.read().strip()
labels = [int(line.split(' ')[0]) for line in payload.split('\n')]
test_data = [line for line in payload.split('\n')]
preds = batch_predict(test_data, 100, endpoint_name, 'text/x-libsvm')
print('\n Median Absolute Percent Error (MdAPE) = ', np.median(np.abs(np.array(labels) - np.array(preds)) / np.array(labels)))
```
### Delete Endpoint
Once you are done using the endpoint, you can use the following to delete it.
```
client.delete_endpoint(EndpointName=endpoint_name)
```
| github_jupyter |
## Preprocessing
```
# from google.colab import drive
# drive.mount('/content/drive')
# cd drive/MyDrive/NLP_Project
# !pip install pandas matplotlib tqdm seaborn sklearn numpy graphviz
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import GridSearchCV
import numpy as np
import warnings
warnings.filterwarnings('always')
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
import pickle as pk
trainData = np.load('../../../dataFinal/npy_files/fin_noWE_t2_train.npy')
trainLabels = open('../../../dataFinal/finalTrainLabels.labels', 'r').readlines()
testData = np.load('../../../dataFinal/npy_files/fin_noWE_t2_test.npy')
testLabels = open('../../../dataFinal/finalTestLabels.labels', 'r').readlines()
validationData = np.load('../../../dataFinal/npy_files/fin_noWE_t2_trial.npy')
validationLabels = open('../../../dataFinal/finalDevLabels.labels', 'r').readlines()
for i in tqdm(range(len(trainLabels))):
trainLabels[i] = int(trainLabels[i])
for i in tqdm(range(len(testLabels))):
testLabels[i] = int(testLabels[i])
for i in tqdm(range(len(validationLabels))):
validationLabels[i] = int(validationLabels[i])
trainLabels = np.array(trainLabels)
testLabels = np.array(testLabels)
validationLabels = np.array(validationLabels)
trainLabels = trainLabels.reshape((-1, ))
testLabels = testLabels.reshape((-1, ))
validationLabels = validationLabels.reshape((-1, ))
X_train, X_test, y_train, y_test, X_val, y_val = trainData, testData, trainLabels, testLabels, validationData, validationLabels
```
## Estimators
### Range 1
```
# accuracy = []
# predVal = []
itr= [150, 250, 350, 450]
for i in tqdm(range(len(itr))):
clf = AdaBoostClassifier(algorithm="SAMME.R",n_estimators=itr[i], random_state=0)
clf.fit(trainData, trainLabels)
y_pred = clf.predict(testData)
y_true = testLabels
print("Test Data:")
print("Classification report for case: ",itr[i])
print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
y_pred = clf.predict(trainData)
y_true = trainLabels
print("Train Data:")
print("Classification report for case: ",itr[i])
print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
y_pred = clf.predict(validationData)
y_true = validationLabels
print("Validation Data:")
print("Classification report for case: ",itr[i])
print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
#predVal.append(itr[i])
# plt.plot(predVal, accuracy)
# plt.xlabel('Num estimators')
# plt.ylabel('Accuracy')
# plt.title('Accuracy vs Num estimators')
# plt.show()
```
### Range 2
```
# ada_accuracy = []
# ada_predVal = []
# itr= [150, 175, 200, 225]
# for i in tqdm(range(len(itr))):
# clf = AdaBoostClassifier(algorithm="SAMME.R",n_estimators=itr[i], random_state=0)
# clf.fit(trainData, trainLabels)
# y_pred = clf.predict(testData)
# y_true = testLabels
# print("Test Data:")
# print("Classification report for case: ",itr[i])
# print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
# print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
# y_pred = clf.predict(trainData)
# y_true = trainLabels
# print("Train Data:")
# print("Classification report for case: ",itr[i])
# print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
# print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
# y_pred = clf.predict(validationData)
# y_true = validationLabels
# print("Validation Data:")
# print("Classification report for case: ",itr[i])
# print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
# print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
# # ada_accuracy.append(round(accuracy_score(y_pred = y_pred, y_true = testLabels) * 100,2))
# # ada_predVal.append(itr[i])
# # plt.plot(ada_predVal, ada_accuracy)
# # plt.xlabel('Num estimators')
# # plt.ylabel('ada_Accuracy')
# # plt.title('ada_Accuracy vs Num estimators')
# # plt.show()
```
## Algrithm
### "SAMME"
```
clf = AdaBoostClassifier(algorithm="SAMME", n_estimators=200, random_state=0)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_true = testLabels
print("Test Data:")
accuracy = round(accuracy_score(y_pred = y_pred, y_true = y_true) * 100,2)
print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
y_pred = clf.predict(X_train)
y_true = trainLabels
print("Train Data:")
print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
y_pred = clf.predict(X_val)
y_true = validationLabels
print("Validation Data:")
print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
```
### "SAMME.R" Better
```
X_train, X_test, y_train, y_test = trainData, testData, trainLabels, testLabels
clf = AdaBoostClassifier(algorithm="SAMME.R",n_estimators=200, random_state=0)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_true = testLabels
print("Test Data:")
accuracy = round(accuracy_score(y_pred = y_pred, y_true = y_true) * 100,2)
print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
y_pred = clf.predict(X_train)
y_true = trainLabels
print("Train Data:")
print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
y_pred = clf.predict(X_val)
y_true = validationLabels
print("Validation Data:")
print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
```
## AdaBoost Final Results
### algorithm="SAMME.R",n_estimators=200
### Accuracy: 27.24
```
# clf = AdaBoostClassifier(algorithm="SAMME.R",n_estimators=200, random_state=0)
# clf.fit(trainData, trainLabels)
# y_pred = clf.predict(X_test)
# y_true = testLabels
# print("Test Data:")
# accuracy = round(accuracy_score(y_pred = y_pred, y_true = y_true) * 100,2)
# print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
# print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
# y_pred = clf.predict(X_train)
# y_true = trainLabels
# print("Train Data:")
# print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
# print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
# y_pred = clf.predict(X_val)
# y_true = validationLabels
# print("Validation Data:")
# print("Accuracy % : ",round(accuracy_score(y_pred = y_pred, y_true=y_true) * 100,2))
# print(classification_report(y_true,y_pred,labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
filename = 'finalModel_AB_NoWE'
pk.dump(clf,open(filename,'wb'))
```
| github_jupyter |
<a href="https://colab.research.google.com/github/abdulazeem/AWS---Chandralingam/blob/master/Untitled6.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import os
import zipfile
list1 = [1, 4, 5, 6, 9]
# Import PyDrive and associated libraries.
# This only needs to be done once per notebook.
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# Authenticate and create the PyDrive client.
# This only needs to be done once per notebook.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
fid = drive.ListFile({'q':"title='dataset.zip'"}).GetList()[0]['id']
f = drive.CreateFile({'id': fid})
f.GetContentFile('dataset.zip')
!unzip "/content/dataset.zip"
import os
path =os.getcwd()
os.getcwd()
import glob
file_list = glob.glob(os.path.join(path,'dataset/*.jpg'))
len(file_list)
import time
from keras.applications import vgg16
from keras.preprocessing.image import load_img,img_to_array
from keras.models import Model
from keras.applications.imagenet_utils import preprocess_input
from tensorflow.python.keras.applications import vgg16
import time
import os
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
file_list[:10]
imagelist = []
feat_list=[]
start_time = time.time()
for i, imagepath in enumerate(file_list):
print(" Status: %s / %s" %(i, len(file_list)), end="\r")
img = load_img(imagepath, target_size=(224, 224))
img_data = img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
prcsd_img = preprocess_input(img_data)
feat_data = np.array(feature_extractor.predict(prcsd_img))
imagelist.append(img_data)
feat_list.append(feat_data.flatten())
#features = np.array(model.predict(img_data))
#featurelist.append(features.flatten())
print("--- %s seconds ---" % (time.time() - start_time))
images = np.vstack(imagelist)
images.shape
a=np.vstack(feat_list)
from sklearn.cluster import KMeans
# Clustering
number_clusters = 6
kmeans = KMeans(n_clusters=number_clusters, random_state=0).fit(np.array(feat_list))
kmeans.labels_[:10]
# Copy images renamed by cluster
# Check if target dir exists
targetdir = "/content/targetdir"
try:
os.makedirs(targetdir)
except OSError:
pass
# Copy with cluster name
print("\n")
for i, m in enumerate(kmeans.labels_):
print(" Copy: %s / %s" %(i, len(kmeans.labels_)), end="\r")
shutil.copy(file_list[i], targetdir + str(m) + "_" + str(i) + ".jpg")
load_img()
for i in range(0, len(closest_imgs)):
original = load_img(closest_imgs[i], target_size=(imgs_width, imgs_height))
plt.imshow(original)
plt.show()
print('similarity score:', closest_imgs_scores[i])
import shutil
sample = "/content/sample"
os.makedirs(sample)
os.getcwd()
kmeans.predict(feat_list[0])
feat_list[0]
wcss = []
for i in range(1, 16):
kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)
kmeans.fit(np.array(feat_list))
wcss.append(kmeans.inertia_)
plt.plot(range(1, 16), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
from sklearn.metrics import silhouette_score
sil =[]
kmax=10
for k in range(2,kmax+1):
kmeans = KMeans(n_clusters = k, init = 'k-means++', random_state = 42)
kmeans.fit(np.array(feat_list))
labels = kmeans.labels_
sil.append(silhouette_score(np.array(feat_list),labels, metric = 'euclidean'))
def cluster_labels(ext_feat, no_of_clusters):
kmeans = KMeans
from sklearn.
sil
plt.plot(range(2, kmax+1), sil)
plt.title('Silhouette')
plt.xlabel('Number of clusters')
plt.ylabel('Silhouete Score')
plt.show()
# Copy images renamed by cluster
# Check if target dir exists
try:
os.makedirs(targetdir)
except OSError:
pass
# Copy with cluster name
print("\n")
for i, m in enumerate(kmeans.labels_):
print(" Copy: %s / %s" %(i, len(kmeans.labels_)), end="\r")
shutil.copy(filelist[i], targetdir + str(m) + "_" + str(i) + ".jpg")
images = np.vstack(imagelist)
processed_imgs = preprocess_input(images.copy())
processed_imgs[0].shape
img_features = feature_extractor.predict(processed_imgs)
img_features.shape
from keras.applications import (vgg16, vgg19, xception, inception_v3,
inception_resnet_v2, mobilenet,
densenet, nasnet, mobilenet_v2)
vgg_model = vgg16.VGG16(weights='imagenet')
feature_extractor = Model(inputs=vgg_model.input, outputs=vgg_model.get_layer('fc2').output)
feature_extractor.summary()
def create_sim_df(imgs_features, files):
cosine_sim = cosine_similarity(imgs_features)
cosine_sim_df = pd.DataFrame(cosine_sim, columns=files, index=files)
return cosine_sim_df
def retrieve_similar_images(given_image, cosine_similarity_df):
print('original image')
original = load_img(given_image, target_size=(imgs_width, imgs_height))
plt.imshow(original)
plt.show()
print('most similar products........')
closest_imgs = cosine_similarity_df[given_image].sort_values(ascending=False)[1:nb_closest_images + 1].index
closest_imgs_scores = cosine_similarity_df[given_image].sort_values(ascending=False)[1:nb_closest_images + 1]
for i in range(0, len(closest_imgs)):
original = load_img(closest_imgs[i], target_size=(imgs_width, imgs_height))
plt.imshow(original)
plt.show()
print('similarity score:{}, Cluster:{}'.format(closest_imgs_scores[i], images[i]))
import os
import zipfile
local_zip = '/tmp/data.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('/tmp/dataset')
zip_ref.close()
# load an example dataset
from vega_datasets import data
cars = data.cars()
import altair as alt
interval = alt.selection_interval()
base = alt.Chart(cars).mark_point().encode(
y='Miles_per_Gallon',
color=alt.condition(interval, 'Origin', alt.value('lightgray'))
).properties(
selection=interval
)
base.encode(x='Acceleration') | base.encode(x='Horsepower')
import os
os.getcwd()
class FirstClass(object):
def hi(self):
print('Hello!')
class SecondClass(object):
def hi(self):
print('Bonjour!')
class FinalClass(SecondClass, FirstClass):
pass
FinalClass().hi()
A5
import os
import zipfile
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
file_path = os.path.join('cats_and_dogs_filtered.zip')
file = zipfile.ZipFile(file_path, 'r')
file.extractall('cats_and_dogs_au')
file.close()
print(len(os.listdir('cats_and_dogs_au')))
base = os.path.join('cats_and_dogs_au/cats_and_dogs_filtered')
print(os.listdir(base))
train = os.path.join(base, 'train')
validate = os.path.join(base, 'validation')
train_gen = ImageDataGenerator(rescale=1.0/255.,
rotation_range=0.2,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
test_gen = ImageDataGenerator(rescale=1.0/255.)
training_gen = train_gen.flow_from_directory(train,
target_size=(150,150),
batch_size=20,
class_mode='binary')
validation_gen = test_gen.flow_from_directory(validate,
target_size=(150,150),
batch_size=20,
class_mode='binary')
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(16, (3,3), input_shape=(150,150,3),activation='relu' ),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.001), metrics=['accuracy'])
print(model.summary())
history = model.fit(training_gen,
steps_per_epoch=100,
validation_data=validation_gen,
validation_steps=50,
epochs=5,
verbose=2)
train_acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
epochs = range(len(train_acc))
plt.plot(epochs, train_acc)
plt.plot(epochs, val_acc)
plt.figure()
train_loss = history.history['loss']
val_loss = history.history['val_loss']
plt.plot(epochs, train_loss)
plt.plot(epochs, val_loss)
plt.show()
import os
import zipfile
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
file_path = os.path.join('cats_and_dogs_filtered.zip')
fileobj= zipfile.ZipFile(file_path,'r')
fileobj.extractall('cats_and_dogs')
fileobj.close()
base = 'cats_and_dogs/cats_and_dogs_filtered'
print(os.listdir(base))
train_dir = os.path.join(base, 'train')
validation_dir =os.path.join(base, 'validation')
train_cats_dir = os.path.join(train_dir, 'cats')
train_dogs_dir = os.path.join(train_dir, 'dogs')
validation_cats_dir = os.path.join(validation_dir, 'cats')
validation_dogs_dir = os.path.join(validation_dir, 'dogs')
print('Total Train Cats : ', len(os.listdir(train_cats_dir)))
print('Total Train Dogs : ', len(os.listdir(train_dogs_dir)))
print('Total Validation Cats : ', len(os.listdir(validation_cats_dir)))
print('Total Vaidation Dogs : ', len(os.listdir(validation_dogs_dir)))
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(16, (3,3), input_shape=(150,150,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.001), metrics = ['accuracy'])
print(model.summary)
#Prepare Dataset
train_gen = ImageDataGenerator(rescale=1.0/255.)
valid_gen = ImageDataGenerator(rescale=1.0/255.)
train_generator = train_gen.flow_from_directory(train_dir,
batch_size=20,
class_mode='binary',
target_size=(150,150))
valid_generator = valid_gen.flow_from_directory(validation_dir,
batch_size=20,
class_mode='binary',
target_size=(150,150))
history= model.fit(train_generator,
steps_per_epoch=100,
validation_data=valid_generator,
validation_steps=50,
verbose=2,
epochs=10)
train_horse_dir = os.path.join('/tmp/horse-or-human/horses')
train_human_dir = os.path.join('/tmp/horse-or-human/humans')
train_horse_names = os.listdir(train_horse_dir)
print(train_horse_names[:10])
train_human_names=os.listdir(train_human_dir)
print(train_human_names[:10])
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1/255)
train_generator = train_datagen.flow_from_directory('/tmp/horse-or-human',
target_size = (300,300),
batch_size=128,
class_mode='binary')
model = tf.keras.models.Sequential()
model = tf.keras.models.Sequential([tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300,300,3)),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.summary()
model.compile(optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.001), loss = 'binary_crossentropy', metrics = ['accuracy'])
history = model.fit(train_generator, steps_per_epoch=8, epochs=2, verbose=1)
model.save('checking.h5')
import numpy as np
import tensorflow as tf
def solution_model():
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0], dtype=float)
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(units=1, input_shape=[1])
])
model.compile(loss='sgd', optimizer = 'mean_squared_error')
model.fit(xs, ys, epochs=500)
return model
# Note that you'll need to save your model as a .h5 like this.
# When you press the Submit and Test button, your saved .h5 model will
# be sent to the testing infrastructure for scoring
# and the score will be returned to you.
if __name__ == '__main__':
model = solution_model()
model.save("mymodel.h5")
import json
import tensorflow as tf
import numpy as np
import urllib
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
def solution_model():
url = 'https://storage.googleapis.com/download.tensorflow.org/data/sarcasm.json'
urllib.request.urlretrieve(url, 'sarcasm.json')
# DO NOT CHANGE THIS CODE OR THE TESTS MAY NOT WORK
vocab_size = 1000
embedding_dim = 16
max_length = 120
trunc_type='post'
padding_type='post'
oov_tok = "<OOV>"
training_size = 20000
sentences = []
labels = []
# YOUR CODE HERE
with open('sarcasm.json', 'r') as f:
data=json.load(f)
for item in data:
sentences.append(item['headline'])
labels.append(item['is_sarcastic'])
training_sentences = sentences[0:training_size]
testing_sentences = sentences[training_size:]
training_labels = labels[0:training_size]
testing_labels = labels[training_size:]
tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)
tokenizer.fit_on_texts(training_sentences)
training_sequences = tokenizer.texts_to_sequences(training_sentences)
training_padded = pad_sequences(training_sequences, maxlen=max_length, padding=padding_type,
truncating=trunc_type)
testing_sequences = tokenizer.texts_to_sequences(testing_sentences)
testing_padded = pad_sequences(testing_sequences, maxlen=max_length, padding=padding_type,
truncating=trunc_type)
model = tf.keras.models.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
tf.keras.layers.Dense(24, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy', optimizer ='adam', metrics=['accuracy'])
training_padded = np.array(training_padded)
testing_padded = np.array(testing_padded)
training_labels = np.array(training_labels)
testing_labels = np.array(testing_labels)
model.fit(training_padded, training_labels, epochs = 10,
validation_data=(testing_padded, testing_labels), verbose=1)
return model
# Note that you'll need to save your model as a .h5 like this.
# When you press the Submit and Test button, your saved .h5 model will
# be sent to the testing infrastructure for scoring
# and the score will be returned to you.
if __name__ == '__main__':
model = solution_model()
model.save("mymodel.h5")
import csv
import tensorflow as tf
import numpy as np
import urllib
# DO NOT CHANGE THIS CODE
def windowed_dataset(series, window_size, batch_size, shuffle_buffer):
series = tf.expand_dims(series, axis=-1)
ds = tf.data.Dataset.from_tensor_slices(series)
ds = ds.window(window_size + 1, shift=1, drop_remainder=True)
ds = ds.flat_map(lambda w: w.batch(window_size + 1))
ds = ds.shuffle(shuffle_buffer)
ds = ds.map(lambda w: (w[:-1], w[1:]))
return ds.batch(batch_size).prefetch(1)
def solution_model():
url = 'https://storage.googleapis.com/download.tensorflow.org/data/Sunspots.csv'
urllib.request.urlretrieve(url, 'sunspots.csv')
time_step = []
sunspots = []
with open('sunspots.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader)
for row in reader:
sunspots.append(float(row[2]))
time_step.append(int(row[0]))
series = np.array(sunspots)
time = np.array(time_step)
# DO NOT CHANGE THIS CODE
# This is the normalization function
min = np.min(series)
max = np.max(series)
series -= min
series /= max
time = np.array(time_step)
# The data should be split into training and validation sets at time step 3000
# DO NOT CHANGE THIS CODE
split_time = 3000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
# DO NOT CHANGE THIS CODE
window_size = 30
batch_size = 32
shuffle_buffer_size = 1000
train_set = windowed_dataset(x_train, window_size=window_size, batch_size=batch_size, shuffle_buffer=shuffle_buffer_size)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv1D(filters = 60, kernel_size=5, strides=1, padding='causal',activation='relu'),
tf.keras.layers.LSTM(60, return_sequences=True),
tf.keras.layers.LSTM(60, return_sequences=True),
tf.keras.layers.LSTM(60, return_sequences=True),
tf.keras.layers.Dense(30, activation='relu'),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(1)
])
model.compile(loss=tf.keras.losses.Huber(), optimizer = tf.keras.optimizers.SGD(learning_rate=1e-5, momentum=0.9), metrics =['mae'])
model.fit(train_set, epochs = 150)
# PLEASE NOTE IF YOU SEE THIS TEXT WHILE TRAINING -- IT IS SAFE TO IGNORE
# BaseCollectiveExecutor::StartAbort Out of range: End of sequence
# [[{{node IteratorGetNext}}]]
#
# YOUR CODE HERE TO COMPILE AND TRAIN THE MODEL
return model
# Note that you'll need to save your model as a .h5 like this.
# When you press the Submit and Test button, your saved .h5 model will
# be sent to the testing infrastructure for scoring
# and the score will be returned to you.
if __name__ == '__main__':
model = solution_model()
model.save("mymodel.h5")
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.optimizers import RMSprop
data = tfds.load("iris")
data = tfds.load("iris")
data['train']
import tensorflow as tf
print(tf.version)
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.optimizers import RMSprop
def preprocess(features):
f, l = next(iter(features))
# Should return features and one-hot encoded labels
return f,l
def solution_model():
train_dataset = data.map(preprocess).batch(10)
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(10, input_sape=(4,), activation = 'relu'),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(optimizer = tf.keras.optimizers.Adam(learning_rate=0.001), loss='sparse_categorical_crossentropy', metrics =['accuracy'])
model.fit(train_dataset, epochs=200)
return model
# Note that you'll need to save your model as a .h5 like this.
# When you press the Submit and Test button, your saved .h5 model will
# be sent to the testing infrastructure for scoring
# and the score will be returned to you.
if __name__ == '__main__':
model = solution_model()
model.save("mymodel.h5")
# ======================================================================
# There are 5 questions in this exam with increasing difficulty from 1-5.
# Please note that the weight of the grade for the question is relative
# to its difficulty. So your Category 1 question will score significantly
# less than your Category 5 question.
#
# Don't use lambda layers in your model.
# You do not need them to solve the question.
# Lambda layers are not supported by the grading infrastructure.
#
# You must use the Submit and Test button to submit your model
# at least once in this category before you finally submit your exam,
# otherwise you will score zero for this category.
# ======================================================================
#
# Computer Vision with CNNs
#
# Build a classifier for Rock-Paper-Scissors based on the rock_paper_scissors
# TensorFlow dataset.
#
# IMPORTANT: Your final layer should be as shown. Do not change the
# provided code, or the tests may fail
#
# IMPORTANT: Images will be tested as 150x150 with 3 bytes of color depth
# So ensure that your input layer is designed accordingly, or the tests
# may fail.
#
# NOTE THAT THIS IS UNLABELLED DATA.
# You can use the ImageDataGenerator to automatically label it
# and we have provided some starter code.
import urllib.request
import zipfile
import tensorflow as tf
from keras_preprocessing.image import ImageDataGenerator
def solution_model():
url = 'https://storage.googleapis.com/download.tensorflow.org/data/rps.zip'
urllib.request.urlretrieve(url, 'rps.zip')
local_zip = 'rps.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('tmp/')
zip_ref.close()
TRAINING_DIR = "tmp/rps/"
training_datagen = ImageDataGenerator(rescale=1./255.0,
rotation_range=0.2,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
train_generator = training_datagen.flow_from_directory(TRAINING_DIR,
target_size= (150,150),
class_mode='categorical')
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150,150,3)),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPool2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
model.fit(train_generator, epochs = 8, verbose =1)
return model
# Note that you'll need to save your model as a .h5 like this.
# When you press the Submit and Test button, your saved .h5 model will
# be sent to the testing infrastructure for scoring
# and the score will be returned to you.
if __name__ == '__main__':
model = solution_model()
model.save("mymodel.h5")
dataset = tfds.load(name="iris", batch_size=32, as_supervised=True)
mnist_train = dataset["train"].repeat().prefetch(1)
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(10, input_shape=(4,), activation = 'relu'),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd")
model.fit(mnist_train, epochs=5)
```
| github_jupyter |
# Experiment Initialization
Here, I define the terms of my experiment, among them the location of the files in S3 (bucket and folder name), and each of the video prefixes (everything before the file extension) that I want to track.
Note that these videos should be similar-ish: while we can account for differences in mean intensities between videos, particle sizes should be approximately the same, and (slightly less important) particles should be moving at about the same order of magnitude speed. In this experiment, these videos were taken in 0.4% agarose gel at 100x magnification and 100.02 fps shutter speeds with nanoparticles of about 100nm in diameter.
```
to_track = []
result_futures = {}
start_knot = 30 #Must be unique number for every run on Cloudknot.
remote_folder = 'Gel_Studies/11_09_18_gel_experiment' #Folder in AWS S3 containing files to be analyzed
bucket = 'ccurtis.data'
vids = 20
gels = ['0_4', '0_6', '0_8', '1_0', '1_2']
for gel in gels:
for num in range(1, vids+1):
#to_track.append('100x_0_4_1_2_gel_{}_bulk_vid_{}'.format(vis, num))
to_track.append('Gels_{}_XY{}'.format(gel, '%02d' % num))
to_track[35]
```
The videos used with this analysis are fairly large (2048 x 2048 pixels and 651 frames), and in cases like this, the tracking algorithm can quickly eat up RAM. In this case, we chose to crop the videos to 512 x 512 images such that we can run our jobs on smaller EC2 instances with 16GB of RAM.
Note that larger jobs can be made with user-defined functions such that splitting isn't necessary-- or perhaps an intermediate amount of memory that contains splitting, tracking, and msd calculation functions all performed on a single EC2 instance.
The compiled functions in the knotlets module require access to buckets on AWS. In this case, we will be using a publicly (read-only) bucket. If users want to run this notebook on their own, will have to transfer files from nancelab.publicfiles to their own bucket, as it requires writing to S3 buckets.
```
import diff_classifier.knotlets as kn
for prefix in to_track[35:]:
kn.split(prefix, remote_folder=remote_folder, bucket=bucket)
```
## Tracking predictor
Tracking normally requires user input in the form of tracking parameters e.g. particle radius, linking max distance, max frame gap etc. When large datasets aren't required, each video can be manageably manually tracked using the TrackMate GUI. However, when datasets get large e.g. >20 videos, this can become extremely arduous. For videos that are fairly similar, you can get away with using similar tracking parameters across all videos. However, one parameter that is a little more noisy that the others is the quality filter value. Quality is a numerical value that approximate how likely a particle is to be "real."
In this case, I built a predictor that estimates the quality filter value based on intensity distributions from the input images. Using a relatively small training dataset (5-20 videos), users can get fairly good estimates of quality filter values that can be used in parallelized tracking workflows.
Note: in the current setup, the predictor should be run in Python 3. While the code will run in Python 3, there are differences between the random number generators in Python2 and Python3 that I was not able to control for.
```
import os
import diff_classifier.imagej as ij
import boto3
import os.path as op
import diff_classifier.aws as aws
import diff_classifier.knotlets as kn
import numpy as np
from sklearn.externals import joblib
```
The regress_sys function should be run twice. When have_output is set to False, it generates a list of files that the user should manually track using Trackmate. Once the quality filter values are found, they can be used as input (y) to generate a regress object that can predict quality filter values for additional videos. Once y is assigned, set have_output to True and re-run the cell.
```
tnum=20 #number of training datasets
pref = []
for num in to_track:
for row in range(0, 4):
for col in range(0, 4):
pref.append("{}_{}_{}".format(num, row, col))
y = np.array([6.2, 4.7, 4.6, 5.2, 5.1, 4.0, 3.9, 3.2, 3.0, 3.8, 3.0, 3.6, 3.3, 5.6, 3.7, 3.0, 5.2, 4.1, 4.5, 4.4])
# Creates regression object based of training dataset composed of input images and manually
# calculated quality cutoffs from tracking with GUI interface.
regress = ij.regress_sys(remote_folder, pref, y, tnum, randselect=True,
have_output=True, bucket_name=bucket)
#Read up on how regress_sys works before running.
#Pickle object
filename = 'regress.obj'
with open(filename,'wb') as fp:
joblib.dump(regress,fp)
import boto3
s3 = boto3.client('s3')
aws.upload_s3(filename, remote_folder+'/'+filename, bucket_name=bucket)
```
Users should input all tracking parameters into the tparams object. Note that the quality value will be overwritten by values found using the quality predictor found above.
```
tparams1 = {'radius': 5.0, 'threshold': 0.0, 'do_median_filtering': False,
'quality': 5.0, 'xdims': (0, 511), 'ydims': (1, 511),
'median_intensity': 300.0, 'snr': 0.0, 'linking_max_distance': 12.0,
'gap_closing_max_distance': 20.0, 'max_frame_gap': 8,
'track_duration': 20.0}
# tparams2 = {'radius': 4.0, 'threshold': 0.0, 'do_median_filtering': False,
# 'quality': 10.0, 'xdims': (0, 511), 'ydims': (1, 511),
# 'median_intensity': 300.0, 'snr': 0.0, 'linking_max_distance': 8.0,
# 'gap_closing_max_distance': 12.0, 'max_frame_gap': 6,
# 'track_duration': 20.0}
```
## Cloudknot setup
Cloudknot requires the user to define a function that will be sent to multiple computers to run. In this case, the function knotlets.tracking will be used. We create a docker image that has the required installations (defined by the requirements.txt file from diff_classifier on Github, and the base Docker Image below that has Fiji pre-installed in the correct location.
Note that I modify the Docker image below such that the correct version of boto3 is installed. For some reason, versions later than 1.5.28 error out, so I specified 5.28 as the correct version. Run my_image.build below to double-check that the Docker image is successfully built prior to submitting the job to Cloudknot.
```
import cloudknot as ck
import os.path as op
github_installs=('https://github.com/ccurtis7/diff_classifier.git@Chad')
#my_image = ck.DockerImage(func=kn.tracking, base_image='arokem/python3-fiji:0.3', github_installs=github_installs)
my_image = ck.DockerImage(func=kn.assemble_msds, base_image='arokem/python3-fiji:0.3', github_installs=github_installs)
docker_file = open(my_image.docker_path)
docker_string = docker_file.read()
docker_file.close()
req = open(op.join(op.split(my_image.docker_path)[0], 'requirements.txt'))
req_string = req.read()
req.close()
new_req = req_string[0:req_string.find('\n')-4]+'5.28'+ req_string[req_string.find('\n'):]
req_overwrite = open(op.join(op.split(my_image.docker_path)[0], 'requirements.txt'), 'w')
req_overwrite.write(new_req)
req_overwrite.close()
my_image.build("0.1", image_name="test_image")
```
The object all_maps is an iterable containing all the inputs sent to Cloudknot. This is useful, because if the user needs to modify some of the tracking parameters for a single video, this can be done prior to submission to Cloudknot.
```
names = []
all_maps = []
for prefix in to_track:
for i in range(0, 4):
for j in range(0, 4):
names.append('{}_{}_{}'.format(prefix, i, j))
all_maps.append(('{}_{}_{}'.format(prefix, i, j), remote_folder, bucket, 'regress.obj',
4, 4, (512, 512), tparams1))
all_maps
```
The Cloudknot knot object sets up the compute environment which will run the code. Note that the name must be unique. Every time you submit a new knot, you should change the name. I do this with the variable start_knot, which I vary for each run.
If larger jobs are anticipated, users can adjust both RAM and storage with the memory and image_id variables. Memory specifies the amount of RAM to be used. Users can build a customized AMI with as much space as they need, and enter the ID into image_ID. Read the Cloudknot documentation for more details.
```
ck.aws.set_region('us-east-1')
knot = ck.Knot(name='download_and_track_{}_d{}'.format('chad1', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures = knot.map(all_maps[0:400], starmap=True)
ck.aws.set_region('us-east-1')
knot.clobber()
len(all_maps)
ck.aws.set_region('us-east-2')
knot1 = ck.Knot(name='download_and_track_{}_d{}'.format('chad2', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures1 = knot1.map(all_maps[400:800], starmap=True)
ck.aws.set_region('us-east-2')
knot1.clobber()
ck.aws.set_region('us-east-2')
knot2 = ck.Knot(name='download_and_track_{}_d{}'.format('chad3', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures2 = knot2.map(all_maps[800:1200], starmap=True)
ck.aws.set_region('us-east-2')
knot2.clobber()
ck.aws.set_region('us-west-1')
knot3 = ck.Knot(name='download_and_track_{}_d{}'.format('chad4', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures3 = knot3.map(all_maps[1200:1600], starmap=True)
ck.aws.set_region('us-west-1')
knot3.clobber()
ck.aws.set_region('us-west-1')
result_futures4 = knot3.map(all_maps[800:1200], starmap=True)
ck.aws.set_region('us-west-1')
knot4 = ck.Knot(name='download_and_track_{}_d{}'.format('chad5', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures4 = knot4.map(all_maps3, starmap=True)
knot4.clobber()
ck.aws.set_region('us-west-1')
knot7 = ck.Knot(name='download_and_track_{}_d{}'.format('chad7', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures7 = knot7.map(all_maps3, starmap=True)
knot7.clobber()
ck.aws.set_region('us-west-1')
knot6 = ck.Knot(name='download_and_track_{}_d{}'.format('chad6', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures6 = knot6.map(all_maps2, starmap=True)
knot6.clobber()
ck.aws.set_region('us-west-1')
knot8 = ck.Knot(name='download_and_track_{}_d{}'.format('chad8', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures8 = knot8.map(all_maps2, starmap=True)
knot8.clobber()
ck.aws.set_region('us-west-1')
knot8 = ck.Knot(name='download_and_track_{}_d{}'.format('chad8', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures8 = knot8.map(all_maps2, starmap=True)
ck.aws.set_region('us-west-1')
knot9 = ck.Knot(name='download_and_track_{}_d{}'.format('chad9', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures9 = knot9.map(all_maps2, starmap=True)
knot9.clobber()
knot.clobber()
knot2 = ck.Knot(name='download_and_track_{}_b{}'.format('chad91', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures2 = knot2.map(all_maps3, starmap=True)
ck.aws.set_region('us-east-1')
knot2.clobber()
knot3 = ck.Knot(name='download_and_track_{}_b{}'.format('chad92', start_knot),
docker_image = my_image,
memory = 144000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
names = []
all_maps2 = []
for prefix in to_track:
all_maps2.append((prefix, remote_folder, bucket, (512, 512), 651, 4, 4))
all_maps2
result_futures3 = knot3.map(all_maps2, starmap=True)
knot2.clobber()
missing = []
all_maps2 = []
import boto3
import botocore
s3 = boto3.resource('s3')
for prefix in to_track:
try:
s3.Object(bucket, '{}/features_{}.csv'.format(remote_folder, prefix)).load()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
missing.append(prefix)
all_maps2.append((prefix, remote_folder, bucket, (512, 512), 651, 4, 4))
else:
print('Something else has gone wrong')
len(all_maps2)
missing
for prefix in missing:
kn.assemble_msds(prefix, remote_folder, bucket=bucket)
print('Done with {}'.format(prefix))
result_futures4 = knot4.map(all_maps3, starmap=True)
knot4.clobber()
knot3 = ck.Knot(name='download_and_track_{}_b{}'.format('chad33', start_knot),
docker_image = my_image,
memory = 64000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-015a1b4cd3895860b', #May need to change this line
pars_policies=('AmazonS3FullAccess',),
)
result_futures5 = knot3.map(all_maps2, starmap=True)
knot3.clobber()
ck.aws.get_region()
ck.aws.set_region('us-east-1')
ck.aws.get_region()
knot2 = ck.Knot(name='download_and_track_{}_b{}'.format('chad2', start_knot),
docker_image = my_image,
memory = 144000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-0e00afdf500081a0d', #May need to change this line
pars_policies=('AmazonS3FullAccess',))
result_futures2 = knot2.map(all_maps, starmap=True)
knot3 = ck.Knot(name='download_and_track_{}_b{}'.format('chad3', start_knot),
docker_image = my_image,
memory = 144000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-0e00afdf500081a0d', #May need to change this line
pars_policies=('AmazonS3FullAccess',))
result_futures3 = knot3.map(all_maps, starmap=True)
knot4 = ck.Knot(name='download_and_track_{}_b{}'.format('chad4', start_knot),
docker_image = my_image,
memory = 144000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-0e00afdf500081a0d', #May need to change this line
pars_policies=('AmazonS3FullAccess',))
result_futures4 = knot4.map(all_maps, starmap=True)
knot5 = ck.Knot(name='download_and_track_{}_b{}'.format('chad5', start_knot),
docker_image = my_image,
memory = 144000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-0e00afdf500081a0d', #May need to change this line
pars_policies=('AmazonS3FullAccess',))
result_futures5 = knot5.map(all_maps, starmap=True)
ck.aws.set_region('eu-west-1')
knot5.clobber()
tparams2 = {'radius': 3.5, 'threshold': 0.0, 'do_median_filtering': False,
'quality': 10.0, 'xdims': (0, 511), 'ydims': (1, 511),
'median_intensity': 300.0, 'snr': 0.0, 'linking_max_distance': 15.0,
'gap_closing_max_distance': 22.0, 'max_frame_gap': 5,
'track_duration': 20.0}
missing = []
all_maps3 = []
import boto3
import botocore
s3 = boto3.resource('s3')
for name in names:
try:
s3.Object(bucket, '{}/Traj_{}.csv'.format(remote_folder, name)).load()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
missing.append(name)
all_maps3.append((name, remote_folder, bucket, 'regress.obj',
4, 4, (512, 512), tparams1))
else:
print('Something else has gone wrong')
names
import diff_classifier.aws as aws
old_folder = 'Gel_Studies/08_14_18_gel_validation/old_msds2'
for name in missing:
filename = 'Traj_{}.csv'.format(name)
aws.download_s3('{}/{}'.format(old_folder, filename), filename, bucket_name=bucket)
aws.upload_s3(filename, '{}/{}'.format(remote_folder, filename), bucket_name=bucket)
```
Users can monitor the progress of their job in the Batch interface. Once the code is complete, users should clobber their knot to make sure that all AWS resources are removed.
```
knot.clobber()
```
## Downstream analysis and visualization
The knotlet.assemble_msds function (which can also potentially be submitted to Cloudknot as well for large jobs) calculates the mean squared displacements and trajectory features from the raw trajectory csv files found from the Cloudknot submission. It accesses them from the S3 bucket to which they were saved.
```
for prefix in to_track:
kn.assemble_msds(prefix, remote_folder, bucket=bucket)
print('Successfully output msds for {}'.format(prefix))
for prefix in to_track[5:7]:
kn.assemble_msds(prefix, remote_folder, bucket='ccurtis.data')
print('Successfully output msds for {}'.format(prefix))
all_maps2 = []
for prefix in to_track:
all_maps2.append((prefix, remote_folder, bucket, 'regress100.obj',
4, 4, (512, 512), tparams))
knot = ck.Knot(name='download_and_track_{}_b{}'.format('chad', start_knot),
docker_image = my_image,
memory = 16000,
resource_type = "SPOT",
bid_percentage = 100,
#image_id = 'ami-0e00afdf500081a0d', #May need to change this line
pars_policies=('AmazonS3FullAccess',))
```
Diff_classifier includes some useful imaging tools as well, including checking trajectories, plotting heatmaps of trajectory features, distributions of diffusion coefficients, and MSD plots.
```
import diff_classifier.heatmaps as hm
import diff_classifier.aws as aws
prefix = to_track[1]
msds = 'msd_{}.csv'.format(prefix)
feat = 'features_{}.csv'.format(prefix)
aws.download_s3('{}/{}'.format(remote_folder, msds), msds, bucket_name=bucket)
aws.download_s3('{}/{}'.format(remote_folder, feat), feat, bucket_name=bucket)
hm.plot_trajectories(prefix, upload=False, figsize=(8, 8))
geomean, geoSEM = hm.plot_individual_msds(prefix, x_range=10, y_range=300, umppx=1, fps=1, upload=False)
hm.plot_heatmap(prefix, upload=False)
hm.plot_particles_in_frame(prefix, y_range=6000, upload=False)
missing = []
all_maps2 = []
import boto3
import botocore
s3 = boto3.resource('s3')
for name in pref:
try:
s3.Object(bucket, '{}/Traj_{}.csv'.format(remote_folder, name)).load()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
missing.append(name)
all_maps3.append((name, remote_folder, bucket, 'regress.obj',
4, 4, (512, 512), tparams1))
else:
print('Something else has gone wrong')
missing = ['PS_COOH_2mM_XY05_1_1', 'PS_NH2_2mM_XY04_2_1']
len(all_maps3)
pref
```
| github_jupyter |
# 深度学习框架
近年来深度学习在很多机器学习领域都有着非常出色的表现,在图像识别、语音识别、自然语言处理、机器人、网络广告投放、医学自动诊断和金融等领域有着广泛应用。面对繁多的应用场景,深度学习框架有助于建模者节省大量而繁琐的外围工作,更聚焦业务场景和模型设计本身。
## 深度学习框架优势
使用深度学习框架完成模型构建有如下两个优势:
1. **节省编写大量底层代码的精力**:屏蔽底层实现,用户只需关注模型的逻辑结构。同时,深度学习工具简化了计算,降低了深度学习入门门槛。
2. **省去了部署和适配环境的烦恼**:具备灵活的移植性,可将代码部署到CPU/GPU/移动端上,选择具有分布式性能的深度学习工具会使模型训练更高效。
## 深度学习框架设计思路
深度学习框架的本质是框架自动实现建模过程中相对通用的模块,建模者只实现模型个性化的部分,这样可以在“节省投入”和“产出强大”之间达到一个平衡。我们想象一下:假设你是一个深度学习框架的创造者,你期望让框架实现哪些功能呢?
相信对神经网络模型有所了解的读者都会得出如 **表1** 所示的设计思路。在构建模型的过程中,每一步所需要完成的任务均可以拆分成个性化和通用化两个部分。
* 个性化部分:往往是指定模型由哪些逻辑元素组合,由建模者完成。
* 通用部分:聚焦这些元素的算法实现,由深度学习框架完成。
<br></br>
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/a895591e0d3242a0bfa9af5b687c3ac616442685d25547b188208cbecd06ee8e" width="900" hegiht="" ></center>
<center><br>表1:深度学习框架设计示意图</br></center>
<br></br>
无论是计算机视觉任务还是自然语言处理任务,使用的深度学习模型结构都是类似的,只是在每个环节指定的实现算法不同。因此,多数情况下,算法实现只是相对有限的一些选择,如常见的Loss函数不超过十种、常用的网络配置也就十几种、常用优化算法不超过五种等等。这些特性使得基于框架建模更像一个编写“模型配置”的过程。
# 飞桨开源深度学习平台
百度出品的深度学习平台飞桨(PaddlePaddle)是主流深度学习框架中一款完全国产化的产品。2016 年飞桨正式开源,是国内首个全面开源开放、技术领先、功能完备的产业级深度学习平台。相比国内其他平台,飞桨是一个功能完整的深度学习平台,也是唯一成熟稳定、具备大规模推广条件的深度学习平台。
飞桨源于产业实践,始终致力于与产业深入融合,与合作伙伴一起帮助越来越多的行业完成AI赋能。目前飞桨已广泛应用于医疗、金融、工业、农业、服务业等领域,如 **图1** 所示。此外在新冠疫情期间,飞桨积极投入各类疫情防护模型的开发,开源了业界首个口罩人脸检测及分类模型,辅助各部门进行疫情防护,通过科技让工作变得更加高效。
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/ee9964e5e6fb41c7a09a891a18a09fae691d1a70929049819342b0728fb35232" width="700" hegiht="" ></center>
<center><br>图1:飞桨在各领域的应用</br></center>
<br></br>
## 飞桨开源深度学习平台全景
飞桨(PaddlePaddle)以百度多年的深度学习技术研究和业务应用为基础,是中国首个开源开放、技术领先、功能完备的产业级深度学习平台,包括飞桨开源平台和飞桨企业版。飞桨开源平台包含核心框架、基础模型库、端到端开发套件与工具组件,持续开源核心能力,为产业、学术、科研创新提供基础底座。飞桨企业版基于飞桨开源平台,针对企业级需求增强了相应特性,包含零门槛AI开发平台EasyDL和全功能AI开发平台BML。EasyDL主要面向中小企业,提供零门槛、预置丰富网络和模型、便捷高效的开发平台;BML是为大型企业提供的功能全面、可灵活定制和被深度集成的开发平台。
飞桨开源平台(以下简称“飞桨”)全景图如 **图2** 所示。
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/d4925ad66cca4fd58fedd4bbc41ea11bdb58bf95cbea4113a8a3447cb2e2bca2" width="900" ></center>
<center><br>图2:飞桨全景图</br></center>
<br></br>
概览图上半部分是从开发、训练到部署的全流程工具,下半部分是预训练模型、各领域的开发套件和模型库等模型资源。
### 框架和全流程工具
飞桨在提供用于模型研发的基础框架外,还推出了一系列的工具组件,来支持深度学习模型从训练到部署的全流程。
#### 1. 模型训练组件
飞桨提供了**分布式训练框架FleetAPI**,还提供了开启**云上任务提交工具PaddleCloud**。同时,飞桨也支持多任务训练,可使用**多任务学习框架PALM**。
#### 2. 模型部署组件
飞桨针对不同硬件环境,提供了丰富的支持方案:
* **Paddle Inference**:飞桨原生推理库,用于服务器端模型部署,支持Python、C、C++、Go等语言,将模型融入业务系统的首选。
* **Paddle Serving**:飞桨服务化部署框架,用于云端服务化部署,可将模型作为单独的Web服务。
* **Paddle Lite**:飞桨轻量化推理引擎,用于Mobile、IoT等场景的部署,有着广泛的硬件支持。
* **Paddle.js**:使用JavaScript(Web)语言部署模型,用于在浏览器、小程序等环境快速部署模型。
* **PaddleSlim**:模型压缩工具,获得更小体积的模型和更快的执行性能。
* **X2Paddle**:飞桨模型转换工具,将其他框架模型转换成Paddle模型,转换格式后可以方便的使用上述5个工具。
#### 3. 其他全研发流程的辅助工具
* **AutoDL**:飞桨自动化深度学习工具,旨在自动网络结构设计,开源的AutoDL设计的图像分类网络在CIFAR10数据集正确率 达到 98%,效果优于目前已公开的10类人类专家设计的网络,居于业内领先位置。
* **VisualDL**:飞桨可视化分析工具,以丰富的图表呈现训练参数变化趋势、模型结构、数据样本、高维数据分布、精度召回曲线等模型关键信息。帮助用户清晰直观地理解深度学习模型训练过程及模型结构,进而实现高效的模型调优、并将算法训练过程及结果分享。
* **PaddleFL**:飞桨联邦学习框架,研究人员可以很轻松地用PaddleFL复制和比较不同的联邦学习算法,便捷地实现大规模分布式集群部署,并且提供丰富的横向和纵向联邦学习策略及其在计算机视觉、自然语言处理、推荐算法等领域的应用。此外,依靠着PaddlePaddle的大规模分布式训练和Kubernetes对训练任务的弹性调度能力,PaddleFL可以基于全栈开源软件轻松部署。
* **PaddleX**:飞桨全流程开发工具,以低代码的形式支持开发者快速实现深度学习算法开发及产业部署。提供极简Python API和可视化界面Demo两种开发模式,可一键安装。针对CPU(OpenVINO)、GPU、树莓派等通用硬件提供完善的部署方案,并可通过RESTful API快速完成集成、再开发,开发者无需分别使用不同套件即可完成全流程模型生产部署。可视化推理界面及丰富的产业案例更为开发者提供飞桨全流程开发的最佳实践。
### 模型资源
飞桨提供了丰富的端到端开发套件、预训练模型和模型库。
**PaddleHub**:飞桨预训练模型应用工具,覆盖文本、图像、视频、语音四大领域超过200个高质量预训练模型。开发者可以轻松结合实际业务场景,选用高质量预训练模型并配合Fine-tune API快速完成模型验证与应用部署工作。适用于个人开发者学习、企业POC快速验证、参加AI竞赛以及教学科研等多种业务场景。
**开发套件**:针对具体的应用场景提供了全套的研发工具,例如在图像检测场景不仅提供了预训练模型,还提供了数据增强等工具。开发套件也覆盖计算机视觉、自然语言处理、语音、推荐这些主流领域,甚至还包括图神经网络和增强学习。与PaddleHub不同,开发套件可以提供一个领域极致优化(State Of The Art)的实现方案,曾有国内团队使用飞桨的开发套件拿下了国际建模竞赛的大奖。一些典型的开发套件包括:
* **PaddleClas**:飞桨图像分类套件,目的是为工业界和学术界提供便捷易用的图像分类任务预训练模型和工具集,打通模型开发、训练、压缩、部署全流程,辅助其它高层视觉任务组网并提升模型效果,助力开发者训练更好的图像分类模型和应用落地。
* **PaddleDetection**:飞桨目标检测套件,旨在帮助开发者更快更好地完成检测模型的训练、精度速度优化到部署全流程。PaddleDetection以模块化的设计实现了多种主流目标检测算法,并且提供了丰富的数据增强、网络组件、损失函数等模块,集成了模型压缩和跨平台高性能部署能力。目前基于PaddleDetection已经完成落地的项目涉及工业质检、遥感图像检测、无人巡检等多个领域。
* **PaddleSeg**:飞桨图像分割套件,覆盖了DeepLabv3+/OCRNet/BiseNetv2/Fast-SCNN等高精度和轻量级等不同方向的大量高质量分割模型。通过模块化的设计,提供了配置化驱动和API调用等两种应用方式,帮助开发者更便捷地完成从训练到部署的全流程图像分割应用。
* **PaddleOCR:** 飞桨文字识别套件,旨在打造一套丰富、领先、且实用的OCR工具库,开源了基于PPOCR实用的超轻量中英文OCR模型、通用中英文OCR模型,以及德法日韩等多语言OCR模型。并提供上述模型训练方法和多种预测部署方式。同时开源文本风格数据合成工具Style-Text和半自动文本图像标注工具PPOCRLable。
* **PaddleGAN**:飞桨生成对抗网络开发套件,集成风格迁移、超分辨率、动漫画生成、图片上色、人脸属性编辑、妆容迁移等SOTA算法,以及预训练模型。并且模块化设计,以便开发者进行二次研发,或是直接使用预训练模型做应用。
* **PLSC**:飞桨海量类别分类套件,为用户提供了大规模分类任务从训练到部署的全流程解决方案。提供简洁易用的高层API,通过数行代码即可实现千万类别分类神经网络的训练,并提供快速部署模型的能力。
* **ERNIE**:基于持续学习的知识增强语义理解框架实现,内置业界领先的系列ERNIE预训练模型,能够 支持各类NLP算法任务Fine-tuning, 包含保证极速推理的Fast-inference API, 灵活部署的ERNIE Service和轻量化解决方案ERNIE Slim,训练过程所见即所得,支持动态debug,同时方便二次开发。
* **ElasticCTR**:飞桨弹性计算推荐套件,可以实现分布式训练CTR预估任务和基于Paddle Serving的在线个性化推荐服务。Paddle Serving服务化部署框架具有良好的易用性、灵活性和高性能,可以提供端到端的CTR训练和部署解决方案。ElasticCTR具备产业实践基础、弹性调度能力、高性能和工业级部署等特点。
* **Parakeet**:飞桨语音合成套件,提供了灵活、高效、先进的文本到语音合成工具,帮助开发者更便捷高效地完成语音合成模型的开发和应用。
* **PGL**:飞桨图学习框架,业界首个提出通用消息并行传递机制, 支持百亿规模巨图的工业级图学习框架。PGL基于飞桨动态图全新升级,极大提升了易用性,原生支持异构 图,支持分布式图存储及分布式学习算法,覆盖30+图学习模型,包括图语义理解模型ERNIESage等。历经 大量真实工业应用验证,能够灵活、高效地搭建前沿的大规模图学习算法。
* **PARL**:飞桨深度强化学习框架,在2018, 2019, 2020夺得强化学习挑战赛三连冠。具有高灵活性、可扩展性和高性能的特点。实现了十余种主流强化学习算法的示例,覆盖了从单智能体到多智能体,离散决策到连续控制不同领域的强化学习算法支持。基于GRPC机制实现数千台CPU和GPU的高性能并行。
* **Paddle Quantum**:量桨,飞桨量子机器学习框架,提供量子优化、量子化学等前沿应用工具集,常用量子电路模型,以及丰富的量子机器学习案例,帮助开发者便捷地搭建量子神经网络,开发量子人工智能应用。
* **PaddleHelix**:飞桨螺旋桨生物计算框架,开放了赋能疫苗设计,新药研发,精准医疗的AI能力。在疫苗设计上,PaddleHelix的LinearRNA系列算法相比传统方法在RNA折叠上提升了几百上千倍的效率; 在新药研发上,PaddleHelix提供了基于大规模数据预训练的分子表示,助力分子性质预测,药物筛选,药物设计等领域;在精准医疗上,PaddleHelix提供了利用组学信息精准定位药物,提升治愈率的高性能模型。
**模型库**:包含了各领域丰富的开源模型代码,不仅可以直接运行模型,还可以根据应用场景的需要修改原始模型代码,得到全新的模型实现。
> 比较三种类型的模型资源,PaddleHub的使用最为简易,模型库的可定制性最强且覆盖领域最广泛。读者可以参考“PaddleHub->各领域的开发套件->模型库”的顺序寻找需要的模型资源,在此基础上根据业务需求进行优化,即可达到事半功倍的效果。
## 飞桨技术优势
与其他深度学习框架相比,飞桨具有如下四大领先优势,如 **图3** 所示。
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/b50da6f7409a4d1fa7799541f215fa2c5a6439455500472b8184797785907bfc" width="900" hegiht="" ></center>
<center><br>图3:飞桨领先的四大技术优势</br></center>
<br></br>
* **开发便捷的深度学习框架**:飞桨兼顾便于性能优化的静态图和易于调试的动态图两种组网编程范式,默认采用命令式编程范式,并实现动静统一,开发者使用飞桨可以实现动态图编程调试,一行代码转静态图训练部署。同时还提供低代码开发的高层API,并且高层API和基础API采用一体化设计,两者可以互相配合使用,做到高低融合,确保用户可以同时享受开发的便捷性和灵活性。
* **超大规模的深度学习模型训练技术**:支持千亿特征、万亿参数的高速并行训练;支持业内首个通用参数服务器架构。
* **多端多平台部署的高性能推理引擎**:即训即用,支持端边云多硬件和多操作系统。
* **产业级开源模型库**:算法总数200+个,包含领先的预训练模型、国际竞赛冠军模型等,助力产业应用。
<br></br>
以其中两项为例,展开说明。
### 多领域产业级模型达到业界领先水平
大量工业实践任务的模型并不需要从头编写,而是在相对标准化的模型基础上进行参数调整和优化。飞桨支持的多领域产业级模型开源开放,且多数模型的效果达到业界领先水平,在国际竞赛中夺得20多项第一,如 **图4** 所示。
<br></br>
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/730ed282e5ae4f179bb55cd591b9d8e5a5eba79b2fa246bb962f590158fa11b8" width="1000" hegiht="" ></center>
<center><br>图4:飞桨各领域模型在国际竞赛中荣获多个第一</br></center>
<br></br>
### 支持多端多平台的部署,适配多种类型硬件芯片
随着深度学习技术在行业的广泛应用,对不同类型硬件设备、不同部署模型、不同操作系统、不同深度学习框架的适配需求涌现,飞桨的适配情况如 **图5** 所示。
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/4ccc037b91a6439f883174af201e908a247c4cc7c91d41b58f60787475bd4c84" width="900" hegiht="" ></center>
<center><br>图5:飞桨对周边产品的适配情况</br></center>
<br></br>
训练好的模型需要无缝集成到各种类型的硬件芯片中,如机房服务器、摄像头芯片等。在中美贸易战时日趋紧张的情况下,训练框架对国产芯片的支持显得尤其重要。飞桨走在了业界前列,截止2020年12月,飞桨已经适配了(或正在适配)的芯片/IP数量达到30种,其中国产的数量达到17种;覆盖了20家厂商,其中国产厂商12家。
<br></br>
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/6f44c12d5f6f4cf38ec24ac36ee3ac96b979b449c6e34305af550fd5ca6b7402" width="700" hegiht="" ></center>
<center><br>图6:飞桨软硬一体深度优化,硬件生态“芯芯向荣”</br></center>
<br></br>
## 飞桨在各行业的应用案例
飞桨在各行业的广泛应用,不但让人们的日常生活变得更加简单和便捷,对企业而言,飞桨还助力产品研发过程更加科学,极大提升了产品性能,节约了大量的人工耗时成本。
### 飞桨联手百度地图,出行时间智能预估准确率从81%提升到86%
在百度,搜索、信息流、输入法、地图等移动互联网产品中大量使用飞桨做深度学习任务。在百度地图,应用飞桨后提升了产品的部署和预测性能,支撑天级别的百亿次调用。完成了天级别的百亿级数据训练,用户出行时间预估的准确率从81%提升到86%,如 **图7** 所示。
<br></br>
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/bccc82ab83084b02b4ed954abad249c41b5710e9c90e451f900e93380ec88576" width="900" hegiht="" ></center>
<center><br>图7:百度地图出行时间智能预估应用</br></center>
<br></br>
### 飞桨联手南方电网,电力巡检迈向“无人时代”
飞桨与南方电网合作,采用机器人代替人工进行变电站仪表的巡检任务,如 **图8** 所示。由于南方电网的变电站数量众多,日常巡检常态化,而人工巡检工作内容单调,人力投入大,巡检效率低。集成了基于飞桨研发的视觉识别能力的机器人,识别表数值的准确率高达99.01%。在本次合作中,飞桨提供了端到端的开发套件支撑需求的快速实现,降低了企业对人工智能领域人才的依赖。
<br></br>
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/2e6dfe68675944afb625452fcafad63533783f29d8774579b692b1d39953381e" width="600" hegiht="" ></center>
<center><br>图8:南方电网电力智能巡检应用</br></center>
<br></br>
------
说明:
以上数据为内部测试结果,实际结果可能受环境影响而在一定范围内变化,仅供参考。如果您想了解更多、更新的飞桨工业实践案例、开发者案例或产研合作案例,可以登录[飞桨官网](https://www.paddlepaddle.org.cn/customercase)。
------
## 飞桨快速安装
进入实践之前,请先安装飞桨。飞桨提供了图形化的安装指导,操作简单,详细步骤请参考 [飞桨官网 -> 快速安装](http://www.paddlepaddle.org.cn/install/quick)。
进入页面后,可按照提示进行安装,如 **图9** 所示。举例来说,笔者选择在笔记本电脑上安装飞桨,那么选择(windows系统+pip+Python3+CPU版本)的配置组合。其中windows系统和CPU版本是个人笔记本的软硬件配置;Python3是需要事先安装好的Python版本(Python有2和3两个主流版本,两者的API接口不兼容);pip是命令行安装的指令。
<br></br>
<center><img src="https://ai-studio-static-online.cdn.bcebos.com/447ab6663a00432e84e2330f28fc171a4a5d5d943b7e4c5296e64ed66abfa929" width="700" hegiht="" ></center>
<center><br>图9:飞桨的安装页面示意图</br></center>
<br></br>
## 联系我们
- 飞桨官方网站: [https://www.paddlepaddle.org.cn/](https://www.paddlepaddle.org.cn/)
- 飞桨GitHub: [https://github.com/paddlepaddle](https://github.com/paddlepaddle)
- 飞桨微信公众号: 飞桨PaddlePaddle
- 飞桨官方QQ群: 1108045677
### 作业1-5
1. 在[AI Studio](http://aistudio.baidu.com/)上注册用户,查阅本课程的案例库,找到房价预测的案例。
1. 在飞桨官网上查看安装手册,在本机或服务器上安装PaddlePaddle库,并在GitHub上将[本课程的案例库](http://github.com/PaddlePaddle/tutorials)下载到本地PC或服务器。
1. 加入飞桨官方QQ群(1108045677),将安装和运行案例时的问题反馈到群中,获得答案。
------
**运行环境要求:**
本地已经安装Python、PaddlePaddle、Jupyter。
------
| github_jupyter |
# 14. Calibration over (lossy) splices and connectors
## Background
While it is best practice to not have connectors or splices within a DTS calibration, sometimes it can't be avoided. For example, in a borehole the fibers in a duplex cable are often connected with either a splice or a loopback connector.
Splices and connectors will cause a step loss in the signal strength, and with varying strain and temperature, this step loss will vary. In double ended setups this step loss can even be asymmetrical for the forward and backward measurements. All these effects have to be taken into account in the calibration.
To calibrate over these splices/connectors, locations with 'transient attenuation' can be defined along the length of the fiber. Adding these does mean that more information is needed to perform the calibration, such as extra reference sections or matching sections of fiber. Matching sections will be explained in notebook 15.
### Demonstration
To demonstrate the effect of a lossy splice, we'll load the same dataset that was used in previous notebooks, and modify the data to simulate a lossy splice.
```
import os
from dtscalibration import read_silixa_files
import matplotlib.pyplot as plt
%matplotlib inline
filepath = os.path.join('..', '..', 'tests', 'data', 'double_ended2')
ds_ = read_silixa_files(
directory=filepath,
timezone_netcdf='UTC',
file_ext='*.xml')
ds = ds_.sel(x=slice(0, 110)) # only calibrate parts of the fiber
sections = {
'probe1Temperature': [slice(7.5, 17.), slice(70., 80.)], # cold bath
'probe2Temperature': [slice(24., 34.), slice(85., 95.)], # warm bath
}
ds.sections = sections
```
To simulate the lossy splice, we introduce a step loss in the signal strength at x = 50 m. For the forward channel, this means all data beyond 50 meters is reduced with a 'random' factor. For the backward channel, this means all data up to 50 meters is reduced with a 'random' factor.
In the plots of the Stokes and anti-Stokes signal the big step loss is clearly visible.
```
ds['st'] = ds.st.where(ds.x < 50, ds.st*.8)
ds['ast'] = ds.ast.where(ds.x < 50, ds.ast*.82)
ds['rst'] = ds.rst.where(ds.x > 50, ds.rst*.85)
ds['rast'] = ds.rast.where(ds.x > 50, ds.rast*.81)
ds.isel(time=0).st.plot(label='st')
ds.isel(time=0).ast.plot(label='ast')
ds.isel(time=0).rst.plot(label='rst')
ds.isel(time=0).rast.plot(label='rast')
plt.legend()
```
We will first run a calibration without adding the transient attenuation location. A big jump in the calibrated temperature is visible at x = 50, and all temperatures before the jump are too low, and the temperatures after the jump are too high.
```
ds_a = ds.copy(deep=True)
st_var, resid = ds_a.variance_stokes(st_label='st')
ast_var, _ = ds_a.variance_stokes(st_label='ast')
rst_var, _ = ds_a.variance_stokes(st_label='rst')
rast_var, _ = ds_a.variance_stokes(st_label='rast')
ds_a.calibration_double_ended(
st_var=st_var,
ast_var=ast_var,
rst_var=rst_var,
rast_var=rast_var,
store_tmpw='tmpw',
method='wls',
solver='sparse')
ds_a.isel(time=0).tmpw.plot(label='calibrated')
```
Now we run a calibration, adding the keyword argument '**transient_asym_att_x**', and provide a list of floats containing the locations of the splices. In this case we only add a single one at x = 50 m. After running the calibration you will see that by adding the transient attenuation location the calibration returns the correct temperature, without the big jump.
*In single-ended calibration the keyword is called '**transient_att_x**'.*
```
st_var, resid = ds.variance_stokes(st_label='st')
ast_var, _ = ds.variance_stokes(st_label='ast')
rst_var, _ = ds.variance_stokes(st_label='rst')
rast_var, _ = ds.variance_stokes(st_label='rast')
ds.calibration_double_ended(
st_var=st_var,
ast_var=ast_var,
rst_var=rst_var,
rast_var=rast_var,
transient_asym_att_x=[50.],
store_tmpw='tmpw',
method='wls',
solver='sparse')
ds_a.isel(time=0).tmpw.plot(label='no trans. att.')
ds.isel(time=0).tmpw.plot(label='with trans. att.')
plt.legend()
```
| github_jupyter |
```
#hide
#default_exp export2html
#default_cls_lvl 3
from nbdev.showdoc import show_doc
#export
from nbdev.imports import *
from nbdev.sync import *
from nbdev.export import *
from nbdev.export import _mk_flag_re
from nbdev.showdoc import *
from nbdev.template import *
from fastcore.foundation import *
from fastcore.script import *
from html.parser import HTMLParser
from nbconvert.preprocessors import ExecutePreprocessor, Preprocessor
from nbconvert import HTMLExporter,MarkdownExporter
import traitlets
import nbformat
```
# Convert to html
> The functions that transform the dev notebooks in the documentation of the library
- toc: true
The most important function defined in this module is `notebook2html`, so you may want to jump to it before scrolling though the rest, which explain the details behind the scenes of the conversion from notebooks to the html documentation. The main things to remember are:
- put `#hide` at the top of any cell you want to completely hide in the docs
- use the hide input [jupyter extension](https://github.com/ipython-contrib/jupyter_contrib_nbextensions) to hide the input of some cells (by default all `show_doc` cells have that marker added)
- you can define some jekyll metadata in the markdown cell with the title, see `get_metadata`
- use backticks for terms you want automatic links to be found, but use `<code>` and `</code>` when you have homonyms and don't want those links
- you can define the default toc level of classes with `#default_cls_lvl` followed by a number (default is 2)
- you can add jekyll warnings, important or note banners with appropriate block quotes (see `add_jekyll_notes`)
- put any images you want to use in the images folder of your notebook folder, they will be automatically copied over to the docs folder
- put `#hide_input` at the top of a cell if you don't want code to be shown in the docs
- cells containing `#export` or `show_doc` have their code hidden automatically
- put `#hide_output` at the top of a cell if you don't want output to be shown in the docs
- use `#collapse_input` or `#collapse_output` to include code or output in the docs under a collapsable element
## Preprocessing notebook
### Cell processors
```
#export
class HTMLParseAttrs(HTMLParser):
"Simple HTML parser which stores any attributes in `attrs` dict"
def handle_starttag(self, tag, attrs): self.tag,self.attrs = tag,dict(attrs)
def attrs2str(self):
"Attrs as string"
return ' '.join([f'{k}="{v}"' for k,v in self.attrs.items()])
def show(self):
"Tag with updated attrs"
return f'<{self.tag} {self.attrs2str()} />'
def __call__(self, s):
"Parse `s` and store attrs"
self.feed(s)
return self.attrs
h = HTMLParseAttrs()
t = h('<img src="src" alt="alt" width="700" caption="cap" />')
test_eq(t['width'], '700')
test_eq(t['src' ], 'src')
t['width'] = '600'
test_eq(h.show(), '<img src="src" alt="alt" width="600" caption="cap" />')
```
The following functions are applied on individual cells as a preprocessing step before the conversion to html.
```
#export
def remove_widget_state(cell):
"Remove widgets in the output of `cells`"
if cell['cell_type'] == 'code' and 'outputs' in cell:
cell['outputs'] = [l for l in cell['outputs']
if not ('data' in l and 'application/vnd.jupyter.widget-view+json' in l.data)]
return cell
```
Those outputs usually can't be rendered properly in html.
```
#export
# Note: `_re_show_doc` will catch show_doc even if it's commented out etc
_re_show_doc = re.compile(r"""
# Catches any show_doc and get the first argument in group 1
^\s*show_doc # line can start with any amount of whitespace followed by show_doc
\s*\(\s* # Any number of whitespace, opening (, any number of whitespace
([^,\)\s]*) # Catching group for any character but a comma, a closing ) or a whitespace
[,\)\s] # A comma, a closing ) or a whitespace
""", re.MULTILINE | re.VERBOSE)
_re_hide_input = [
_mk_flag_re('export', (0,1), "Cell that has `#export"),
_mk_flag_re('(hide_input|hide-input)', 0, "Cell that has `#hide_input` or `#hide-input`")]
_re_hide_output = _mk_flag_re('(hide_output|hide-output)', 0, "Cell that has `#hide_output` or `#hide-output`")
#export
def upd_metadata(cell, key, value=True):
"Sets `key` to `value` on the `metadata` of `cell` without replacing metadata"
cell.setdefault('metadata',{})[key] = value
#export
def hide_cells(cell):
"Hide inputs of `cell` that need to be hidden"
if check_re_multi(cell, [_re_show_doc, *_re_hide_input]): upd_metadata(cell, 'hide_input')
elif check_re(cell, _re_hide_output): upd_metadata(cell, 'hide_output')
return cell
```
This concerns all the cells with `#export` or `#hide_input` flags and all the cells containing a `show_doc` for a function or class.
```
for source in ['show_doc(read_nb)', '# export\nfrom local.core import *', '# hide_input\n2+2',
'line1\n show_doc (read_nb) \nline3', '# export with.mod\nfrom local.core import *']:
cell = {'cell_type': 'code', 'source': source}
cell1 = hide_cells(cell.copy())
assert 'metadata' in cell1
assert 'hide_input' in cell1['metadata']
assert cell1['metadata']['hide_input']
flag = '# exports'
cell = {'cell_type': 'code', 'source': f'{flag}\nfrom local.core2 import *'}
test_eq(hide_cells(cell.copy()), cell)
```
This concerns all the cells with `#hide_output`.
```
for source in ['# hide-output\nfrom local.core import *', '# hide_output\n2+2']:
cell = {'cell_type': 'code', 'source': source}
cell1 = hide_cells(cell.copy())
assert 'metadata' in cell1
assert 'hide_output' in cell1['metadata']
assert cell1['metadata']['hide_output']
cell = {'cell_type': 'code', 'source': '# hide-outputs\nfrom local.core import *'}
test_eq(hide_cells(cell.copy()), cell)
#export
def clean_exports(cell):
"Remove all flags from code `cell`s"
if cell['cell_type'] == 'code': cell['source'] = split_flags_and_code(cell, str)[1]
return cell
```
The rest of the cell is displayed without any modification.
```
flag = '# exports'
cell = {'cell_type': 'code', 'source': f'{flag}\nfrom local.core import *'}
test_eq(clean_exports(cell.copy()), {'cell_type': 'code', 'source': 'from local.core import *'})
cell['cell_type'] = 'markdown'
test_eq(clean_exports(cell.copy()), cell)
cell = {'cell_type': 'code', 'source': f'{flag} core\nfrom local.core import *'}
test_eq(clean_exports(cell.copy()), {'cell_type': 'code', 'source': 'from local.core import *'})
cell = {'cell_type': 'code', 'source': f'# comment \n# exports\nprint("something")'}
test_eq(clean_exports(cell.copy()), {'cell_type': 'code', 'source': '# exports\nprint("something")'})
#export
def treat_backticks(cell):
"Add links to backticks words in `cell`"
if cell['cell_type'] == 'markdown': cell['source'] = add_doc_links(cell['source'])
return cell
cell = {'cell_type': 'markdown', 'source': 'This is a `DocsTestClass`'}
# test_eq(treat_backticks(cell), {'cell_type': 'markdown',
# 'source': 'This is a [`DocsTestClass`](/export.html#DocsTestClass)'})
#export
_re_nb_link = re.compile(r"""
# Catches any link to a local notebook and keeps the title in group 1, the link without .ipynb in group 2
\[ # Opening [
([^\]]*) # Catching group for any character except ]
\]\( # Closing ], opening (
([^http] # Catching group that must not begin by html (local notebook)
[^\)]*) # and containing anything but )
.ipynb\) # .ipynb and closing )
""", re.VERBOSE)
#export
_re_block_notes = re.compile(r"""
# Catches any pattern > Title: content with title in group 1 and content in group 2
^\s*>\s* # > followed by any number of whitespace
([^:]*) # Catching group for any character but :
:\s* # : then any number of whitespace
([^\n]*) # Catching group for anything but a new line character
(?:\n|$) # Non-catching group for either a new line or the end of the text
""", re.VERBOSE | re.MULTILINE)
#export
def _to_html(text):
return text.replace("'", "’")
#export
def add_jekyll_notes(cell):
"Convert block quotes to jekyll notes in `cell`"
styles = get_config().get('jekyll_styles', 'note,warning,tip,important').split(',')
def _inner(m):
title,text = m.groups()
if title.lower() not in styles: return f"> {title}:{text}"
return '{% include '+title.lower()+".html content=\'"+_to_html(text)+"\' %}"
if cell['cell_type'] == 'markdown':
cell['source'] = _re_block_notes.sub(_inner, cell['source'])
return cell
```
Supported styles are `Warning`, `Note` `Tip` and `Important`:
Typing `> Warning: There will be no second warning!` will render in the docs:
> Warning: There will be no second warning!
Typing `> Important: Pay attention! It's important.` will render in the docs:
> Important: Pay attention! It's important.
Typing `> Tip: This is my tip.` will render in the docs:
> Tip: This is my tip.
Typing `> Note: Take note of this.` will render in the docs:
> Note: Take note of this.
Typing ``> Note: A doc link to `add_jekyll_notes` should also work fine.`` will render in the docs:
> Note: A doc link to `add_jekyll_notes` should also work fine.
```
#hide
for w in ['Warning', 'Note', 'Important', 'Tip', 'Bla']:
cell = {'cell_type': 'markdown', 'source': f"> {w}: This is my final {w.lower()}!"}
res = '{% include '+w.lower()+'.html content=\'This is my final '+w.lower()+'!\' %}'
if w != 'Bla': test_eq(add_jekyll_notes(cell), {'cell_type': 'markdown', 'source': res})
else: test_eq(add_jekyll_notes(cell), cell)
#hide
cell = {'cell_type': 'markdown', 'source': f"> This is a link, don't break me! https://my.link.com"}
test_eq(add_jekyll_notes(cell.copy()), cell)
#export
_re_image = re.compile(r"""
# Catches any image file used, either with `` or `<img src="image_file">`
^(!\[ # Beginning of line (since re.MULTILINE is passed) followed by ![ in a catching group
[^\]]* # Anything but ]
\]\() # Closing ] and opening (, end of the first catching group
[ \t]* # Whitespace before the image path
([^\) \t]*) # Catching block with any character that is not ) or whitespace
(\)| |\t) # Catching group with closing ) or whitespace
| # OR
^(<img\ [^>]*>) # Catching group with <img some_html_code>
""", re.MULTILINE | re.VERBOSE)
m=_re_image.search('')
test_eq(m.groups(), ('', None))
# using ) or whitespace to close the group means we don't need a special case for captions
m=_re_image.search('")')
test_eq(m.groups(), (')
#export
def _img2jkl(d, h, jekyll=True):
if d.get("src","").startswith("http"): jekyll=False
if jekyll:
if 'width' in d: d['max-width'] = d.get('width')
else:
if 'width' in d: d['style'] = f'max-width: {d.get("width")}px'
d.pop('align','')
return '<img ' + h.attrs2str() + '>'
if 'src' in d: d['file'] = d.pop('src')
return '{% include image.html ' + h.attrs2str() + ' %}'
#export
def _is_real_image(src):
return not (src.startswith('http://') or src.startswith('https://') or src.startswith('data:image/') or src.startswith('attachment:'))
#export
def copy_images(cell, fname, dest, jekyll=True):
"Copy images referenced in `cell` from `fname` parent folder to `dest` folder"
def _rep_src(m):
grps = m.groups()
if grps[3] is not None:
h = HTMLParseAttrs()
dic = h(grps[3])
src = dic['src']
else: src = grps[1]
if _is_real_image(src):
os.makedirs((Path(dest)/src).parent, exist_ok=True)
shutil.copy(Path(fname).parent/src, Path(dest)/src)
src = get_config().doc_baseurl + src
if grps[3] is not None:
dic['src'] = src
return _img2jkl(dic, h, jekyll=jekyll)
else: return f"{grps[0]}{src}{grps[2]}"
if cell['cell_type'] == 'markdown': cell['source'] = _re_image.sub(_rep_src, cell['source'])
return cell
```
This is to ensure that all images defined in `nbs_folder/images` and used in notebooks are copied over to `doc_folder/images`.
```
dest_img = get_config().path("doc_path")/'images'/'logo.png'
cell = {'cell_type': 'markdown', 'source':'Text\n'}
try:
copy_images(cell, Path('01_export.ipynb'), get_config().path("doc_path"))
test_eq(cell["source"], 'Text\n')
#Image has been copied
assert dest_img.exists()
cell = {'cell_type': 'markdown', 'source':'Text\n")'}
copy_images(cell, Path('01_export.ipynb'), get_config().path("doc_path"))
test_eq(cell["source"], 'Text\n")')
finally: dest_img.unlink()
#hide
cell = {'cell_type': 'markdown', 'source':'Text\n'}
copy_images(cell, Path('01_export.ipynb'), get_config().path("doc_path"))
test_eq(cell["source"], 'Text\n')
cell = {'cell_type': 'markdown', 'source':'Text\n'}
copy_images(cell, Path('01_export.ipynb'), get_config().path("doc_path"))
test_eq(cell["source"], 'Text\n')
#export
def _relative_to(path1, path2):
p1,p2 = Path(path1).absolute().parts,Path(path2).absolute().parts
i=0
while i <len(p1) and i<len(p2) and p1[i] == p2[i]: i+=1
p1,p2 = p1[i:],p2[i:]
return os.path.sep.join(['..' for _ in p2] + list(p1))
#hide
test_eq(_relative_to(Path('images/logo.png'), get_config().path("doc_path")), str(Path('../nbs/images/logo.png')))
test_eq(_relative_to(Path('images/logo.png'), get_config().path("doc_path").parent), str(Path('nbs/images/logo.png')))
#export
def adapt_img_path(cell, fname, dest, jekyll=True):
"Adapt path of images referenced in `cell` from `fname` to work in folder `dest`"
def _rep(m):
gps = m.groups()
if gps[0] is not None:
start,img,end = gps[:3]
if not (img.startswith('http:/') or img.startswith('https:/')):
img = _relative_to(fname.parent/img, dest)
return f'{start}{img}{end}'
else:
h = HTMLParseAttrs()
dic = h(gps[3])
if not (dic['src'].startswith('http:/') or dic['src'].startswith('https:/')):
dic['src'] = _relative_to(fname.parent/dic['src'], dest)
return _img2jkl(dic, h, jekyll=jekyll)
if cell['cell_type'] == 'markdown': cell['source'] = _re_image.sub(_rep, cell['source'])
return cell
```
This function is slightly different as it ensures that a notebook convert to a file that will be placed in `dest` will have the images location updated. It is used for the `README.md` file (generated automatically from the index) since the images are copied inside the github repo, but in general, you should make sure your images are going to be accessible from the location your file ends up being.
```
cell = {'cell_type': 'markdown', 'source': str(Path('Text\n'))}
cell1 = adapt_img_path(cell, Path('01_export.ipynb'), Path('.').absolute().parent)
test_eq(cell1['source'], str(Path('Text\n')))
cell = {'cell_type': 'markdown', 'source': 'Text\n'}
cell1 = adapt_img_path(cell, Path('01_export.ipynb'), Path('.').absolute().parent)
test_eq(cell1['source'], 'Text\n')
```
Escape Latex in liquid
```
#export
_re_latex = re.compile(r'^(\$\$.*\$\$)$', re.MULTILINE)
#export
def escape_latex(cell):
if cell['cell_type'] != 'markdown': return cell
cell['source'] = _re_latex.sub(r'{% raw %}\n\1\n{% endraw %}', cell['source'])
return cell
cell = {'cell_type': 'markdown',
'source': 'lala\n$$equation$$\nlala'}
cell = escape_latex(cell)
test_eq(cell['source'], 'lala\n{% raw %}\n$$equation$$\n{% endraw %}\nlala')
```
### Collapsable Code Cells
```
#export
_re_cell_to_collapse_closed = _mk_flag_re('(collapse|collapse_hide|collapse-hide)', 0, "Cell with #collapse or #collapse_hide")
_re_cell_to_collapse_open = _mk_flag_re('(collapse_show|collapse-show)', 0, "Cell with #collapse_show")
_re_cell_to_collapse_output = _mk_flag_re('(collapse_output|collapse-output)', 0, "Cell with #collapse_output")
#export
def collapse_cells(cell):
"Add a collapse button to inputs or outputs of `cell` in either the open or closed position"
if check_re(cell, _re_cell_to_collapse_closed): upd_metadata(cell,'collapse_hide')
elif check_re(cell, _re_cell_to_collapse_open): upd_metadata(cell,'collapse_show')
elif check_re(cell, _re_cell_to_collapse_output): upd_metadata(cell,'collapse_output')
return cell
#hide
for flag in [
('collapse_hide', '#collapse'),
('collapse_hide', '# collapse_hide'),
('collapse_hide', ' # collapse-hide'),
('collapse_show', '#collapse_show'),
('collapse_show', '#collapse-show'),
('collapse_output', ' #collapse_output'),
('collapse_output', '#collapse-output')]:
cell = nbformat.v4.new_code_cell(f'#comment\n{flag[1]} \ndef some_code')
test_eq(True, collapse_cells(cell)['metadata'][flag[0]])
#hide
# check that we can't collapse both input and output
cell = nbformat.v4.new_code_cell(f'#hide-input\n#collapse_output \ndef some_code')
test_eq({'hide_input': True, 'collapse_output': True}, hide_cells(collapse_cells(cell))['metadata'])
```
- Placing `#collapse_input open` in a code cell will include your code under a collapsable element that is **open** by default.
```
#collapse_input open
print('This code cell is not collapsed by default but you can collapse it to hide it from view!')
print("Note that the output always shows with `%collapse_input`.")
```
- Placing `#collapse_input` in a code cell will include your code in a collapsable element that is **closed** by default. For example:
```
#collapse_input
print('The code cell that produced this output is collapsed by default but you can expand it!')
```
- Placing `#collapse_output` in a code cell will hide the output under a collapsable element that is **closed** by default.
```
#collapse_output
print('The input of this cell is visible as usual.\nHowever, the OUTPUT of this cell is collapsed by default but you can expand it!')
```
### Preprocessing the list of cells
The following functions are applied to the entire list of cells of the notebook as a preprocessing step before the conversion to html.
```
#export
_re_hide = _mk_flag_re('hide', 0, 'Cell with #hide')
_re_cell_to_remove = _mk_flag_re('(default_exp|exporti)', (0,1), 'Cell with #default_exp or #exporti')
_re_default_cls_lvl = _mk_flag_re('default_cls_lvl', 1, "Cell with #default_cls_lvl")
#export
def remove_hidden(cells):
"Remove in `cells` the ones with a flag `#hide`, `#default_exp`, `#default_cls_lvl` or `#exporti`"
_hidden = lambda c: check_re(c, _re_hide, code_only=False) or check_re(c, _re_cell_to_remove)
return L(cells).filter(_hidden, negate=True)
cells = [{'cell_type': 'code', 'source': source, 'hide': hide} for hide, source in [
(False, '# export\nfrom local.core import *'),
(False, '# exporti mod file'), # Note: this used to get removed but we're more strict now
(True, '# hide\nfrom local.core import *'),
(False, '# hide_input\nfrom local.core import *'),
(False, '#exports\nsuper code'),
(True, '#default_exp notebook.export'),
(False, 'show_doc(read_nb)'),
(False, '#hide (last test of to_concat)'),
(True, '# exporti\n1 + 1')]] + [
{'cell_type': 'markdown', 'source': source, 'hide': hide} for hide, source in [
(False, '#hide_input\nnice'),
(True, '#hide\n\nto hide')]]
for a,b in zip([cell for cell in cells if not cell['hide']], remove_hidden(cells)):
test_eq(a,b)
#export
def find_default_level(cells):
"Find in `cells` the default class level."
res = L(cells).map_first(check_re_multi, pats=_re_default_cls_lvl)
return int(res.groups()[0]) if res else 2
tst_nb = read_nb('00_export.ipynb')
test_eq(find_default_level(tst_nb['cells']), 3)
#export
_re_export = _mk_flag_re("exports?", (0,1), "Line with #export or #exports with or without module name")
#export
def nb_code_cell(source):
"A code cell (as a dict) containing `source`"
return {'cell_type': 'code', 'execution_count': None, 'metadata': {}, 'outputs': [], 'source': source}
#export
def _show_doc_cell(name, cls_lvl=None):
return nb_code_cell(f"show_doc({name}{'' if cls_lvl is None else f', default_cls_level={cls_lvl}'})")
def add_show_docs(cells, cls_lvl=None):
"Add `show_doc` for each exported function or class"
documented = L(cells).map(check_re, pat=_re_show_doc).filter().map(Self.group(1))
res = []
for cell in cells:
res.append(cell)
if check_re(cell, _re_export):
for n in export_names(cell['source'], func_only=True):
if not n in documented: res.insert(len(res)-1, _show_doc_cell(n, cls_lvl=cls_lvl))
return res
```
This only adds cells with a `show_doc` for non-documented functions, so if you add yourself a `show_doc` cell (because you want to change one of the default argument), there won't be any duplicates.
```
for i,cell in enumerate(tst_nb['cells']):
if cell['source'].startswith('#export\ndef read_nb'): break
tst_cells = [c.copy() for c in tst_nb['cells'][i-1:i+1]]
added_cells = add_show_docs(tst_cells, cls_lvl=3)
test_eq(len(added_cells), 3)
test_eq(added_cells[0], tst_nb['cells'][i-1])
test_eq(added_cells[2], tst_nb['cells'][i])
test_eq(added_cells[1], _show_doc_cell('read_nb', cls_lvl=3))
test_eq(added_cells[1]['source'], 'show_doc(read_nb, default_cls_level=3)')
for flag in ['#export', '#exports']:
for show_doc_source in [
('show_doc(my_func)', 'show_doc(my_func, title_level=3)')]:
#Check show_doc isn't added if it was already there.
tst_cells1 = [{'cell_type':'code', 'source': f'{flag}\ndef my_func(x):\n return x'},
{'cell_type':'code', 'source': show_doc_source[0]}]
test_eq(add_show_docs(tst_cells1), tst_cells1)
#Check show_doc is added
test_eq(len(add_show_docs(tst_cells1[:-1])), len(tst_cells1))
tst_cells1 = [{'cell_type':'code', 'source': f'{flag} with.mod\ndef my_func(x):\n return x'},
{'cell_type':'markdown', 'source': 'Some text'},
{'cell_type':'code', 'source': show_doc_source[1]}]
test_eq(add_show_docs(tst_cells1), tst_cells1)
#Check show_doc is added when using mod export
test_eq(len(add_show_docs(tst_cells1[:-1])), len(tst_cells1))
#export
_re_fake_header = re.compile(r"""
# Matches any fake header (one that ends with -)
\#+ # One or more #
\s+ # One or more of whitespace
.* # Any char
-\s* # A dash followed by any number of white space
$ # End of text
""", re.VERBOSE)
#export
def remove_fake_headers(cells):
"Remove in `cells` the fake header"
return [c for c in cells if c['cell_type']=='code' or _re_fake_header.search(c['source']) is None]
```
You can fake headers in your notebook to navigate them more easily with collapsible headers, just make them finish with a dash and they will be removed. One typical use case is to have a header of level 2 with the name of a class, since the `show_doc` cell of that class will create the same anchor, you need to have the one you created manually disappear to avoid any duplicate.
```
cells = [{'cell_type': 'markdown',
'metadata': {},
'source': '### Fake-'}] + tst_nb['cells'][:10]
cells1 = remove_fake_headers(cells)
test_eq(len(cells1), len(cells)-1)
test_eq(cells1[0], cells[1])
#export
def remove_empty(cells):
"Remove in `cells` the empty cells"
return [c for c in cells if len(c['source']) >0]
```
### Grabbing metadata
```
#export
_re_title_summary = re.compile(r"""
# Catches the title and summary of the notebook, presented as # Title > summary, with title in group 1 and summary in group 2
^\s* # Beginning of text followed by any number of whitespace
\#\s+ # # followed by one or more of whitespace
([^\n]*) # Catching group for any character except a new line
\n+ # One or more new lines
>[ ]* # > followed by any number of whitespace
([^\n]*) # Catching group for any character except a new line
""", re.VERBOSE)
_re_title_only = re.compile(r"""
# Catches the title presented as # Title without a summary
^\s* # Beginning of text followed by any number of whitespace
\#\s+ # # followed by one or more of whitespace
([^\n]*) # Catching group for any character except a new line
(?:\n|$) # New line or end of text
""", re.VERBOSE)
_re_properties = re.compile(r"""
^-\s+ # Beginning of a line followed by - and at least one space
(.*?) # Any pattern (shortest possible)
\s*:\s* # Any number of whitespace, :, any number of whitespace
(.*?)$ # Any pattern (shortest possible) then end of line
""", re.MULTILINE | re.VERBOSE)
_re_mdlinks = re.compile(r"\[(.+)]\((.+)\)", re.MULTILINE)
#export
def _md2html_links(s):
'Converts markdown links to html links'
return _re_mdlinks.sub(r"<a href='\2'>\1</a>", s)
#export
def get_metadata(cells):
"Find the cell with title and summary in `cells`."
for i,cell in enumerate(cells):
if cell['cell_type'] == 'markdown':
match = _re_title_summary.match(cell['source'])
if match:
cells.pop(i)
attrs = {k:v for k,v in _re_properties.findall(cell['source'])}
return {'keywords': 'fastai',
'summary' : _md2html_links(match.groups()[1]),
'title' : match.groups()[0],
**attrs}
elif _re_title_only.search(cell['source']) is not None:
title = _re_title_only.search(cell['source']).groups()[0]
cells.pop(i)
attrs = {k:v for k,v in _re_properties.findall(cell['source'])}
return {'keywords': 'fastai',
'title' : title,
**attrs}
return {'keywords': 'fastai',
'title' : 'Title'}
```
In the markdown cell with the title, you can add the summary as a block quote (just put an empty block quote for an empty summary) and a list with any additional metadata you would like to add, for instance:
```
# Title
> Awesome summary
- toc: False
```
The toc: False metadata will prevent the table of contents from showing on the page.
```
tst_nb = read_nb('00_export.ipynb')
test_eq(get_metadata(tst_nb['cells']), {
'keywords': 'fastai',
'summary': 'The functions that transform notebooks in a library',
'title': 'Export to modules'})
#The cell with the metada is popped out, so if we do it a second time we get the default.
test_eq(get_metadata(tst_nb['cells']), {'keywords': 'fastai', 'title' : 'Title'})
#hide
#test with title only
test_eq(get_metadata([{'cell_type': 'markdown', 'source': '# Awesome title'}]),
{'keywords': 'fastai', 'title': 'Awesome title'})
#hide
text = r"""
[This](https://nbdev.fast.ai) goes to docs.
This [one:here](00_export.ipynb) goes to a local nb.
\n[And-this](http://dev.fast.ai/) goes to fastai docs
"""
res = """
<a href='https://nbdev.fast.ai'>This</a> goes to docs.\nThis <a href='00_export.ipynb'>one:here</a> goes to a local nb. \n\\n<a href='http://dev.fast.ai/'>And-this</a> goes to fastai docs
"""
test_eq(_md2html_links(text), res)
#hide
cells = [{'cell_type': 'markdown', 'source': "# Title\n\n> s\n\n- toc: false"}]
test_eq(get_metadata(cells), {'keywords': 'fastai', 'summary': 's', 'title': 'Title', 'toc': 'false'})
```
## Executing show_doc cells
```
#export
_re_mod_export = _mk_flag_re("export[s]?", 1,
"Matches any line with #export or #exports with a module name and catches it in group 1")
def _gather_export_mods(cells):
res = []
for cell in cells:
tst = check_re(cell, _re_mod_export)
if tst is not None: res.append(tst.groups()[0])
return res
#hide
cells = [
{'cell_type': 'markdown', 'source': '#export ignored'},
{'cell_type': 'code', 'source': '#export'},
{'cell_type': 'code', 'source': '#export normal'},
{'cell_type': 'code', 'source': '# exports show'},
{'cell_type': 'code', 'source': '# exporti hidden'},
{'cell_type': 'code', 'source': '#export\n@call_parse'},
{'cell_type': 'code', 'source': '#export \n@delegates(concurrent.futures.ProcessPoolExecutor)'}
]
test_eq(_gather_export_mods(cells), ['normal', 'show'])
#export
# match any cell containing a zero indented import from the current lib
_re_lib_import = ReLibName(r"^from LIB_NAME\.", re.MULTILINE)
# match any cell containing a zero indented import
_re_import = re.compile(r"^from[ \t]+\S+[ \t]+import|^import[ \t]", re.MULTILINE)
# match any cell containing a zero indented call to notebook2script
_re_notebook2script = re.compile(r"^notebook2script\(", re.MULTILINE)
#hide
for cell in [nbformat.v4.new_code_cell(s, metadata={'exp': exp}) for exp,s in [
(True, 'show_doc(Tensor.p)'),
(True, ' show_doc(Tensor.p)'),
(True, 'if something:\n show_doc(Tensor.p)'),
(False, '# show_doc(Tensor.p)'),
(True, '# comment \n show_doc(Tensor.p)'),
(True, '"""\nshow_doc(Tensor.p)\n"""'),
(True, 'import torch\nshow_doc(Tensor.p)'),
(False,'class Ex(ExP):\n"An `ExP` that ..."\ndef preprocess_cell(self, cell, resources, index):\n'),
(False, 'from somewhere import something'),
(False, 'from '),
(False, 'import re'),
(False, 'import '),
(False, 'try: from PIL import Image\except: pass'),
(False, 'from PIL import Image\n@patch\ndef p(x:Image):\n pass'),
(False, '@patch\ndef p(x:Image):\n pass\nfrom PIL import Image')]]:
exp = cell.metadata.exp
assert exp == bool(check_re_multi(cell, [_re_show_doc, _re_lib_import.re])), f'expected {exp} for {cell}'
#hide
for cell in [nbformat.v4.new_code_cell(s, metadata={'exp': exp}) for exp,s in [
(False, 'show_doc(Tensor.p)'),
(True, 'import torch\nshow_doc(Tensor.p)'),
(False,'class Ex(ExP):\n"An `ExP` that ..."\ndef preprocess_cell(self, cell, resources, index):\n'),
(False, ' from somewhere import something'),
(True, 'from somewhere import something'),
(False, 'from '),
(False, 'select * \nfrom database'),
(False, ' import re'),
(True, 'import re'),
(True, 'import '),
(False, 'try: from PIL import Image\except: pass'),
(True, 'from PIL import Image\n@patch\ndef p(x:Image):\n pass'),
(True, '@patch\ndef p(x:Image):\n pass\nfrom PIL import Image')]]:
exp = cell.metadata.exp
assert exp == bool(check_re(cell, _re_import)), f'expected {exp} for {cell}'
#hide
for cell in [nbformat.v4.new_code_cell(s, metadata={'exp': exp}) for exp,s in [
(False, 'show_doc(Tensor.p)'),
(False, 'notebook2script'),
(False, '#notebook2script()'),
(True, 'notebook2script()'),
(True, 'notebook2script(anything at all)')]]:
exp = cell.metadata.exp
assert exp == bool(check_re(cell, _re_notebook2script)), f'expected {exp} for {cell}'
#export
def _non_comment_code(s):
if re.match(r'\s*#', s): return False
if _re_import.findall(s) or _re_lib_import.re.findall(s): return False
return re.match(r'\s*\w', s)
#export
class ExecuteShowDocPreprocessor(ExecutePreprocessor):
"An `ExecutePreprocessor` that only executes `show_doc` and `import` cells"
def preprocess_cell(self, cell, resources, index):
if not check_re(cell, _re_notebook2script):
if check_re(cell, _re_show_doc):
return super().preprocess_cell(cell, resources, index)
elif check_re_multi(cell, [_re_import, _re_lib_import.re]):
if check_re_multi(cell, [_re_export, 'show_doc', '^\s*#\s*import']):
# r = list(filter(_non_comment_code, cell['source'].split('\n')))
# if r: print("You have import statements mixed with other code", r)
return super().preprocess_cell(cell, resources, index)
# try: return super().preprocess_cell(cell, resources, index)
# except: pass
return cell, resources
```
Cells containing:
- a zero indented call to `notebook2script`
are not run while building docs. This avoids failures caused by importing empty or partially built modules.
Cells containing:
- `show_doc` (which could be indented) or
- a "library import" (zero indent import from current library) e.g. `from LIB_NAME.core import *`
are executed and must run without error. If running these cells raises an exception, the build will stop.
Cells containing zero indented imports. e.g.
- `from module import *` or
- `import module`
are executed but errors will not stop the build.
If you need to `show_doc` something, please make sure it's imported via a cell that does not depend on previous cells being run. The easiest way to do this is to use a cell that contains nothing but imports.
```
#export
def _import_show_doc_cell(mods=None):
"Add an import show_doc cell."
source = f"from nbdev.showdoc import show_doc"
if mods is not None:
for mod in mods: source += f"\nfrom {get_config().lib_name}.{mod} import *"
return {'cell_type': 'code',
'execution_count': None,
'metadata': {'hide_input': True},
'outputs': [],
'source': source}
def execute_nb(nb, mod=None, metadata=None, show_doc_only=True):
"Execute `nb` (or only the `show_doc` cells) with `metadata`"
mods = ([] if mod is None else [mod]) + _gather_export_mods(nb['cells'])
nb['cells'].insert(0, _import_show_doc_cell(mods))
ep_cls = ExecuteShowDocPreprocessor if show_doc_only else ExecutePreprocessor
ep = ep_cls(timeout=600, kernel_name='python3')
metadata = metadata or {}
pnb = nbformat.from_dict(nb)
ep.preprocess(pnb, metadata)
return pnb
```
## Converting bibtex citations
```
#export
_re_cite = re.compile(r"(\\cite{)([^}]*)(})", re.MULTILINE | re.VERBOSE) # Catches citations used with `\cite{}`
#export
def _textcite2link(text):
citations = _re_cite.finditer(text)
out = []
start_pos = 0
for cit_group in citations:
cit_pos_st = cit_group.span()[0]
cit_pos_fin = cit_group.span()[1]
out.append(text[start_pos:cit_pos_st])
out.append('[')
cit_group = cit_group[2].split(',')
for i, cit in enumerate(cit_group):
cit=cit.strip()
out.append(f"""<a class="latex_cit" id="call-{cit}" href="#cit-{cit}">{cit}</a>""")
if i != len(cit_group) - 1:
out.append(',')
out.append(']')
start_pos = cit_pos_fin
out.append(text[start_pos:])
return ''.join(out)
#export
def cite2link(cell):
'''Creates links from \cite{} to Reference section generated by jupyter_latex_envs'''
if cell['cell_type'] == 'markdown': cell['source'] = _textcite2link(cell['source'])
return cell
```
jupyter_latex_envs is a jupyter extension https://github.com/jfbercher/jupyter_latex_envs.
You can find relevant section [here](https://rawgit.com/jfbercher/jupyter_latex_envs/master/src/latex_envs/static/doc/latex_env_doc.html#Bibliography)
Note, that nbdev now only supports `\cite{}` conversion and not the rest, e.g., `\figure{}` and so on.
```
#hide
cell = {'cell_type': 'markdown', 'source': r"""This is cited multireference \cite{Frob1, Frob3}.
And single \cite{Frob2}."""}
expected=r"""This is cited multireference [<a class="latex_cit" id="call-Frob1" href="#cit-Frob1">Frob1</a>,<a class="latex_cit" id="call-Frob3" href="#cit-Frob3">Frob3</a>].
And single [<a class="latex_cit" id="call-Frob2" href="#cit-Frob2">Frob2</a>]."""
test_eq(cite2link(cell)["source"], expected)
```
It's important to execute all `show_doc` cells before exporting the notebook to html because some of them have just been added automatically or others could have outdated links.
```
#slow
fake_nb = {k:v for k,v in tst_nb.items() if k != 'cells'}
fake_nb['cells'] = [tst_nb['cells'][0].copy()] + added_cells
fake_nb = execute_nb(fake_nb, mod='export')
assert len(fake_nb['cells'][-2]['outputs']) > 0
```
## Filling templates
The following functions automatically adds jekyll templates if they are missing.
```
#export
def write_tmpl(tmpl, nms, cfg, dest):
"Write `tmpl` to `dest` (if missing) filling in `nms` in template using dict `cfg`"
if dest.exists(): return
vs = {o:cfg.d[o] for o in nms.split()}
outp = tmpl.format(**vs)
dest.mk_write(outp)
#export
def write_tmpls():
"Write out _config.yml and _data/topnav.yml using templates"
cfg = get_config()
path = Path(cfg.get('doc_src_path', cfg.path("doc_path")))
write_tmpl(config_tmpl, 'user lib_name title copyright description recursive', cfg, path/'_config.yml')
write_tmpl(topnav_tmpl, 'host git_url', cfg, path/'_data'/'topnav.yml')
write_tmpl(makefile_tmpl, 'nbs_path lib_name', cfg, cfg.config_file.parent/'Makefile')
#export
@call_parse
def nbdev_build_lib(fname:Param("A notebook name or glob to convert", str)=None,
bare:Param("Omit nbdev annotation comments (may break some functionality).", store_true)=False):
"Export notebooks matching `fname` to python modules"
write_tmpls()
notebook2script(fname=fname, bare=bare)
```
## Conversion
```
__file__ = str(get_config().path("lib_path")/'export2html.py')
#export
def nbdev_exporter(cls=HTMLExporter, template_file=None):
cfg = traitlets.config.get_config()
exporter = cls(cfg)
exporter.exclude_input_prompt=True
exporter.exclude_output_prompt=True
exporter.anchor_link_text = ' '
exporter.template_file = 'jekyll.tpl' if template_file is None else template_file
exporter.template_path.append(str(Path(__file__).parent/'templates'))
return exporter
#export
process_cells = [remove_fake_headers, remove_hidden, remove_empty]
process_cell = [hide_cells, collapse_cells, remove_widget_state, add_jekyll_notes, escape_latex, cite2link]
#export
def _nb2htmlfname(nb_path, dest=None):
if dest is None: dest = get_config().path("doc_path")
return Path(dest)/re_digits_first.sub('', nb_path.with_suffix('.html').name)
#hide
test_eq(_nb2htmlfname(Path('00a_export.ipynb')), get_config().path("doc_path")/'export.html')
test_eq(_nb2htmlfname(Path('export.ipynb')), get_config().path("doc_path")/'export.html')
test_eq(_nb2htmlfname(Path('00ab_export_module_1.ipynb')), get_config().path("doc_path")/'export_module_1.html')
test_eq(_nb2htmlfname(Path('export.ipynb'), '.'), Path('export.html'))
#export
def convert_nb(fname, cls=HTMLExporter, template_file=None, exporter=None, dest=None, execute=True):
"Convert a notebook `fname` to html file in `dest_path`."
fname = Path(fname).absolute()
nb = read_nb(fname)
meta_jekyll = get_metadata(nb['cells'])
meta_jekyll['nb_path'] = str(fname.relative_to(get_config().path("lib_path").parent))
cls_lvl = find_default_level(nb['cells'])
mod = find_default_export(nb['cells'])
nb['cells'] = compose(*process_cells,partial(add_show_docs, cls_lvl=cls_lvl))(nb['cells'])
_func = compose(partial(copy_images, fname=fname, dest=get_config().path("doc_path")), *process_cell, treat_backticks)
nb['cells'] = [_func(c) for c in nb['cells']]
if execute: nb = execute_nb(nb, mod=mod)
nb['cells'] = [clean_exports(c) for c in nb['cells']]
if exporter is None: exporter = nbdev_exporter(cls=cls, template_file=template_file)
with open(_nb2htmlfname(fname, dest=dest),'w') as f:
f.write(exporter.from_notebook_node(nb, resources=meta_jekyll)[0])
#export
def _notebook2html(fname, cls=HTMLExporter, template_file=None, exporter=None, dest=None, execute=True):
time.sleep(random.random())
print(f"converting: {fname}")
try:
convert_nb(fname, cls=cls, template_file=template_file, exporter=exporter, dest=dest, execute=execute)
return True
except Exception as e:
print(e)
return False
#export
def notebook2html(fname=None, force_all=False, n_workers=None, cls=HTMLExporter, template_file=None,
exporter=None, dest=None, pause=0, execute=True):
"Convert all notebooks matching `fname` to html files"
files = nbglob(fname)
if len(files)==1:
force_all = True
if n_workers is None: n_workers=0
if not force_all:
# only rebuild modified files
files,_files = [],files.copy()
for fname in _files:
fname_out = _nb2htmlfname(Path(fname).absolute(), dest=dest)
if not fname_out.exists() or os.path.getmtime(fname) >= os.path.getmtime(fname_out):
files.append(fname)
if len(files)==0: print("No notebooks were modified")
else:
if sys.platform == "win32": n_workers = 0
passed = parallel(_notebook2html, files, n_workers=n_workers, cls=cls,
template_file=template_file, exporter=exporter, dest=dest, pause=pause, execute=execute)
if not all(passed):
msg = "Conversion failed on the following:\n"
print(msg + '\n'.join([f.name for p,f in zip(passed,files) if not p]))
with tempfile.TemporaryDirectory() as d:
print(d)
notebook2html('01_sync.ipynb', dest='.', n_workers=0);
#hide
# Test when an argument is given to notebook2html
with tempfile.TemporaryDirectory() as d:
p1 = Path(d).joinpath('sync.html')
notebook2html('01_sync.ipynb', dest=d, n_workers=0);
assert p1.exists()
#slow
#hide
# Test when no argument is given to notebook2html
with tempfile.TemporaryDirectory() as d:
dest_files = [_nb2htmlfname(Path(f), dest=d) for f in nbglob()]
[f.unlink() for f in dest_files if f.exists()]
notebook2html(fname=None, dest=d);
for f in dest_files: assert f.exists(), f
```
Hide cells starting with `#export` and only leaves the prose and the tests. If `fname` is not specified, this will convert all notebooks not beginning with an underscore in the `nb_folder` defined in `setting.ini`. Otherwise `fname` can be a single filename or a glob expression.
By default, only the notebooks that are more recent than their html counterparts are modified, pass `force_all=True` to change that behavior.
```
#hide
#notebook2html(force_all=True)
#export
def convert_md(fname, dest_path, img_path='docs/images/', jekyll=True):
"Convert a notebook `fname` to a markdown file in `dest_path`."
fname = Path(fname).absolute()
if not img_path: img_path = fname.stem + '_files/'
Path(img_path).mkdir(exist_ok=True, parents=True)
nb = read_nb(fname)
meta_jekyll = get_metadata(nb['cells'])
try: meta_jekyll['nb_path'] = str(fname.relative_to(get_config().path("lib_path").parent))
except: meta_jekyll['nb_path'] = str(fname)
nb['cells'] = compose(*process_cells)(nb['cells'])
nb['cells'] = [compose(partial(adapt_img_path, fname=fname, dest=dest_path, jekyll=jekyll), *process_cell)(c)
for c in nb['cells']]
fname = Path(fname).absolute()
dest_name = fname.with_suffix('.md').name
exp = nbdev_exporter(cls=MarkdownExporter, template_file='jekyll-md.tpl' if jekyll else 'md.tpl')
export = exp.from_notebook_node(nb, resources=meta_jekyll)
md = export[0]
for ext in ['png', 'svg']:
md = re.sub(r'!\['+ext+'\]\((.+)\)', '', md)
with (Path(dest_path)/dest_name).open('w') as f: f.write(md)
if hasattr(export[1]['outputs'], 'items'):
for n,o in export[1]['outputs'].items():
with open(Path(dest_path)/img_path/n, 'wb') as f: f.write(o)
```
This is used to convert the index into the `README.md`.
```
#hide
def _test_md(fn):
fn,dest = Path(fn),Path().absolute().parent
try: convert_md(fn, dest, jekyll=False)
finally: (dest/f'{fn.stem}.md').unlink()
#hide
_test_md('index.ipynb')
# `export[1]['outputs']` will be a `str` if the notebook has no markdown cells to convert.
# e.g. the nb could have a single jekyll markdown cell or just code cells ...
_test_md(f'../tests/single-cell-index.ipynb')
#export
_re_att_ref = re.compile(r' *!\[(.*)\]\(attachment:image.png(?: "(.*)")?\)')
t = ''
test_eq(_re_att_ref.match(t).groups(), ('screenshot', None))
t = ''
test_eq(_re_att_ref.match(t).groups(), ('screenshot', "Deploying to Binder"))
#export
try: from PIL import Image
except: pass # Only required for _update_att_ref
#export
_tmpl_img = '<img alt="{title}" width="{width}" caption="{title}" id="{id}" src="{name}">'
def _update_att_ref(line, path, img):
m = _re_att_ref.match(line)
if not m: return line
alt,title = m.groups()
w = img.size[0]
if alt=='screenshot': w //= 2
if not title: title = "TK: add title"
return _tmpl_img.format(title=title, width=str(w), id='TK: add it', name=str(path))
#export
def _nb_detach_cell(cell, dest, use_img):
att,src = cell['attachments'],cell['source']
mime,img = first(first(att.values()).items())
ext = mime.split('/')[1]
for i in range(99999):
p = dest/(f'att_{i:05d}.{ext}')
if not p.exists(): break
img = b64decode(img)
p.write_bytes(img)
del(cell['attachments'])
if use_img: return [_update_att_ref(o,p,Image.open(p)) for o in src]
else: return [o.replace('attachment:image.png', str(p)) for o in src]
#export
def _nbdev_detach(path_nb, dest="", use_img=False, replace=True):
path_nb = Path(path_nb)
if not dest: dest = f'{path_nb.stem}_files'
dest = Path(dest)
dest.mkdir(exist_ok=True, parents=True)
j = json.load(path_nb.open())
atts = [o for o in j['cells'] if 'attachments' in o]
for o in atts: o['source'] = _nb_detach_cell(o, dest, use_img)
if atts and replace: json.dump(j, path_nb.open('w'))
if not replace: return j
@call_parse
def nbdev_detach(path_nb:Param("Path to notebook"),
dest:Param("Destination folder", str)="",
use_img:Param("Convert markdown images to img tags", bool_arg)=False,
replace:Param("Write replacement notebook back to `path_bn`", bool_arg)=True):
"Export cell attachments to `dest` and update references"
_nbdev_detach(path_nb, dest, use_img, replace)
#export
_re_index = re.compile(r'^(?:\d*_|)index\.ipynb$')
#export
def make_readme():
"Convert the index notebook to README.md"
index_fn = None
for f in get_config().path("nbs_path").glob('*.ipynb'):
if _re_index.match(f.name): index_fn = f
assert index_fn is not None, "Could not locate index notebook"
print(f"converting {index_fn} to README.md")
convert_md(index_fn, get_config().config_file.parent, jekyll=False)
n = get_config().config_file.parent/index_fn.with_suffix('.md').name
shutil.move(n, get_config().config_file.parent/'README.md')
if Path(get_config().config_file.parent/'PRE_README.md').is_file():
with open(get_config().config_file.parent/'README.md', 'r') as f: readme = f.read()
with open(get_config().config_file.parent/'PRE_README.md', 'r') as f: pre_readme = f.read()
with open(get_config().config_file.parent/'README.md', 'w') as f: f.write(f'{pre_readme}\n{readme}')
#export
@call_parse
def nbdev_build_docs(fname:Param("A notebook name or glob to convert", str)=None,
force_all:Param("Rebuild even notebooks that haven't changed", bool_arg)=False,
mk_readme:Param("Also convert the index notebook to README", bool_arg)=True,
n_workers:Param("Number of workers to use", int)=None,
pause:Param("Pause time (in secs) between notebooks to avoid race conditions", float)=0.5):
"Build the documentation by converting notebooks matching `fname` to html"
notebook2html(fname=fname, force_all=force_all, n_workers=n_workers, pause=pause)
if fname is None: make_sidebar()
if mk_readme: make_readme()
#export
@call_parse
def nbdev_nb2md(fname:Param("A notebook file name to convert", str),
dest:Param("The destination folder", str)='.',
img_path:Param("Folder to export images to")="",
jekyll:Param("To use jekyll metadata for your markdown file or not", bool_arg)=False,):
"Convert the notebook in `fname` to a markdown file"
_nbdev_detach(fname, dest=img_path)
convert_md(fname, dest, jekyll=jekyll, img_path=img_path)
```
## Sidebar
```
#export
import time,random,warnings
#export
def _leaf(k,v):
url = 'external_url' if "http" in v else 'url'
#if url=='url': v=v+'.html'
return {'title':k, url:v, 'output':'web,pdf'}
#export
_k_names = ['folders', 'folderitems', 'subfolders', 'subfolderitems']
def _side_dict(title, data, level=0):
k_name = _k_names[level]
level += 1
res = [(_side_dict(k, v, level) if isinstance(v,dict) else _leaf(k,v))
for k,v in data.items()]
return ({k_name:res} if not title
else res if title.startswith('empty')
else {'title': title, 'output':'web', k_name: res})
#export
_re_catch_title = re.compile('^title\s*:\s*(\S+.*)$', re.MULTILINE)
#export
def _get_title(fname):
"Grabs the title of html file `fname`"
with open(fname, 'r') as f: code = f.read()
src = _re_catch_title.search(code)
return fname.stem if src is None else src.groups()[0]
#hide
test_eq(_get_title(get_config().path("doc_path")/'export.html'), "Export to modules")
#export
def _create_default_sidebar():
"Create the default sidebar for the docs website"
dic = {"Overview": "/"}
files = nbglob()
fnames = [_nb2htmlfname(f) for f in sorted(files)]
titles = [_get_title(f) for f in fnames if f.stem!='index']
if len(titles) > len(set(titles)): print(f"Warning: Some of your Notebooks use the same title ({titles}).")
dic.update({_get_title(f):f.name if get_config().host=='github' else f.with_suffix('').name for f in fnames if f.stem!='index'})
return dic
#export
def create_default_sidebar():
"Create the default sidebar for the docs website"
dic = {get_config().lib_name: _create_default_sidebar()}
json.dump(dic, open(get_config().path("doc_path")/'sidebar.json', 'w'), indent=2)
```
The default sidebar lists all html pages with their respective title, except the index that is named "Overview". To build a custom sidebar, set the flag `custom_sidebar` in your `settings.ini` to `True` then change the `sidebar.json` file in the `doc_folder` to your liking. Otherwise, the sidebar is updated at each doc build.
```
#export
def make_sidebar():
"Making sidebar for the doc website form the content of `doc_folder/sidebar.json`"
cfg = get_config()
if not (cfg.path("doc_path")/'sidebar.json').exists() or cfg.get('custom_sidebar', 'False') == 'False':
create_default_sidebar()
sidebar_d = json.load(open(cfg.path("doc_path")/'sidebar.json', 'r'))
res = _side_dict('Sidebar', sidebar_d)
res = {'entries': [res]}
res_s = yaml.dump(res, default_flow_style=False)
res_s = res_s.replace('- subfolders:', ' subfolders:').replace(' - - ', ' - ')
res_s = f"""
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
# Instead edit {'../../sidebar.json'}
"""+res_s
pth = cfg.path("doc_path")/'_data/sidebars/home_sidebar.yml'
pth.mk_write(res_s)
make_sidebar()
```
## Export-
```
#hide
from nbdev.export import *
notebook2script()
```
| github_jupyter |
<!--BOOK_INFORMATION-->
<a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76px; height: 100px; background: white; padding: 1px; border: 1px solid black; margin-right:10px;"></a>
*This notebook contains an excerpt from the book [Machine Learning for OpenCV](https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv) by Michael Beyeler.
The code is released under the [MIT license](https://opensource.org/licenses/MIT),
and is available on [GitHub](https://github.com/mbeyeler/opencv-machine-learning).*
*Note that this excerpt contains only the raw code - the book is rich with additional explanations and illustrations.
If you find this content useful, please consider supporting the work by
[buying the book](https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv)!*
<!--NAVIGATION-->
< [Implementing a Multi-Layer Perceptron (MLP) in OpenCV](09.02-Implementing-a-Multi-Layer-Perceptron-in-OpenCV.ipynb) | [Contents](../README.md) | [Training an MLP in OpenCV to Classify Handwritten Digits](09.04-Training-an-MLP-in-OpenCV-to-Classify-Handwritten-Digits.ipynb) >
https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py
# Getting Acquainted with Deep Learning
Back when deep learning didn't have a fancy name yet, it was called artificial neural
networks. So you already know a great deal about it! This was a respected field in itself, but
after the days of Rosenblatt's perceptron, many researchers and machine learning
practitioners slowly began to lose interest in the field since no one had a good solution for
training a neural network with multiple layers.
With the current popularity of deep learning in both industry and academia, we are
fortunate enough to have a whole range of open-source deep learning frameworks at our
disposal:
- **Google Brain's [TensorFlow](http://www.tensorflow.org)**: This is a machine learning library that describes computations as dataflow graphs. To date, this is one of the most commonly used deep learning libraries. Hence, it is also evolving quickly, so you might have to check back often for software updates. TensorFlow provides a whole range of user interfaces, including Python, C++, and Java interface.
- **Microsoft Research's [Cognitive Toolkit (CNTK)](https://www.microsoft.com/en-us/research/product/cognitive-toolkit)**: This is a deep learning framework that describes neural networks as a series of computational steps via a directed graph.
- UC Berkeley's [Caffe](http://caffe.berkeleyvision.org): This is a pure deep learning framework written in C++, with an additional Python interface.
- **University of Montreal's [Theano](http://deeplearning.net/software/theano)**: This is a numerical computation library compiled to run efficiently on CPU and GPU architectures. Theano is more than a machine learning library; it can express any computation using a specialized computer algebra system. Hence, it is best suited for people who wish to write their machine learning algorithms from scratch.
- **[Torch](http://www.torch.ch)**: This is a scientific computing framework based on the Lua programming language. Like Theano, Torch is more than a machine learning library, but it is heavily used for deep learning by companies such as Facebook, IBM, and Yandex.
Finally, there is also [Keras](http://keras.io), which we will be using in the following sections. In contrast to
the preceding frameworks, Keras understands itself as an interface rather than an end-toend
deep learning framework. It allows you to specify deep neural nets using an easy-tounderstand
API, which can then be run on backends, such as TensorFlow, CNTK, or
Theano.
## Getting acquainted with Keras
The core data structure of Keras is a model, which is similar to OpenCV's classifier object,
except it focuses on neural networks only. The simplest type of model is the `Sequential`
model, which arranges the different layers of the neural net in a linear stack, just like we did
for the MLP in OpenCV:
```
from keras.models import Sequential
model = Sequential()
```
Then different layers can be added to the model one by one. In Keras, layers do not just
contain neurons, they also perform a function. Some core layer types include the following:
- `Dense`: This is a densely connected layer. This is exactly what we used when we designed our MLP: a layer of neurons that is connected to every neuron in the previous layer.
- `Activation`: This applies an activation function to an output. Keras provides a whole range of activation functions, including OpenCV's identify function (`linear`), the hyperbolic tangent (`tanh`), a sigmoidal squashing function (`sigmoid`), a softmax function (`softmax`), and many more.
- `Reshape`: This reshapes an output to a certain shape.
There are other layers that calculate arithmetic or geometric operations on their inputs:
- **Convolutional layers**: These layers allow you to specify a kernel with which the input layer is convolved. This allows you to perform operations such as a Sobel filter or apply a Gaussian kernel in 1D, 2D, or even 3D.
- **Pooling layers**: These layers perform a max pooling operation on their input, where the output neuron's activity is given by the maximally active input neuron.
Some other layers that are popular in deep learning are as follows:
- `Dropout`: This layer randomly sets a fraction of input units to zero at each update. This is a way to inject noise into the training process, making it more robust.
- `Embedding`: This layer encodes categorical data, similar to some functions from scikit-learn's `preprocessing` module.
- `GaussianNoise`: This layer applies additive zero-centered Gaussian noise. This is another way of injecting noise into the training process, making it more robust.
A perceptron similar to the preceding one could thus be implemented using a
`Dense` layer that has two inputs and one output. Staying true to our earlier
example, we will initialize the weights to zero and use the hyperbolic tangent as
an activation function:
```
from keras.layers import Dense
model.add(Dense(1, activation='linear', input_dim=2, kernel_initializer='zeros'))
```
Finally, we want to specify the training method. Keras provides a number of optimizers,
including the following:
- **stochastic gradient descent** (`'sgd'`): This is what we have discussed before
- **root mean square propagation** (`'RMSprop'`): This is a method in which the
learning rate is adapted for each of the parameters
- **adaptive moment estimation** (`'Adam'`): This is an update to root mean square propagation and many more
In addition, Keras also provides a number of different loss functions:
- **mean squared error** (`'mean_squared_error'`): This is what was discussed before
- **hinge loss** (`'hinge'`): This is a maximum-margin classifier often used with SVM, as discussed in [Chapter 6](06.00-Detecting-Pedestrians-with-Support-Vector-Machines.ipynb), *Detecting Pedestrians with Support Vector Machines*, and many more
You can see that there's a whole plethora of parameters to be specified and methods to
choose from. To stay true to our aforementioned perceptron implementation, we will
choose stochastic gradient descent as an optimizer, the mean squared error as a cost
function, and accuracy as a scoring function:
```
model.compile(optimizer='sgd',
loss='mean_squared_error',
metrics=['accuracy'])
```
In order to compare the performance of the Keras implementation to our home-brewed
version, we will apply the classifier to the same dataset:
```
from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=100, centers=2, cluster_std=2.2, random_state=42)
```
Finally, a Keras model is fit to the data with a very familiar syntax. Here, we can also choose
how many iterations to train for (`epochs`), how many samples to present before we
calculate the error gradient (`batch_size`), whether to shuffle the dataset (`shuffle`), and
whether to output progress updates (`verbose`):
```
model.fit(X, y, epochs=400, batch_size=100, shuffle=False, verbose=0)
```
After the training completes, we can evaluate the classifier as follows:
```
model.evaluate(X, y)
```
Here, the first reported value is the mean squared error, whereas the second value denotes
accuracy. This means that the final mean squared error was 0.04, and we had 100%
accuracy. Way better than our own implementation!
```
import numpy as np
np.random.seed(1337) # for reproducibility
```
With these tools in hand, we are now ready to approach a real-world dataset!
<!--NAVIGATION-->
< [Implementing a Multi-Layer Perceptron (MLP) in OpenCV](09.02-Implementing-a-Multi-Layer-Perceptron-in-OpenCV.ipynb) | [Contents](../README.md) | [Training an MLP in OpenCV to Classify Handwritten Digits](09.04-Training-an-MLP-in-OpenCV-to-Classify-Handwritten-Digits.ipynb) >
| github_jupyter |
# Best Practices for Preprocessing Natural Language Data
In this notebook, we improve the quality of our Project Gutenberg word vectors by adopting best-practices for preprocessing natural language data.
**N.B.:** Some, all or none of these preprocessing steps may be helpful to a given downstream application.
#### Load dependencies
```
# the initial block is copied from creating_word_vectors_with_word2vec.ipynb
import nltk
from nltk import word_tokenize, sent_tokenize
import gensim
from gensim.models.word2vec import Word2Vec
from sklearn.manifold import TSNE
import pandas as pd
from bokeh.io import output_notebook, output_file
from bokeh.plotting import show, figure
%matplotlib inline
nltk.download('punkt')
# new!
import string
from nltk.corpus import stopwords
from nltk.stem.porter import *
from gensim.models.phrases import Phraser, Phrases
from keras.preprocessing.text import one_hot
nltk.download('stopwords')
```
#### Load data
```
nltk.download('gutenberg')
from nltk.corpus import gutenberg
gberg_sents = gutenberg.sents()
```
#### Iteratively preprocess a sentence
##### a tokenized sentence:
```
gberg_sents[4]
```
##### to lowercase:
```
[w.lower() for w in gberg_sents[4]]
```
##### remove stopwords and punctuation:
```
stpwrds = stopwords.words('english') + list(string.punctuation)
stpwrds
[w.lower() for w in gberg_sents[4] if w not in stpwrds]
```
##### stem words:
```
stemmer = PorterStemmer()
[stemmer.stem(w.lower()) for w in gberg_sents[4] if w not in stpwrds]
```
##### handle bigram collocations:
```
phrases = Phrases(gberg_sents) # train detector
bigram = Phraser(phrases) # create a more efficient Phraser object for transforming sentences
bigram.phrasegrams # output count and score of each bigram
"Jon lives in New York City".split()
bigram["Jon lives in New York City".split()]
```
#### Preprocess the corpus
```
lower_sents = []
for s in gberg_sents:
lower_sents.append([w.lower() for w in s if w not in list(string.punctuation)])
lower_sents[0:5]
lower_bigram = Phraser(Phrases(lower_sents))
lower_bigram.phrasegrams # miss taylor, mr woodhouse, mr weston
lower_bigram["jon lives in new york city".split()]
lower_bigram = Phraser(Phrases(lower_sents, min_count=32, threshold=64))
lower_bigram.phrasegrams
# as in Maas et al. (2001):
# - leave in stop words ("indicative of sentiment")
# - no stemming ("model learns similar representations of words of the same stem when data suggests it")
clean_sents = []
for s in lower_sents:
clean_sents.append(lower_bigram[s])
clean_sents[0:9]
clean_sents[6] # could consider removing stop words or common words
```
#### Run word2vec
```
# max_vocab_size can be used instead of min_count (which has increased here)
# model = Word2Vec(sentences=clean_sents, size=64, sg=1, window=10, min_count=10, seed=42, workers=8)
# model.save('clean_gutenberg_model.w2v')
```
#### Explore model
```
# skip re-training the model with the next line:
model = gensim.models.Word2Vec.load('clean_gutenberg_model.w2v')
len(model.wv.vocab) # down from 17k in previous notebook
model['ma_am']
model.most_similar('ma_am')
# swap woman and man
model.most_similar(positive=['ma_am', 'man'], negative=['woman'])
model.most_similar(positive=['father', 'woman'], negative=['man'])
```
#### Reduce word vector dimensionality with t-SNE
```
tsne = TSNE(n_components=2, n_iter=1000)
X_2d = tsne.fit_transform(model[model.wv.vocab])
coords_df = pd.DataFrame(X_2d, columns=['x','y'])
coords_df['token'] = model.wv.vocab.keys()
coords_df.head()
# coords_df.to_csv('clean_gutenberg_tsne.csv', index=False)
```
#### Visualise
```
coords_df = pd.read_csv('clean_gutenberg_tsne.csv')
_ = coords_df.plot.scatter('x', 'y', figsize=(12,12), marker='.', s=10, alpha=0.2)
output_notebook()
subset_df = coords_df.sample(n=5000)
p = figure(plot_width=800, plot_height=800)
_ = p.text(x=subset_df.x, y=subset_df.y, text=subset_df.token)
show(p)
# output_file() here
```
| github_jupyter |
# Rules and relations
SEGAR provides a framework on the simulator rules, which determine how states transition from one to another over subsequent time steps. SEGAR comes with a set of built-in rules for the simulator, but these can be changed at the user's disgression.
### Rules
Rules are functions from one set of factors to another. Consider the following built-in rules:
```
from segar.rules import lorentz_law, move, apply_friction
print(lorentz_law)
print(move)
print(apply_friction)
```
These rules all apply on sets of (sets of) factors (see the factors README for more details). If the rule contains a single set of factors, this applies to a single Entity (see the things README for more details). If a rule contains multiple sets, then the rule applies to multiple things.
Rules apply automatic pattern matching, such that a rule will not return a valid change in factor unless the input pattern matches the factors contained in the inputs and the parameters:
```
from segar.factors import Position, Charge, Mass, Velocity, Friction
from segar.sim import Simulator
from segar.things import Object, Tile
from segar.parameters import Gravity, MinVelocity
sim = Simulator() # Must initialize sim before creating things.
o = Object(initial_factors={Charge: 0.1, Mass: 1.0, Position: [-0.5, 0.5]},
sim=sim)
print(o.keys())
o2 = Object(initial_factors={Charge: 0.2, Mass: 2.0, Velocity: [1.0, 1.0]}, sim=sim)
t = Tile(initial_factors={Friction: 1.0}, sim=sim)
print(t.keys())
g = Gravity(1.0) # Gravity parameter
min_vel = MinVelocity(1e-5) # Min velocity parameter, for allowing objects to "stop"
```
Note that the objects contain factors needed for the lorentz law, but not the tile. The tile contains the factors needed for friction. If we pass the wrong things to lorentz law it will return `DidNotMatch`.
```
print(lorentz_law(o))
print(lorentz_law(o, t))
```
However, if we pass the correct inputs:
```
l_apply = lorentz_law(o, o2)
print(l_apply, type(l_apply))
f_apply = apply_friction(o2, t, g)
print(f_apply, type(f_apply))
```
The output of these applications are `Aggregate` objects, which inform the sim to aggregate all rules that apply to the target factor as the new value. In this case, what is aggregating is the acceleration of the object, corresponding to the addition of forces.
Rules can also return differentials over time, such as what happens when we apply velocity to change position:
```
m_apply = move(o2, min_vel)
print(m_apply, type(m_apply))
```
This rule application is a `Differential`, which says that the position will change in the direction of the velocity, integrated over the time interval, assuming that the velocity is constant over said interval.
Finally, there is a `SetFactor` application, which informs the sim of a new value for a factor.
Given a set of applications provided from the rules, the sim will decide which rules to apply and when.
Roughly speaking:
1) The sim will first apply all valid rules to everything but position and velocity.
2) Then the sim will apply all rules to velocity
3) Finally, the sim will apply rules to positions, correcting for any collisions that might occur.
* The sim will choose, if the different rules apply to the same factor, which rules to apply. `SetFactor` is applied over `Aggregate` and `Differential`. Additional rule conditions can increase the weight of a rule application over others.
### Rule design
SEGAR allows users to design their own rules, then add them to the sim. Let's design a custom rule:
```
from segar.rules import TransitionFunction, Differential
@TransitionFunction
def fast_loses_mass(m: Mass, v: Velocity) -> Differential[Velocity]:
m_new = m * (1. - max(v.norm(), 1.)) # Scale the mass by the velocity
return Differential[Velocity](m, m_new)
print(fast_loses_mass)
```
This is a strange rule, but it helps demonstrate the flexibility for creating custom rules in SEGAR. Let's see how it would be applied:
```
fast_loses_mass(o2)
```
Note: Some care needs to be taken when applying rules, as they may cause factors to do unusual things (such as become negative).
Finally, we can add the rule to our sim:
```
sim.add_rule(fast_loses_mass)
print(sim.rules)
```
Now verify that this rule indeed applies to the mass:
```
print('before: ', o[Mass], o2[Mass])
sim.step()
print('after: ', o[Mass], o2[Mass])
```
There is additional functionality in rules, including adding conditions. See the source code for more details.
| github_jupyter |
# Logistic Regression
## Predicting a Category or Class
```
%run Include-1-File-Paths.ipynb
%run Include-2-Shared-Functions.ipynb
%run Include-3-Shared-Viz-Functions.ipynb
```
**ACKNOWLEDGEMENT**
**Some of the code in this notebook is based on John D. Wittenauer's notebooks that cover the exercises in Andrew Ng's course on Machine Learning on Coursera. I've also modified some code from Sebastian Raschka's book *Python Machine Learning*, and used some code from Sonya Sawtelle's [blog](https://sdsawtelle.github.io/blog/output/week3-andrew-ng-machine-learning-with-python.html). **
## What is Logistic Regression?
Despite the fancy technical name, logistic regression is not a scary thing. It just means predicting a class or category rather than a number.
Or more accurately, it's about predicting a categorical value rather than a a numerical value.
## Why do Logistic Regression?
Because many business problems are really classification problems in disguise.
- Will person A respond to my marketing email?
- Will customer B renew their subscription for our services?
- Will this jet engine work well once it's installed on an aircraft?
- Will student C be accepted by Princeton?
- Is this bank note a counterfeit?
### Exercise 1
Can you think of a (business) problem you're familiar with that's really a classification problem in disguise?
## The Problem We'll Tackle
How to distinguish a real from a fake banknote?
Modern banknotes have a large number of subtle distinguishing characteristics like watermarks, background lettering, and holographic images.
It would be hard (and time consuming and even counterproductive) to write these down as a concrete set of rules. Especially as notes can age, tear, and get mangled in a number of ways these rules can start to get very complex.
Can a machine learn to do it using image data?
Let's see...
## Load the Data
About the data. It comes from the [University of California at Irvine's repository of data sets](https://archive.ics.uci.edu/ml/datasets/banknote+authentication). According to the authors of the data,
> "Data were extracted from images that were taken from genuine and forged banknote-like specimens. For digitization, an industrial camera usually used for print inspection was used. The final images have 400x 400 pixels. Due to the object lens and distance to the investigated object gray-scale pictures with a resolution of about 660 dpi were gained. [A] Wavelet Transform tool were used to extract features from images."
The features of the data are values from this wavelet transform process that the images were put through.
```
# Load the data into a dataframe
file_url = os.path.join(data_dir_path, "forged-bank-notes.csv")
#file_url
# header=0 drops the header row in the csv file
data = pd.read_csv(file_url, header=0, names=['A1', 'A2', 'A3', 'A4', 'Genuine'])
# Number of rows and columns in the data
print("The dataset has {} (rows, columns)".format(data.shape))
# First few rows of the datastet
data.tail()
```
## Step 1: Visualize the Data
```
# Scatter of A1 versus A2
positive = data[data['Genuine'].isin([1])]
negative = data[data['Genuine'].isin([0])]
fig, ax = plt.subplots(figsize=(12,8))
ax.scatter(positive['A1'], positive['A2'], s=30, c='b', marker='+', label='Genuine')
ax.scatter(negative['A1'], negative['A2'], s=30, c='r', marker='s', label='Forged')
ax.legend(loc='lower right')
ax.set_xlabel('A1')
ax.set_ylabel('A2')
plt.title('Bank Note Validation Based on Features A1 and A2');
# Scatter of A3 versus A4
positive = data[data['Genuine'].isin([1])]
negative = data[data['Genuine'].isin([0])]
fig, ax = plt.subplots(figsize=(12,8))
ax.scatter(positive['A3'], positive['A4'], s=30, c='b', marker='+', label='Genuine')
ax.scatter(negative['A3'], negative['A4'], s=30, c='r', marker='s', label='Forged')
ax.legend(loc='lower right')
ax.set_xlabel('A3')
ax.set_ylabel('A4')
plt.title('Bank Note Validation Based on Features A3 and A4');
# Scatter of A1 versus A4
positive = data[data['Genuine'].isin([1])]
negative = data[data['Genuine'].isin([0])]
fig, ax = plt.subplots(figsize=(12,8))
ax.scatter(positive['A1'], positive['A4'], s=30, c='b', marker='+', label='Genuine')
ax.scatter(negative['A1'], negative['A4'], s=30, c='r', marker='s', label='Forged')
ax.legend(loc='lower right')
ax.set_xlabel('A1')
ax.set_ylabel('A4')
plt.title('Bank Note Validation Based on Features A1 and A4');
# Scatter of A2 versus A3
positive = data[data['Genuine'].isin([1])]
negative = data[data['Genuine'].isin([0])]
fig, ax = plt.subplots(figsize=(12,8))
ax.scatter(positive['A2'], positive['A3'], s=30, c='b', marker='+', label='Genuine')
ax.scatter(negative['A2'], negative['A3'], s=30, c='r', marker='s', label='Forged')
ax.legend(loc='lower right')
ax.set_xlabel('A2')
ax.set_ylabel('A3')
plt.title('Bank Note Validation Based on Features A2 and A3');
# Scatter of A2 versus A4
positive = data[data['Genuine'].isin([1])]
negative = data[data['Genuine'].isin([0])]
fig, ax = plt.subplots(figsize=(12,8))
ax.scatter(positive['A2'], positive['A4'], s=30, c='b', marker='+', label='Genuine')
ax.scatter(negative['A2'], negative['A4'], s=30, c='r', marker='s', label='Forged')
ax.legend(loc='lower right')
ax.set_xlabel('A2')
ax.set_ylabel('A4')
plt.title('Bank Note Validation Based on Features A2 and A4');
```
### Exercise 2
Use Orange to replicate the scatter plots for all features in the dataset. The data is available from the course's [GitHub repository](https://github.com/jsub10/Machine-Learning-Course-2018/blob/master/DataSets/forged-bank-notes.xlsx).
Let's use features A1 and A2 alone to begin with. In addition to keeping things simpler, it will let us visualize what's going on.
<img src="../Images/classification-lines.jpg" alt="Classification Boundaries" style="width:600px"/>
Right away we see that this doesn't even look like a regular regression problem -- there are two classes -- Genuine and Forged. These are not continuous values -- it's one or the other.
Moreover, the classes don't separate cleanly. This is what we usually face in the real world. No matter how we try to separate these classes, we're probably never going to get it 100% right.
## Step 2: Define the Task You Want to Accomplish
Task = Classify a banknote as genuine or counterfeit given the values of its features A1 and A2.
### Step 2a: Identify the Inputs
The inputs are the features A1 and A2 generated by the instrument reading the images (the wavelet transform tool).
```
# First few rows of the input
inputs = data[['A1', 'A2']]
inputs.head()
```
### Step 2b: Identify the Output/Target
The output or target we'd like to predict is the feature called "Genuine". It takes the value 1 when the banknote is real and 0 when the banknote is counterfeit.
```
# First few rows of the output/target
output = data[['Genuine']]
output.head()
```
## Step 3: Define the Model
### Step 3a: Define the Features
We have 2 features: A1 and A2.
### Step 3b: Transform the Inputs Into an Output
Although the task we now face is different from the regression task, we're going to start just as we did before.
$$\hat{y} = w_{0} * x_{0}\ +\ w_{1} * x_{1} +\ w_{2} * x_{2}$$
It looks like the form of a linear regression and that's exactly what it is.
But now a twist...
When we transform the inputs A1 and A2 using the expression
$$\hat{y} = w_{0} * x_{0}\ +\ w_{1} * x_{1} +\ w_{2} * x_{2}$$
we're going to end up with a numeric value. It might be 4.2 or -12.56 or whatever depending on the values you plug in for $w_{0}$, $w_{1}$, and $w_{2}$.
But what we *need* is an output of 0 or 1.
**Question**: How to go from a numeric (continuous) value like -12.56 to a categorical value like 0 or 1?
### The Sigmoid
The way to transform a numerical value into a categorical value is through something called a sigmoid. Here's what it looks like.
```
# Define the sigmoid function or transformation
# NOTE: ALSO PUT INTO THE SharedFunctions notebook
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# Plot the sigmoid function
# Generate the values to be plotted
x_vals = np.linspace(-10,10,1000)
y_vals = [sigmoid(x) for x in x_vals]
# Plot the values
fig, ax = plt.subplots(figsize=(12,6))
ax.plot(x_vals, y_vals, 'blue')
ax.grid()
# Draw some constant lines to aid visualization
plt.axvline(x=0, color='black')
plt.axhline(y=0.5, color='black')
plt.yticks(np.arange(0,1.1,0.1))
plt.xticks(np.arange(-10,11,1))
plt.xlabel(r'$\hat{y}$', fontsize=15)
plt.ylabel(r'$sigmoid(\hat{y})$', fontsize=15)
plt.title('The Sigmoid Transformation', fontsize=15)
ax.plot;
```
Because the sigmoid can never be less than zero or greater than 1, the sigmoid can take any number and convert it into another number *between 0 and 1*.
But that *still* doesn't get us to just 1 or just 0.
If you look at the sigmoid above, you'll see that when $\hat{y}$ is around 5 or higher, $sigmoid(\hat{y})$ is very close to 1.
Similarly, when $\hat{y}$ is around -5 or lower, $sigmoid(\hat{y})$ is very close to 0.
But we develop this much simpler rule:
- When the value of $sigmoid(\hat{y})$ is greater than 0.5, treat it as 1.
- When the value of $sigmoid(\hat{y})$ is less than or equal to 0.5, treat it as a 0.
That's it. A system for going from any number (positive or negative) to either a 0 or a 1.
Let's recap what we've done so far to build a model for logistic regression.
- A model is a scheme for transforming inputs to an output.
- The model for logistic regression transforms the inputs of each row of the dataset to an output in three steps:
- First, it uses the same scheme we used for regression: $\hat{y} = w_{0} * x_{0}\ +\ w_{1} * x_{1} +\ w_{2} * x_{2}$
- Then it takes $\hat{y}$ and transforms it using the sigmoid into $sigmoid(\hat{y})$.
- Finally,
- if $sigmoid(\hat{y})$ is greater than 0.5, the output is equal to 1.
- if $sigmoid(\hat{y})$ is less than or equal to 0.5, the output is equal to 0.
### Step 3c: Clarify the Parameters of the Model
Just as they were before, the parameters of the model are still $w_{0}$, $w_{1}$, and $w_{2}$.
## Step 4: Define the Penalty for Getting it Wrong
Here's where things change quite a bit from what we've seen in regression.
A penalty applies when the model (i.e., the scheme for transforming inputs to an ouput) gives the wrong answer.
The intuition is: the more wrong the model output is, the higher the penalty should be.
Let's see what this looks like.
```
# Visualize the penalty function when y = 1 and y = 0
x_vals = np.linspace(0,1,100)
y_1_vals = -np.log(x_vals)
y_0_vals = -np.log(1 - x_vals)
fig, ax = plt.subplots(figsize=(12,6))
ax.grid()
ax.plot(x_vals, y_1_vals, color='blue', linestyle='solid', label='actual value of y = 1')
ax.plot(x_vals, y_0_vals, color='orange', linestyle='solid', label='actual value of y = 0')
plt.legend(loc='upper center')
plt.xlabel(r'$sigmoid(\hat{y})$', fontsize=15)
plt.ylabel('Penalty', fontsize=15)
ax.plot;
```

Keep your eye on the orange curve. This is for the case when the actual value of a row in the dataset is 0 (the banknote is a fake). If the banknote is a fake and say $\hat{y}$ is 7, then $sigmoid(\hat{y})$ is going to be close to 1, say 0.9. This means that the penalty is going to be very high because the orange curve increases rapidly in value as it approaches 1.
Similarly, when the actual value of the dataset is 1, the blue penalty curve comes into play. If $\hat{y}$ is 7, then once again $sigmoid(\hat{y})$ is going to be close to 1, say 0.9. But in this case the penalty is very low because the blue curve decreases rapidly in value as it approaches 1.
<img src="../Images/inputs-to-penalty.png" alt="Going from Inputs to the Penalty" width="500px"/>
<img src="../Images/logistic-regression-dataset-view.png" alt="Going from Inputs to the Penalty" width="500px"/>
## Step 5: Find the Parameter Values that Minimize the Penalty
We've set up the logistic regression model and we'll use the familiar algorithm of gradient descent to learn the optimal values of the parameters.
```
# Set up the training data
X_train = inputs.values
#X_train.shape
# Set up the target data
y = output.values
# Change the shape of y to suit scikit learn's requirements
y_train = np.array(list(y.squeeze()))
#y_train.shape
# Set up the logistic regression model from SciKit Learn
from sklearn.linear_model import LogisticRegression
# Solvers that seem to work well are 'liblinear' and 'newton-cg"
lr = LogisticRegression(C=100.0, random_state=0, solver='liblinear', verbose=2)
# Train the model and find the optimal parameter values
lr.fit(X_train, y_train)
# These are the optimal values of w0, w1 and w2
w0 = lr.intercept_[0]
w1 = lr.coef_.squeeze()[0]
w2 = lr.coef_.squeeze()[1]
print("w0: {}\nw1: {}\nw2: {}".format(w0, w1, w2))
```
## Step 6: Use the Model and Optimal Parameter Values to Make Predictions
```
# Genuine or fake for the entire data set
y_pred = lr.predict(X_train)
print(y_pred)
# How do the predictions compare with the actual labels on the data set?
y_train == y_pred
# The probabilities of [Genuine = 0, Genuine = 1]
y_pred_probs = lr.predict_proba(X_train)
print(y_pred_probs)
# Where did the model misclassify banknotes?
errors = data[data['Genuine'] != y_pred]
#errors
# Following Sonya Sawtelle
# (https://sdsawtelle.github.io/blog/output/week3-andrew-ng-machine-learning-with-python.html)
# This is the classifier boundary line when z=0
x1 = np.linspace(-6,6,100) # Array of A1 value
x2 = (-w0/w2) - (w1/w2)*x1 # Corresponding A2 values along the line z=0
# Following Sonya Sawtelle
# (https://sdsawtelle.github.io/blog/output/week3-andrew-ng-machine-learning-with-python.html)
# Scatter of V1 versus V2
positive = data[data['Genuine'].isin([1])]
negative = data[data['Genuine'].isin([0])]
fig, ax = plt.subplots(figsize=(15,10))
#colors = ["r", "b"]
#la = ["Forged", "Genuine"]
#markers = [colors[gen] for gen in data['Genuine']] # this is a cool way to color the categories!
#labels = [la[gen] for gen in data['Genuine']]
#ax.scatter(data['V1'], data['V2'], color=markers, s=10, label=labels)
ax.scatter(positive['A1'], positive['A2'], s=30, c='b', marker='+', label='Genuine')
ax.scatter(negative['A1'], negative['A2'], s=30, c='r', marker='s', label='Forged')
ax.set_xlabel('A1')
ax.set_ylabel('A2')
# Now plot black circles around data points that were incorrectly predicted
ax.scatter(errors["A1"], errors["A2"], facecolors="none", edgecolors="m", s=80, label="Wrongly Classified")
# Finally plot the line which represents the decision boundary
ax.plot(x1, x2, color="green", linestyle="--", marker=None, label="boundary")
ax.legend(loc='upper right')
plt.title('Bank Note Validation Based on Features A1 and A2');
```
Even though we've used the sigmoid function to transform $\hat{y}$ values, the $\hat{y}$ values are themselves the result of a simple linear model:
$$\hat{y} = w_{0} * x_{0}\ +\ w_{1} * x_{1} +\ w_{2} * x_{2}$$
But clearly, the A1-A2 values of genuine and forged banknotes are somewhat mixed up -- a line (or something straight) is never going to classify the banknotes reliably. There are many mistakes as denoted by the points circled in magenta in the diagram we saw earlier.
What if we made the model non-linear? We consider that in the next session.
## Step 7: Measure the Performance of the Model
We're going to see how this is done using the Test and Score and Confusion Matrix widgets in Orange.
## Summary
- We've taken the same basic scheme of transforming inputs and into and output that we used for linear regression and turned it into a way to classify things.
- The sigmoid is used to convert a numerical (continous) value into a categorical (discrete) value. This is done in two steps.
- First, the value of the sigmoid is returned. This is a numerical value between 0 and 1 and can be interpreted as the probability of belonging to a particular class.
- Second, we use a simple "cutoff" rule -- if the sigmoid value is greater than 0.5, the class is a 1; otherwise it's a 0.
| github_jupyter |
# "Azure speech recognition for Irish, part 2"
> "json output contains nbest, timestamps, and text without replacements"
- toc: false
- branch: master
- comments: true
- categories: [azure, irish, asr]
```
%%capture
!pip install azure-cognitiveservices-speech
!pip install youtube-dl
%%capture
!youtube-dl https://www.youtube.com/watch?v=cfjdfaqWY3Y
import azure.cognitiveservices.speech as speechsdk
```
Use either Key1 or Key2 (on [Azure Portal](https://portal.azure.com/), in "Keys and Endpoints" from the menu on the left hand side of the screen).
```
_SUBS=input('put your subscription key here: ')
_LOC='westeurope'
speech_config = speechsdk.SpeechConfig(region=_LOC, subscription=_SUBS)
!wget https://upload.wikimedia.org/wikipedia/commons/6/60/MSF_chapter_3.ogg https://upload.wikimedia.org/wikipedia/commons/e/ee/MSF_chapter_4.ogg https://upload.wikimedia.org/wikipedia/commons/b/b3/MSF_chapter_5.ogg https://upload.wikimedia.org/wikipedia/commons/2/21/MSF_chapter_6.ogg https://upload.wikimedia.org/wikipedia/commons/7/71/MSF_chapter_7.ogg https://upload.wikimedia.org/wikipedia/commons/d/d5/MSF_chapter_8.ogg
!ffmpeg -i MSF_chapter_5.ogg -acodec pcm_s16le -ac 1 -ar 16000 MSF_chapter_5.wav
speech_config.speech_recognition_language = 'ga-IE'
speech_config.request_word_level_timestamps()
speech_config.output_format = speechsdk.OutputFormat(1)
speech_config.endpoint_id=f'https://{_LOC}.api.cognitive.microsoft.com/sts/v1.0/issuetoken'
# https://github.com/Azure-Samples/cognitive-services-speech-sdk/blob/master/samples/python/console/speech_sample.py
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
import time
import json
def speech_recognize_continuous_from_file(speech_config, filename):
"""performs continuous speech recognition with input from an audio file"""
speech_config = speech_config
audio_config = speechsdk.audio.AudioConfig(filename=filename)
outfilename = filename.replace('.wav', '.json')
outfile = open(outfilename, 'a')
speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, language='ga-IE', audio_config=audio_config)
done = False
def stop_cb(evt):
"""callback that signals to stop continuous recognition upon receiving an event `evt`"""
print('CLOSING on {}'.format(evt))
nonlocal done
done = True
def cancelled(evt):
result = evt.result
cancellation_details = result.cancellation_details
print("Speech Recognition canceled: {}".format(cancellation_details.reason))
if cancellation_details.reason == speechsdk.CancellationReason.Error:
print("Error details: {}".format(cancellation_details.error_details))
def recognised(evt):
response = json.loads(evt.result.json)
outfile.write('{}\n'.format(evt.result.json))
# Connect callbacks to the events fired by the speech recognizer
speech_recognizer.recognizing.connect(lambda evt: print('RECOGNIZING: {}'.format(evt)))
speech_recognizer.recognized.connect(recognised)
speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED: {}'.format(evt)))
speech_recognizer.session_stopped.connect(lambda evt: print('SESSION STOPPED {}'.format(evt)))
speech_recognizer.canceled.connect(cancelled)
# stop continuous recognition on either session stopped or canceled events
speech_recognizer.session_stopped.connect(stop_cb)
speech_recognizer.canceled.connect(stop_cb)
# Start continuous speech recognition
speech_recognizer.start_continuous_recognition()
while not done:
time.sleep(.5)
speech_recognizer.stop_continuous_recognition()
outfile.close()
for i in "345678":
speech_recognize_continuous_from_file(speech_config, f'MSF_chapter_{i}.wav')
```
| github_jupyter |
# Proving stability of a Boolean network motif
Stability in a biological system is defined as the presence of a single fix point and no cycles (that is loops with more than one state). It can be thought of as a measure of robustness; if you believe your model represents a homoestatic system, or a system at equilibrium, we can use stability as a way to test that the model is sound. This was discussed in the previous practical about using the BMA, and Z3 is used in the BMA to prove stability in cases where the default algorithm cannot (i.e. when you are using "Further Testing").
Here we will test a small Boolean network model representing "perfect adaption"- a negative feed forward loop. In this case we are modelling it as a deterministic system; all variables update at the same time. Furthermore, we are modelling it with a constant "on" input.
## Getting started
In this section we will be using Z3 as a library. To start we will need to download the files if they are not already available. These first cells download Z3 as a zip, extract it, and load it into memory. We then reference the extracted file and open it as a module.
** If the first cell does not run, manually download z3 from the link for your operating system and unzip it to a folder with the notebooks called "z3" **
```
#r "System.IO.Compression.FileSystem.dll"
open System
open System.IO
open System.IO.Compression
open System.Net
//Specify Tls version to avoid cryptic connection errors
System.Net.ServicePointManager.SecurityProtocol <- SecurityProtocolType.Tls12 ||| SecurityProtocolType.Tls11
let wc = new WebClient()
type OS =
| OSX
| Windows
| Linux
let getOS =
match int Environment.OSVersion.Platform with
| 4 | 128 -> Linux
| 6 -> OSX
| _ -> Windows
if true <> System.IO.File.Exists("z3/LICENSE.txt") then
match getOS with
| Linux -> wc.DownloadFile("https://github.com/Z3Prover/z3/releases/download/z3-4.6.0/z3-4.6.0-x64-ubuntu-16.04.zip", @"z3.zip")
//This will take a while
ZipFile.ExtractToDirectory("z3.zip", ".")
System.IO.Directory.Move("z3-4.6.0-x64-ubuntu-16.04","z3")
| Windows ->wc.DownloadFile("https://github.com/Z3Prover/z3/releases/download/z3-4.6.0/z3-4.6.0-x64-win.zip", @"z3.zip")
//This will take a while
ZipFile.ExtractToDirectory("z3.zip", ".")
System.IO.Directory.Move("z3-4.6.0-x64-win","z3")
| _ -> ()
#r "z3/bin/Microsoft.Z3.dll"
open Microsoft.Z3
```
## Variables and transitions
A convience function defines a new variable for Z3- *makeVariable*- based on a name (string), and a time.

How different variables update is specified in the step function. The step function is given two times and defines new constraints, before adding them to the solver. According to the graph above, Input is constantly True or False, so the constraint *update'* specifies its state. The next state of A (at t') is set to the current state of Input (at t). B has a similar dependency on A. The output node is more complex- it is true in the next step if and only if A is true and B is false. These constraints are constructed using a "And" term (conjuction). Finally the constraints are added to the solver.
```
let makeVariable (ctx:Context) name time =
ctx.MkBoolConst(sprintf "%s-%d" name time)
let step (ctx:Context) (s:Solver) t t' =
//Update input
let input' = ctx.MkEq((makeVariable ctx "Input" t'),ctx.MkTrue())
//Update A
let a' = ctx.MkEq((makeVariable ctx "A" t'),(makeVariable ctx "Input" t))
//Update B
let b' = ctx.MkEq((makeVariable ctx "B" t'),(makeVariable ctx "A" t))
//Update Output
let output' = ctx.MkAnd( [|
ctx.MkImplies(ctx.MkEq((makeVariable ctx "A" t),(ctx.MkFalse())),ctx.MkEq((makeVariable ctx "Output" t'),ctx.MkFalse()))
ctx.MkImplies(ctx.MkAnd(ctx.MkEq((makeVariable ctx "A" t),ctx.MkTrue()),ctx.MkEq((makeVariable ctx "B" t),(ctx.MkFalse()))),ctx.MkEq((makeVariable ctx "Output" t'),ctx.MkTrue()))
ctx.MkImplies(ctx.MkAnd(ctx.MkEq((makeVariable ctx "A" t),ctx.MkTrue()),ctx.MkEq((makeVariable ctx "B" t),(ctx.MkTrue()))),ctx.MkEq((makeVariable ctx "Output" t'),ctx.MkFalse()))
|] )
s.Add(ctx.MkAnd([|input'; a'; b'; output'|]))
```
## Searching for stability- finding a single fixpoint
Once the transitions are defined we can start searching for the endpoints of the system. Firstly, we need to find a single fix point. If there isn't one, we can be sure that the model is unstable; however we would still need to find the cycle to be sure. To find a fix point we can specify a step where the time is the same; this effectively constrains the system to the set states that are self loops. The first answer is one fix point, but we need to know that this fix point is unique. After finding an initial solution we can then exclude this solution with a new constraint, defeined with the function *excludeState* and repeat the Check(). If this call is not satisfiable then we can be sure that there is no bifurcation in the system. It's worth noting that searching for fix points is relatively quick.
```
type result = Bifurcation | NoBifurcation | Cycle | Stable
let excludeState (ctx:Context) (s:Solver) t =
s.Add(ctx.MkNot(ctx.MkAnd(
[|
ctx.MkEq(s.Model.Eval(makeVariable ctx "Input" t),makeVariable ctx "Input" t)
ctx.MkEq(s.Model.Eval(makeVariable ctx "A" t),makeVariable ctx "A" t)
ctx.MkEq(s.Model.Eval(makeVariable ctx "B" t),makeVariable ctx "B" t)
ctx.MkEq(s.Model.Eval(makeVariable ctx "Output" t),makeVariable ctx "Output" t)
|]
)))
let findFixpoints _ =
let ctx = new Context()
let s = ctx.MkSolver()
step ctx s 0 0
match s.Check() with
| Status.SATISFIABLE -> printf "Found Fixpoint\n"
ignore(List.map (fun name -> printf "%s:\t%O\n" name (s.Model.Eval(makeVariable ctx name 0)) ) ["Input";"A";"B";"Output"])
excludeState ctx s 0
match s.Check() with
| Status.UNSATISFIABLE -> printf "Only a single fixpoint\n"; NoBifurcation
| Status.SATISFIABLE -> printf "Found bifurcation\n"; Bifurcation
| _ -> failwith "Unknown result from Z3"
| Status.UNSATISFIABLE -> printf "No fixpoints\n"; NoBifurcation
| _ -> failwith "Unknown result from fixpoint search"
```
## Searching for stability- finding a cycle
The next stage is to search for cycles. We need to show that there are no cycles in the system, up to the maximum bound of the system to know that the model is stable. There are 16 states in the system (2^4) so we can use that as the maximum bound (this would not necessarily hold in an asynchronous system). To search for cycles
* We use a loop to increment the number of steps from 0 up to the current bound
* We add a constraints that the states at time 0 and time 1 are not the same (i.e. the last states are not a fixpoint)
* We add a constraint that the initial state and the final state are the same
We can then run repeated checks up to the bound of the system. Once the bound is reached, we can be confident that there are no cycles.
```
let statesEqual (ctx:Context) t t' =
ctx.MkAnd(
[|
ctx.MkEq(makeVariable ctx "Input" t',makeVariable ctx "Input" t)
ctx.MkEq(makeVariable ctx "A" t',makeVariable ctx "A" t)
ctx.MkEq(makeVariable ctx "B" t',makeVariable ctx "B" t)
ctx.MkEq(makeVariable ctx "Output" t',makeVariable ctx "Output" t)
|]
)
let statesAreEqual ctx (s:Solver) t t' =
s.Add(statesEqual ctx t t')
let statesAreNotEqual (ctx:Context) (s:Solver) t t' =
s.Add(ctx.MkNot(statesEqual ctx t t'))
let findCycles bound =
let ctx = new Context()
let s = ctx.MkSolver()
printf "Searching for cycles at bound"
let rec core i bound =
printf "...%d" i;
step ctx s (i-1) i
s.Push()
//Need to assert that first state is not a fixpoint
statesAreNotEqual ctx s 0 1
statesAreEqual ctx s 0 i
match s.Check() with
| Status.SATISFIABLE -> printf "Found cycle of length %d\n" i; Cycle
| Status.UNSATISFIABLE -> s.Pop(); if i < bound then core (i+1) bound else printf "\n"; Stable
| _ -> failwith "Unknown result"
core 1 bound
```
## Main
Finally, run the functions!
Run the fast test for bifurcation first (so if you find it, you can avoid the slow cycle search).
```
let main _ =
match findFixpoints () with
| Bifurcation -> ()
| _ -> match findCycles 16 with
| Cycle -> ()
| Stable -> printf "Model is stable!\n"
| _ -> failwith "problem- error"
main ()
```
# Exercises
1. Modify the model so that the input is constantly high, and retest. Whats the result? Does it match with what you expect?
2. Modify *step* function to change the network from a negative feedforward loop to a negative feedback loop i.e. . Test its stability with high and low inputs; what do you find, and is it correct?
3. Model checking like this can be optimised by adding new tests or adding additional constraints. The cycle search is slow because it searches up to the boundary of the system. In this case its 16, but for more complex networks it can be intractably large. One optimisation that the BMA has is to test whether a simulation of a given length exists and finishing the loop early. Try add this to the cycle searching code.
4. If the system was *asynchronous*, which parts of the code would have to be kept and which parts would need to be replaced? Where possible, suggest how you would modify the functions.
5. Write an *asynchonous* update function and a function that finds a simulation of length 5 using it
| github_jupyter |
### <font color = "darkblue">Updates to Assignment</font>
#### If you were working on the older version:
* Please click on the "Coursera" icon in the top right to open up the folder directory.
* Navigate to the folder: Week 3/ Planar data classification with one hidden layer. You can see your prior work in version 6b: "Planar data classification with one hidden layer v6b.ipynb"
#### List of bug fixes and enhancements
* Clarifies that the classifier will learn to classify regions as either red or blue.
* compute_cost function fixes np.squeeze by casting it as a float.
* compute_cost instructions clarify the purpose of np.squeeze.
* compute_cost clarifies that "parameters" parameter is not needed, but is kept in the function definition until the auto-grader is also updated.
* nn_model removes extraction of parameter values, as the entire parameter dictionary is passed to the invoked functions.
# Planar data classification with one hidden layer
Welcome to your week 3 programming assignment. It's time to build your first neural network, which will have a hidden layer. You will see a big difference between this model and the one you implemented using logistic regression.
**You will learn how to:**
- Implement a 2-class classification neural network with a single hidden layer
- Use units with a non-linear activation function, such as tanh
- Compute the cross entropy loss
- Implement forward and backward propagation
## 1 - Packages ##
Let's first import all the packages that you will need during this assignment.
- [numpy](https://www.numpy.org/) is the fundamental package for scientific computing with Python.
- [sklearn](http://scikit-learn.org/stable/) provides simple and efficient tools for data mining and data analysis.
- [matplotlib](http://matplotlib.org) is a library for plotting graphs in Python.
- testCases provides some test examples to assess the correctness of your functions
- planar_utils provide various useful functions used in this assignment
```
# Package imports
import numpy as np
import matplotlib.pyplot as plt
from testCases_v2 import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
%matplotlib inline
np.random.seed(1) # set a seed so that the results are consistent
```
## 2 - Dataset ##
First, let's get the dataset you will work on. The following code will load a "flower" 2-class dataset into variables `X` and `Y`.
```
X, Y = load_planar_dataset()
```
Visualize the dataset using matplotlib. The data looks like a "flower" with some red (label y=0) and some blue (y=1) points. Your goal is to build a model to fit this data. In other words, we want the classifier to define regions as either red or blue.
```
# Visualize the data:
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);
```
You have:
- a numpy-array (matrix) X that contains your features (x1, x2)
- a numpy-array (vector) Y that contains your labels (red:0, blue:1).
Lets first get a better sense of what our data is like.
**Exercise**: How many training examples do you have? In addition, what is the `shape` of the variables `X` and `Y`?
**Hint**: How do you get the shape of a numpy array? [(help)](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html)
```
### START CODE HERE ### (≈ 3 lines of code)
shape_X = X.shape
shape_Y = Y.shape
m = X.shape[1] # training set size
### END CODE HERE ###
print ('The shape of X is: ' + str(shape_X))
print ('The shape of Y is: ' + str(shape_Y))
print ('I have m = %d training examples!' % (m))
```
**Expected Output**:
<table style="width:20%">
<tr>
<td>**shape of X**</td>
<td> (2, 400) </td>
</tr>
<tr>
<td>**shape of Y**</td>
<td>(1, 400) </td>
</tr>
<tr>
<td>**m**</td>
<td> 400 </td>
</tr>
</table>
## 3 - Simple Logistic Regression
Before building a full neural network, lets first see how logistic regression performs on this problem. You can use sklearn's built-in functions to do that. Run the code below to train a logistic regression classifier on the dataset.
```
# Train the logistic regression classifier
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T);
```
You can now plot the decision boundary of these models. Run the code below.
```
# Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")
# Print accuracy
LR_predictions = clf.predict(X.T)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
'% ' + "(percentage of correctly labelled datapoints)")
```
**Expected Output**:
<table style="width:20%">
<tr>
<td>**Accuracy**</td>
<td> 47% </td>
</tr>
</table>
**Interpretation**: The dataset is not linearly separable, so logistic regression doesn't perform well. Hopefully a neural network will do better. Let's try this now!
## 4 - Neural Network model
Logistic regression did not work well on the "flower dataset". You are going to train a Neural Network with a single hidden layer.
**Here is our model**:
<img src="images/classification_kiank.png" style="width:600px;height:300px;">
**Mathematically**:
For one example $x^{(i)}$:
$$z^{[1] (i)} = W^{[1]} x^{(i)} + b^{[1]}\tag{1}$$
$$a^{[1] (i)} = \tanh(z^{[1] (i)})\tag{2}$$
$$z^{[2] (i)} = W^{[2]} a^{[1] (i)} + b^{[2]}\tag{3}$$
$$\hat{y}^{(i)} = a^{[2] (i)} = \sigma(z^{ [2] (i)})\tag{4}$$
$$y^{(i)}_{prediction} = \begin{cases} 1 & \mbox{if } a^{[2](i)} > 0.5 \\ 0 & \mbox{otherwise } \end{cases}\tag{5}$$
Given the predictions on all the examples, you can also compute the cost $J$ as follows:
$$J = - \frac{1}{m} \sum\limits_{i = 0}^{m} \large\left(\small y^{(i)}\log\left(a^{[2] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[2] (i)}\right) \large \right) \small \tag{6}$$
**Reminder**: The general methodology to build a Neural Network is to:
1. Define the neural network structure ( # of input units, # of hidden units, etc).
2. Initialize the model's parameters
3. Loop:
- Implement forward propagation
- Compute loss
- Implement backward propagation to get the gradients
- Update parameters (gradient descent)
You often build helper functions to compute steps 1-3 and then merge them into one function we call `nn_model()`. Once you've built `nn_model()` and learnt the right parameters, you can make predictions on new data.
### 4.1 - Defining the neural network structure ####
**Exercise**: Define three variables:
- n_x: the size of the input layer
- n_h: the size of the hidden layer (set this to 4)
- n_y: the size of the output layer
**Hint**: Use shapes of X and Y to find n_x and n_y. Also, hard code the hidden layer size to be 4.
```
# GRADED FUNCTION: layer_sizes
def layer_sizes(X, Y):
"""
Arguments:
X -- input dataset of shape (input size, number of examples)
Y -- labels of shape (output size, number of examples)
Returns:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size of the output layer
"""
### START CODE HERE ### (≈ 3 lines of code)
n_x = X.shape[0] # size of input layer
n_h = 4
n_y = Y.shape[0] # size of output layer
### END CODE HERE ###
return (n_x, n_h, n_y)
X_assess, Y_assess = layer_sizes_test_case()
(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)
print("The size of the input layer is: n_x = " + str(n_x))
print("The size of the hidden layer is: n_h = " + str(n_h))
print("The size of the output layer is: n_y = " + str(n_y))
```
**Expected Output** (these are not the sizes you will use for your network, they are just used to assess the function you've just coded).
<table style="width:20%">
<tr>
<td>**n_x**</td>
<td> 5 </td>
</tr>
<tr>
<td>**n_h**</td>
<td> 4 </td>
</tr>
<tr>
<td>**n_y**</td>
<td> 2 </td>
</tr>
</table>
### 4.2 - Initialize the model's parameters ####
**Exercise**: Implement the function `initialize_parameters()`.
**Instructions**:
- Make sure your parameters' sizes are right. Refer to the neural network figure above if needed.
- You will initialize the weights matrices with random values.
- Use: `np.random.randn(a,b) * 0.01` to randomly initialize a matrix of shape (a,b).
- You will initialize the bias vectors as zeros.
- Use: `np.zeros((a,b))` to initialize a matrix of shape (a,b) with zeros.
```
# GRADED FUNCTION: initialize_parameters
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
params -- python dictionary containing your parameters:
W1 -- weight matrix of shape (n_h, n_x)
b1 -- bias vector of shape (n_h, 1)
W2 -- weight matrix of shape (n_y, n_h)
b2 -- bias vector of shape (n_y, 1)
"""
np.random.seed(2) # we set up a seed so that your output matches ours although the initialization is random.
### START CODE HERE ### (≈ 4 lines of code)
W1 = np.random.randn(n_h,n_x)*0.01
b1 = np.zeros((n_h,1))
W2 = np.random.randn(n_y,n_h)*0.01
b2 = np.zeros((n_y,1))
### END CODE HERE ###
assert (W1.shape == (n_h, n_x))
assert (b1.shape == (n_h, 1))
assert (W2.shape == (n_y, n_h))
assert (b2.shape == (n_y, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
n_x, n_h, n_y = initialize_parameters_test_case()
parameters = initialize_parameters(n_x, n_h, n_y)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
```
**Expected Output**:
<table style="width:90%">
<tr>
<td>**W1**</td>
<td> [[-0.00416758 -0.00056267]
[-0.02136196 0.01640271]
[-0.01793436 -0.00841747]
[ 0.00502881 -0.01245288]] </td>
</tr>
<tr>
<td>**b1**</td>
<td> [[ 0.]
[ 0.]
[ 0.]
[ 0.]] </td>
</tr>
<tr>
<td>**W2**</td>
<td> [[-0.01057952 -0.00909008 0.00551454 0.02292208]]</td>
</tr>
<tr>
<td>**b2**</td>
<td> [[ 0.]] </td>
</tr>
</table>
### 4.3 - The Loop ####
**Question**: Implement `forward_propagation()`.
**Instructions**:
- Look above at the mathematical representation of your classifier.
- You can use the function `sigmoid()`. It is built-in (imported) in the notebook.
- You can use the function `np.tanh()`. It is part of the numpy library.
- The steps you have to implement are:
1. Retrieve each parameter from the dictionary "parameters" (which is the output of `initialize_parameters()`) by using `parameters[".."]`.
2. Implement Forward Propagation. Compute $Z^{[1]}, A^{[1]}, Z^{[2]}$ and $A^{[2]}$ (the vector of all your predictions on all the examples in the training set).
- Values needed in the backpropagation are stored in "`cache`". The `cache` will be given as an input to the backpropagation function.
```
# GRADED FUNCTION: forward_propagation
def forward_propagation(X, parameters):
"""
Argument:
X -- input data of size (n_x, m)
parameters -- python dictionary containing your parameters (output of initialization function)
Returns:
A2 -- The sigmoid output of the second activation
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"
"""
# Retrieve each parameter from the dictionary "parameters"
### START CODE HERE ### (≈ 4 lines of code)
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
### END CODE HERE ###
# Implement Forward Propagation to calculate A2 (probabilities)
### START CODE HERE ### (≈ 4 lines of code)
Z1 = np.dot(W1,X) + b1
A1 = np.tanh(Z1)
Z2 = np.dot(W2,A1) + b2
A2 = sigmoid(Z2)
### END CODE HERE ###
assert(A2.shape == (1, X.shape[1]))
cache = {"Z1": Z1,
"A1": A1,
"Z2": Z2,
"A2": A2}
return A2, cache
X_assess, parameters = forward_propagation_test_case()
A2, cache = forward_propagation(X_assess, parameters)
# Note: we use the mean here just to make sure that your output matches ours.
print(np.mean(cache['Z1']) ,np.mean(cache['A1']),np.mean(cache['Z2']),np.mean(cache['A2']))
```
**Expected Output**:
<table style="width:50%">
<tr>
<td> 0.262818640198 0.091999045227 -1.30766601287 0.212877681719 </td>
</tr>
</table>
Now that you have computed $A^{[2]}$ (in the Python variable "`A2`"), which contains $a^{[2](i)}$ for every example, you can compute the cost function as follows:
$$J = - \frac{1}{m} \sum\limits_{i = 1}^{m} \large{(} \small y^{(i)}\log\left(a^{[2] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[2] (i)}\right) \large{)} \small\tag{13}$$
**Exercise**: Implement `compute_cost()` to compute the value of the cost $J$.
**Instructions**:
- There are many ways to implement the cross-entropy loss. To help you, we give you how we would have implemented
$- \sum\limits_{i=0}^{m} y^{(i)}\log(a^{[2](i)})$:
```python
logprobs = np.multiply(np.log(A2),Y)
cost = - np.sum(logprobs) # no need to use a for loop!
```
(you can use either `np.multiply()` and then `np.sum()` or directly `np.dot()`).
Note that if you use `np.multiply` followed by `np.sum` the end result will be a type `float`, whereas if you use `np.dot`, the result will be a 2D numpy array. We can use `np.squeeze()` to remove redundant dimensions (in the case of single float, this will be reduced to a zero-dimension array). We can cast the array as a type `float` using `float()`.
```
# GRADED FUNCTION: compute_cost
def compute_cost(A2, Y, parameters):
"""
Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
parameters -- python dictionary containing your parameters W1, b1, W2 and b2
[Note that the parameters argument is not used in this function,
but the auto-grader currently expects this parameter.
Future version of this notebook will fix both the notebook
and the auto-grader so that `parameters` is not needed.
For now, please include `parameters` in the function signature,
and also when invoking this function.]
Returns:
cost -- cross-entropy cost given equation (13)
"""
m = Y.shape[1] # number of example
# Compute the cross-entropy cost
### START CODE HERE ### (≈ 2 lines of code)
logprobs = np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2))
cost = - np.sum(logprobs) / m
### END CODE HERE ###
cost = float(np.squeeze(cost)) # makes sure cost is the dimension we expect.
# E.g., turns [[17]] into 17
assert(isinstance(cost, float))
return cost
A2, Y_assess, parameters = compute_cost_test_case()
print("cost = " + str(compute_cost(A2, Y_assess, parameters)))
```
**Expected Output**:
<table style="width:20%">
<tr>
<td>**cost**</td>
<td> 0.693058761... </td>
</tr>
</table>
Using the cache computed during forward propagation, you can now implement backward propagation.
**Question**: Implement the function `backward_propagation()`.
**Instructions**:
Backpropagation is usually the hardest (most mathematical) part in deep learning. To help you, here again is the slide from the lecture on backpropagation. You'll want to use the six equations on the right of this slide, since you are building a vectorized implementation.
<img src="images/grad_summary.png" style="width:600px;height:300px;">
<!--
$\frac{\partial \mathcal{J} }{ \partial z_{2}^{(i)} } = \frac{1}{m} (a^{[2](i)} - y^{(i)})$
$\frac{\partial \mathcal{J} }{ \partial W_2 } = \frac{\partial \mathcal{J} }{ \partial z_{2}^{(i)} } a^{[1] (i) T} $
$\frac{\partial \mathcal{J} }{ \partial b_2 } = \sum_i{\frac{\partial \mathcal{J} }{ \partial z_{2}^{(i)}}}$
$\frac{\partial \mathcal{J} }{ \partial z_{1}^{(i)} } = W_2^T \frac{\partial \mathcal{J} }{ \partial z_{2}^{(i)} } * ( 1 - a^{[1] (i) 2}) $
$\frac{\partial \mathcal{J} }{ \partial W_1 } = \frac{\partial \mathcal{J} }{ \partial z_{1}^{(i)} } X^T $
$\frac{\partial \mathcal{J} _i }{ \partial b_1 } = \sum_i{\frac{\partial \mathcal{J} }{ \partial z_{1}^{(i)}}}$
- Note that $*$ denotes elementwise multiplication.
- The notation you will use is common in deep learning coding:
- dW1 = $\frac{\partial \mathcal{J} }{ \partial W_1 }$
- db1 = $\frac{\partial \mathcal{J} }{ \partial b_1 }$
- dW2 = $\frac{\partial \mathcal{J} }{ \partial W_2 }$
- db2 = $\frac{\partial \mathcal{J} }{ \partial b_2 }$
!-->
- Tips:
- To compute dZ1 you'll need to compute $g^{[1]'}(Z^{[1]})$. Since $g^{[1]}(.)$ is the tanh activation function, if $a = g^{[1]}(z)$ then $g^{[1]'}(z) = 1-a^2$. So you can compute
$g^{[1]'}(Z^{[1]})$ using `(1 - np.power(A1, 2))`.
```
# GRADED FUNCTION: backward_propagation
def backward_propagation(parameters, cache, X, Y):
"""
Implement the backward propagation using the instructions above.
Arguments:
parameters -- python dictionary containing our parameters
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
X -- input data of shape (2, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
Returns:
grads -- python dictionary containing your gradients with respect to different parameters
"""
m = X.shape[1]
# First, retrieve W1 and W2 from the dictionary "parameters".
### START CODE HERE ### (≈ 2 lines of code)
W1 = parameters["W1"]
W2 = parameters["W2"]
### END CODE HERE ###
# Retrieve also A1 and A2 from dictionary "cache".
### START CODE HERE ### (≈ 2 lines of code)
A1 = cache["A1"]
A2 = cache["A2"]
### END CODE HERE ###
# Backward propagation: calculate dW1, db1, dW2, db2.
### START CODE HERE ### (≈ 6 lines of code, corresponding to 6 equations on slide above)
dZ2 = A2-Y
dW2 = (1/m)*np.dot(dZ2,A1.T)
db2 = (1/m)*np.sum(dZ2,axis = 1,keepdims = True)
dZ1 = np.dot(W2.T,dZ2)*(1 - np.power(A1, 2))
dW1 = (1/m)*np.dot(dZ1,X.T)
db1 = (1/m)*np.sum(dZ1,axis = 1,keepdims = True)
### END CODE HERE ###
grads = {"dW1": dW1,
"db1": db1,
"dW2": dW2,
"db2": db2}
return grads
parameters, cache, X_assess, Y_assess = backward_propagation_test_case()
grads = backward_propagation(parameters, cache, X_assess, Y_assess)
print ("dW1 = "+ str(grads["dW1"]))
print ("db1 = "+ str(grads["db1"]))
print ("dW2 = "+ str(grads["dW2"]))
print ("db2 = "+ str(grads["db2"]))
```
**Expected output**:
<table style="width:80%">
<tr>
<td>**dW1**</td>
<td> [[ 0.00301023 -0.00747267]
[ 0.00257968 -0.00641288]
[-0.00156892 0.003893 ]
[-0.00652037 0.01618243]] </td>
</tr>
<tr>
<td>**db1**</td>
<td> [[ 0.00176201]
[ 0.00150995]
[-0.00091736]
[-0.00381422]] </td>
</tr>
<tr>
<td>**dW2**</td>
<td> [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]] </td>
</tr>
<tr>
<td>**db2**</td>
<td> [[-0.16655712]] </td>
</tr>
</table>
**Question**: Implement the update rule. Use gradient descent. You have to use (dW1, db1, dW2, db2) in order to update (W1, b1, W2, b2).
**General gradient descent rule**: $ \theta = \theta - \alpha \frac{\partial J }{ \partial \theta }$ where $\alpha$ is the learning rate and $\theta$ represents a parameter.
**Illustration**: The gradient descent algorithm with a good learning rate (converging) and a bad learning rate (diverging). Images courtesy of Adam Harley.
<img src="images/sgd.gif" style="width:400;height:400;"> <img src="images/sgd_bad.gif" style="width:400;height:400;">
```
# GRADED FUNCTION: update_parameters
def update_parameters(parameters, grads, learning_rate = 1.2):
"""
Updates parameters using the gradient descent update rule given above
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients
Returns:
parameters -- python dictionary containing your updated parameters
"""
# Retrieve each parameter from the dictionary "parameters"
### START CODE HERE ### (≈ 4 lines of code)
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
### END CODE HERE ###
# Retrieve each gradient from the dictionary "grads"
### START CODE HERE ### (≈ 4 lines of code)
dW1 = grads["dW1"]
db1 = grads["db1"]
dW2 = grads["dW2"]
db2 = grads["db2"]
## END CODE HERE ###
# Update rule for each parameter
### START CODE HERE ### (≈ 4 lines of code)
W1 = W1 - learning_rate*dW1
b1 = b1 - learning_rate*db1
W2 = W2 - learning_rate*dW2
b2 = b2 - learning_rate*db2
### END CODE HERE ###
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
parameters, grads = update_parameters_test_case()
parameters = update_parameters(parameters, grads)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
```
**Expected Output**:
<table style="width:80%">
<tr>
<td>**W1**</td>
<td> [[-0.00643025 0.01936718]
[-0.02410458 0.03978052]
[-0.01653973 -0.02096177]
[ 0.01046864 -0.05990141]]</td>
</tr>
<tr>
<td>**b1**</td>
<td> [[ -1.02420756e-06]
[ 1.27373948e-05]
[ 8.32996807e-07]
[ -3.20136836e-06]]</td>
</tr>
<tr>
<td>**W2**</td>
<td> [[-0.01041081 -0.04463285 0.01758031 0.04747113]] </td>
</tr>
<tr>
<td>**b2**</td>
<td> [[ 0.00010457]] </td>
</tr>
</table>
### 4.4 - Integrate parts 4.1, 4.2 and 4.3 in nn_model() ####
**Question**: Build your neural network model in `nn_model()`.
**Instructions**: The neural network model has to use the previous functions in the right order.
```
# GRADED FUNCTION: nn_model
def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):
"""
Arguments:
X -- dataset of shape (2, number of examples)
Y -- labels of shape (1, number of examples)
n_h -- size of the hidden layer
num_iterations -- Number of iterations in gradient descent loop
print_cost -- if True, print the cost every 1000 iterations
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
np.random.seed(3)
n_x = layer_sizes(X, Y)[0]
n_y = layer_sizes(X, Y)[2]
# Initialize parameters
### START CODE HERE ### (≈ 1 line of code)
parameters = initialize_parameters(n_x, n_h, n_y)
### END CODE HERE ###
# Loop (gradient descent)
for i in range(0, num_iterations):
### START CODE HERE ### (≈ 4 lines of code)
# Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache".
A2, cache = forward_propagation(X,parameters)
# Cost function. Inputs: "A2, Y, parameters". Outputs: "cost".
cost = compute_cost(A2, Y, parameters)
# Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads".
grads = backward_propagation(parameters, cache, X, Y)
# Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters".
parameters = update_parameters(parameters, grads)
### END CODE HERE ###
# Print the cost every 1000 iterations
if print_cost and i % 1000 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
return parameters
X_assess, Y_assess = nn_model_test_case()
parameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=True)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
```
**Expected Output**:
<table style="width:90%">
<tr>
<td>
**cost after iteration 0**
</td>
<td>
0.692739
</td>
</tr>
<tr>
<td>
<center> $\vdots$ </center>
</td>
<td>
<center> $\vdots$ </center>
</td>
</tr>
<tr>
<td>**W1**</td>
<td> [[-0.65848169 1.21866811]
[-0.76204273 1.39377573]
[ 0.5792005 -1.10397703]
[ 0.76773391 -1.41477129]]</td>
</tr>
<tr>
<td>**b1**</td>
<td> [[ 0.287592 ]
[ 0.3511264 ]
[-0.2431246 ]
[-0.35772805]] </td>
</tr>
<tr>
<td>**W2**</td>
<td> [[-2.45566237 -3.27042274 2.00784958 3.36773273]] </td>
</tr>
<tr>
<td>**b2**</td>
<td> [[ 0.20459656]] </td>
</tr>
</table>
### 4.5 Predictions
**Question**: Use your model to predict by building predict().
Use forward propagation to predict results.
**Reminder**: predictions = $y_{prediction} = \mathbb 1 \text{{activation > 0.5}} = \begin{cases}
1 & \text{if}\ activation > 0.5 \\
0 & \text{otherwise}
\end{cases}$
As an example, if you would like to set the entries of a matrix X to 0 and 1 based on a threshold you would do: ```X_new = (X > threshold)```
```
# GRADED FUNCTION: predict
def predict(parameters, X):
"""
Using the learned parameters, predicts a class for each example in X
Arguments:
parameters -- python dictionary containing your parameters
X -- input data of size (n_x, m)
Returns
predictions -- vector of predictions of our model (red: 0 / blue: 1)
"""
# Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold.
### START CODE HERE ### (≈ 2 lines of code)
A2, cache = forward_propagation(X,parameters)
predictions = np.array([1 if x > 0.5 else 0 for x in A2[0]])
### END CODE HERE ###
return predictions
parameters, X_assess = predict_test_case()
predictions = predict(parameters, X_assess)
print("predictions mean = " + str(np.mean(predictions)))
```
**Expected Output**:
<table style="width:40%">
<tr>
<td>**predictions mean**</td>
<td> 0.666666666667 </td>
</tr>
</table>
It is time to run the model and see how it performs on a planar dataset. Run the following code to test your model with a single hidden layer of $n_h$ hidden units.
```
# Build a model with a n_h-dimensional hidden layer
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)
# Plot the decision boundary
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
plt.title("Decision Boundary for hidden layer size " + str(4))
```
**Expected Output**:
<table style="width:40%">
<tr>
<td>**Cost after iteration 9000**</td>
<td> 0.218607 </td>
</tr>
</table>
```
# Print accuracy
predictions = predict(parameters, X)
print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')
```
**Expected Output**:
<table style="width:15%">
<tr>
<td>**Accuracy**</td>
<td> 90% </td>
</tr>
</table>
Accuracy is really high compared to Logistic Regression. The model has learnt the leaf patterns of the flower! Neural networks are able to learn even highly non-linear decision boundaries, unlike logistic regression.
Now, let's try out several hidden layer sizes.
### 4.6 - Tuning hidden layer size (optional/ungraded exercise) ###
Run the following code. It may take 1-2 minutes. You will observe different behaviors of the model for various hidden layer sizes.
```
# This may take about 2 minutes to run
plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]
for i, n_h in enumerate(hidden_layer_sizes):
plt.subplot(5, 2, i+1)
plt.title('Hidden Layer of size %d' % n_h)
parameters = nn_model(X, Y, n_h, num_iterations = 5000)
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
predictions = predict(parameters, X)
accuracy = float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100)
print ("Accuracy for {} hidden units: {} %".format(n_h, accuracy))
```
**Interpretation**:
- The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models overfit the data.
- The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits the data well without also incurring noticeable overfitting.
- You will also learn later about regularization, which lets you use very large models (such as n_h = 50) without much overfitting.
**Optional questions**:
**Note**: Remember to submit the assignment by clicking the blue "Submit Assignment" button at the upper-right.
Some optional/ungraded questions that you can explore if you wish:
- What happens when you change the tanh activation for a sigmoid activation or a ReLU activation?
- Play with the learning_rate. What happens?
- What if we change the dataset? (See part 5 below!)
<font color='blue'>
**You've learnt to:**
- Build a complete neural network with a hidden layer
- Make a good use of a non-linear unit
- Implemented forward propagation and backpropagation, and trained a neural network
- See the impact of varying the hidden layer size, including overfitting.
Nice work!
## 5) Performance on other datasets
If you want, you can rerun the whole notebook (minus the dataset part) for each of the following datasets.
```
# Datasets
noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()
datasets = {"noisy_circles": noisy_circles,
"noisy_moons": noisy_moons,
"blobs": blobs,
"gaussian_quantiles": gaussian_quantiles}
### START CODE HERE ### (choose your dataset)
dataset = "noisy_moons"
### END CODE HERE ###
X, Y = datasets[dataset]
X, Y = X.T, Y.reshape(1, Y.shape[0])
# make blobs binary
if dataset == "blobs":
Y = Y%2
# Visualize the data
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);
```
Congrats on finishing this Programming Assignment!
Reference:
- http://scs.ryerson.ca/~aharley/neural-networks/
- http://cs231n.github.io/neural-networks-case-study/
| github_jupyter |
```
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from scipy import optimize
# Input data files are available in the read-only "../input/" directory
import matplotlib.pyplot as plt
import os
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigder(x):
return sigmoid(x) * (1-sigmoid(x))
# we will be using a single layered neuran network for this implementation
def nnCost(nn_params,
input_layer_size,
hidden_layer_size,
num_labels,
X,y,lambda_=0):
# with the formula we have fabricated we can get the two weights of the neural network which
# we can write as theta1 and theta 2 which are concatenated in the nnparams
# thetai = nnparams[len(thetai-1): hiddenlayeri * (hiddenlayer(i-1) + 1) + len(theta(i-1))]
Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)],
(hidden_layer_size, (input_layer_size + 1)))
Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):],
(num_labels, (hidden_layer_size + 1)))
# Setup some useful variables
m = y.size
# we need to get the following parameters as the result of this function
J = 0
Theta1_grad = np.zeros(Theta1.shape)
Theta2_grad = np.zeros(Theta2.shape)
a1 = np.concatenate([np.ones((m, 1)), X], axis=1)
a2 = sigmoid(a1.dot(Theta1.T))
a2 = np.concatenate([np.ones((a2.shape[0], 1)), a2], axis=1)
a3 = sigmoid(a2.dot(Theta2.T))
y_matrix = y.reshape(-1)
y_matrix = np.eye(num_labels)[y_matrix]
temp1 = Theta1
temp2 = Theta2
# Add regularization term
reg_term = (lambda_ / (2 * m)) * (np.sum(np.square(temp1[:, 1:])) + np.sum(np.square(temp2[:, 1:])))
J = (-1 / m) * np.sum((np.log(a3) * y_matrix) + np.log(1 - a3) * (1 - y_matrix)) + reg_term
# Backpropogation
delta_3 = a3 - y_matrix
delta_2 = delta_3.dot(Theta2)[:, 1:] * sigder(a1.dot(Theta1.T))
Delta1 = delta_2.T.dot(a1)
Delta2 = delta_3.T.dot(a2)
# Add regularization to gradient
Theta1_grad = (1 / m) * Delta1
Theta1_grad[:, 1:] = Theta1_grad[:, 1:] + (lambda_ / m) * Theta1[:, 1:]
Theta2_grad = (1 / m) * Delta2
Theta2_grad[:, 1:] = Theta2_grad[:, 1:] + (lambda_ / m) * Theta2[:, 1:]
grad = np.concatenate([Theta1_grad.ravel(), Theta2_grad.ravel()])
return J, grad
#lets define our input now
trainfile = 'train.csv'
traindata = pd.read_csv(trainfile).to_numpy()
hidden_layer_size = 49
num_labels = 10
input_layer_size = traindata[:,1:].shape[1]
X,y = traindata[:,1:],traindata[:,0]
m = y.size
#lets show a random data from out traning set
rand = np.random.randint(0,m)
plt.imshow(255- X[rand].reshape(28,28) , cmap='gray')
y[rand]
#now we get the randomized weights for the neural network
def randweightgenerator(L_in,L_out,epsilon = 0.12):
W = np.zeros((L_out, 1 + L_in))
W = np.random.rand(L_out, 1 + L_in) * 2 * epsilon - epsilon
return W
theta1 = randweightgenerator(input_layer_size, hidden_layer_size)
theta2 = randweightgenerator(hidden_layer_size, num_labels)
#now we set nn_params as a list of theta 1 and theta 2
nn_params = np.concatenate([theta1.ravel(), theta2.ravel()], axis=0)
#now we can use the optimizer from the scipy library to minimize our weights
# the other way to optimize this would be to use the gradients and do gradient descent
options = {'maxiter':1000}
lambda_ = 3
#now we make a temp cost function
costfn = lambda p :nnCost(p,input_layer_size,hidden_layer_size,num_labels,X,y,lambda_)
res = optimize.minimize(costfn,nn_params,jac=True ,method="TNC",options=options)
finalnnparams = res.x
j,_ = nnCost(finalnnparams,input_layer_size,hidden_layer_size,num_labels,X,y,lambda_)
print('The final cost after traning is : ',j)
# now lets define a fucntion which will use the given weights and predict the digits
def predict(nn_params,X,input_layer_size):
Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)],
(hidden_layer_size, (input_layer_size + 1)))
Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):],
(num_labels, (hidden_layer_size + 1)))
m = X.shape[0]
a1 = np.concatenate([np.ones((m, 1)), X], axis=1)
a2 = sigmoid(a1.dot(Theta1.T))
a2 = np.concatenate([np.ones((a2.shape[0], 1)), a2], axis=1)
a3 = sigmoid(a2.dot(Theta2.T))
# now lets get the index of maximum valued probability from p
p = np.argmax(a3, axis = 1)
return p
#load the testing data
testfile = 'test.csv'
testdata = pd.read_csv(testfile).to_numpy()
X_test = testdata
input_layer_size = testdata.shape[1]
outputs = predict(finalnnparams,X_test,input_layer_size)
finalres = outputs.tolist()
#submission part
df = pd.DataFrame(finalres)
df= df.rename(columns={0:'Label'})
df['ImageId'] = [i+1 for i in range(outputs.size)]
df.set_index('ImageId',inplace=True)
df.to_csv('submit.csv')
#now lets see some predictions
# visualization of the predictions
rand = np.random.randint(0,28000)
plt.imshow(255- X_test[rand].reshape(28,28) , cmap='gray')
outputs[rand]
```
| github_jupyter |
```
from gridworld import *
% matplotlib inline
# create the gridworld as a specific MDP
gridworld=GridMDP([[-0.04,-0.04,-0.04,1],[-0.04,None, -0.04, -1], [-0.04, -0.04, -0.04, -0.04]], terminals=[(3,2), (3,1)], gamma=1.)
example_pi = {(0,0): (0,1), (0,1): (0,1), (0,2): (1,0), (1,0): (1,0), (1,2): (1,0), (2,0): (0,1), (2,1): (0,1), (2,2): (1,0), (3,0):(-1,0), (3,1): None, (3,2):None}
example_q = { ((0,0),(-1,0)): 0.1,((0,0),(1,0)): 0.4,((0,0),(0,1)): 0.3,((0,0),(0,-1)): 0.2,
((0,1),(-1,0)): 0.0,((0,1),(1,0)): 0.2,((0,1),(0,1)): 0.5,((0,1),(0,-1)): 0.1,
((0,2),(-1,0)): 0.1,((0,2),(1,0)): 0.6,((0,2),(0,1)): 0.1,((0,2),(0,-1)): 0.0,
((1,0),(-1,0)): 0.4,((1,0),(1,0)): 0.2,((1,0),(0,1)): 0.1,((1,0),(0,-1)): 0.2,
((1,2),(-1,0)): 0.2,((1,2),(1,0)): 0.7,((1,2),(0,1)): 0.4,((1,2),(0,-1)): 0.3,
((2,0),(-1,0)): 0.3,((2,0),(1,0)): -0.2,((2,0),(0,1)): 0.3,((2,0),(0,-1)): 0.1,
((2,1),(-1,0)): 0.1,((2,1),(1,0)): -0.4,((2,1),(0,1)): 0.3,((2,1),(0,-1)): -0.1,
((2,2),(-1,0)): 0.3,((2,2),(1,0)): 0.8,((2,2),(0,1)): 0.3,((2,2),(0,-1)): 0.3,
((3,0),(-1,0)): 0.2,((3,0),(1,0)): -0.3,((3,0),(0,1)): -0.6,((3,0),(0,-1)): 0.2,
((3,1), None): -0.8, ((3,2),None):0.9}
"""
1) Complete the function passive_td, which implements temporal-
difference learning for fixed policies. The function takes as input a
policy, the MDP and returns as output the value function.
"""
def passive_td(pi, mdp, alpha = 0.05, n_trials = 500):
V = dict([(s, 0) for s in mdp.states]) # initialize value function
R, gamma = mdp.R, mdp.gamma
for i in range(n_trials):
state = (0,0)
while True:
newstate = mdp.new_state(state, pi[state])
raise NotImplementedError # implement TD update here
if newstate in mdp.terminals:
raise NotImplementedError # final TD update
break
state = newstate
return V
V=passive_td(example_pi, gridworld)
gridworld.v_plot(V)
"""
2) Implement Q-learning in the function below and complete the function best_policy_q which
computes the best policy given a q-function. Compare the q-function you get with the q-function
computed by value_iteration_q.
"""
""" function argmax is needed for choosing the optimal action """
def argmax(seq, fn):
best = seq[0]; best_score = fn(best)
for x in seq:
x_score = fn(x)
if x_score > best_score:
best, best_score = x, x_score
return best
def q_learning(mdp, alpha = 0.1, n_trials=500):
# initialize Q
Q=dict([ ((s,a),0) for s in mdp.states for a in mdp.actions(s)])
R, gamma = mdp.R, mdp.gamma
for i in range(n_trials):
state = (0,0)
while True:
raise NotImplementedError # implement action selection, state update and TD update
if newstate in mdp.terminals:
Q[newstate, None] = Q[newstate, None] + alpha*( R(newstate) -Q[newstate, None])
break
state = newstate
return Q
def best_policy_q(mdp, Q):
"""Given an MDP and a q function, determine the best policy,
as a mapping from state to action. """
pi = {}
raise NotImplementedError # assign optimal policy by looping through states
return pi
def value_iteration_q(mdp, epsilon=0.0001):
"Computing the q-function by value iteration. This assumes the transition model is known"
Q1=dict([ ((s,a),0) for s in mdp.states for a in mdp.actions(s)]) # initialize value function
R, T, gamma = mdp.R, mdp.T, mdp.gamma
while True:
Q = Q1.copy()
delta = 0
for s in mdp.states:
for a in mdp.actions(s):
Q1[s,a] = R(s) + gamma * sum([p * max([Q[s1,a1] for a1 in mdp.actions(s1)]) for (p, s1) in T(s, a)])
delta = max(delta, abs(Q1[s,a] - Q[s,a]))
if delta < epsilon:
return Q
Q = q_learning(gridworld)
Qval = value_iteration_q(gridworld)
gridworld.q_plot(Q)
gridworld.q_plot(Qval)
"""
3) Modify the function Q-learning so that it implements an epsilon-greedy agent.
"""
def epsilon_q_learning(mdp, epsilon, alpha = 0.1, n_trials=500):
# initialize Q
Q=dict([ ((s,a),0) for s in mdp.states for a in mdp.actions(s)])
R, gamma = mdp.R, mdp.gamma
for i in range(n_trials):
raise NotImplementedError # implement the epsilon-greedy q-learner
# use the function random.choice(mdp.actions(state)) for random action selection
return Q
Qeps = epsilon_q_learning(gridworld, 0.5)
gridworld.q_plot(Qeps)
```
| github_jupyter |
This notebook uses [mvncall](https://mathgen.stats.ox.ac.uk/genetics_software/mvncall/mvncall.html) to phase two multiallelic SNPs within VGSC and to add back in the insecticide resistance linked N1570Y SNP filtered out of the PASS callset.
```
%run setup.ipynb
```
## install mvncall
- mvncall depends on a couple of boost libraries, I installed these first using "sudo apt-get install libboost-dev"
```
%%bash --err install_err --out install_out
# This script downloads and installs mvncall. We won't include this in
# the standard install.sh script as this is not something we want to do
# as part of continuous integration, it is only needed for this data
# generation task.
set -xeo pipefail
cd ../dependencies
if [ ! -f mvncall.installed ]; then
echo installing mvncall
# clean up
rm -rvf mvncall*
# download and unpack
wget https://mathgen.stats.ox.ac.uk/genetics_software/mvncall/mvncall_v1.0_x86_64_dynamic.tgz
tar zxvf mvncall_v1.0_x86_64_dynamic.tgz
# trick mnvcall into finding boost libraries - their names aren't what mvncall expects
locate libboost_iostreams | xargs -I '{}' ln -v -f -s '{}' libboost_iostreams.so.5
locate libboost_program_options | xargs -I '{}' ln -v -f -s '{}' libboost_program_options.so.5
# try running mvncall
export LD_LIBRARY_PATH=.
./mvncall_v1.0_x86_64_dynamic/mvncall
# mark success
touch mvncall.installed
else
echo mvncall already installed
fi
#check install
print(install_out)
# check we can run mvncall
mvncall = 'LD_LIBRARY_PATH=../dependencies ../dependencies/mvncall_v1.0_x86_64_dynamic/mvncall'
!{mvncall}
```
## prepare input files
```
# these are the source data files for the phasing
sample_file = '../ngs.sanger.ac.uk/production/ag1000g/phase1/AR3.1/haplotypes/main/shapeit/ag1000g.phase1.ar3.1.haplotypes.2L.sample.gz'
vcf_file = '../ngs.sanger.ac.uk/production/ag1000g/phase1/AR3/variation/main/vcf/ag1000g.phase1.ar3.2L.vcf.gz'
scaffold_file = '../ngs.sanger.ac.uk/production/ag1000g/phase1/AR3.1/haplotypes/main/shapeit/ag1000g.phase1.ar3.1.haplotypes.2L.haps.gz'
```
## list of SNPs to phase
```
# this file will contain the list of SNPs to be phased
list_file = '../data/phasing_extra_phase1.list'
%%file {list_file}
2391228
2400071
2429745
# for mvncall we need a simple manifest of sample IDs
# N.B., we will exclude the cross parents
!gunzip -v {sample_file} -c | head -n 767 | tail -n 765 | cut -d' ' -f1 > /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.sample
!head /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.sample
!tail /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.sample
!wc -l /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.sample
```
## haplotype scaffold
```
# mvncall needs the haps unzipped. Also we will exclude the cross parents
!if [ ! -f /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.haps ]; then gunzip -v {scaffold_file} -c | cut -d' ' -f1-1535 > /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.haps; fi
# check cut has worked
!head -n1 /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.haps
# check cut has worked
!head -n1 /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.haps | wc
# mvncall needs an unzipped VCF, we'll extract only the region we need
region_vgsc = SeqFeature('2L', 2358158, 2431617)
region_vgsc.region_str
# extract the VCF
!bcftools view -r {region_vgsc.region_str} --output-file /tmp/vgsc.vcf --output-type v {vcf_file}
%%bash
for numsnps in 50 100 200; do
echo $numsnps
done
%%bash
# run mvncall, only if output file doesn't exist (it's slow)
mvncall="../dependencies/mvncall_v1.0_x86_64_dynamic/mvncall"
export LD_LIBRARY_PATH=../dependencies
for numsnps in 50 100 200; do
output_file=../data/phasing_extra_phase1.mvncall.${numsnps}.vcf
if [ ! -f $output_file ]; then
echo running mvncall $numsnps
$mvncall \
--sample-file /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.sample \
--glfs /tmp/vgsc.vcf \
--scaffold-file /tmp/ag1000g.phase1.ar3.1.haplotypes.2L.haps \
--list ../data/phasing_extra_phase1.list \
--numsnps $numsnps \
--o $output_file > /tmp/mvncall.${numsnps}.log
else
echo skipping mvncall $numsnps
fi
done
!tail /tmp/mvncall.100.log
!cat ../data/phasing_extra_phase1.mvncall.50.vcf
!ls -lh ../data/*.mvncall*
```
## convert to numpy arrays
- so we can interleave these variants back into the genotype array easily
```
def vcf_to_numpy(numsnps):
# input VCF filename
vcf_fn = '../data/phasing_extra_phase1.mvncall.{}.vcf'.format(numsnps)
# extract variants
variants = vcfnp.variants(vcf_fn, cache=False,
dtypes={'REF': 'S1', 'ALT': 'S1'},
flatten_filter=True)
# fix the chromosome
variants['CHROM'] = (b'2L',) * len(variants)
# extract calldata
calldata = vcfnp.calldata_2d(vcf_fn, cache=False,
fields=['genotype', 'GT', 'is_phased'])
# N.B., there is a trailing tab character somewhere in the input VCFs (samples line?)
# which means an extra sample gets added when parsing. Hence we will trim off the last
# field.
calldata = calldata[:, :-1]
# save output
output_fn = vcf_fn[:-3] + 'npz'
np.savez_compressed(output_fn, variants=variants, calldata=calldata)
for numsnps in 50, 100, 200:
vcf_to_numpy(numsnps)
```
check parsing...
```
callset = np.load('../data/phasing_extra_phase1.mvncall.200.npz')
callset
variants = callset['variants']
allel.VariantTable(variants)
calldata = callset['calldata']
g = allel.GenotypeArray(calldata['genotype'])
g.is_phased = calldata['is_phased']
g.displayall()
```
| github_jupyter |
<h1> Machine Learning using tf.estimator </h1>
In this notebook, we will create a machine learning model using tf.estimator and evaluate its performance. The dataset is rather small (7700 samples), so we can do it all in-memory. We will also simply pass the raw data in as-is.
```
import datalab.bigquery as bq
import tensorflow as tf
import pandas as pd
import numpy as np
import shutil
print(tf.__version__)
```
Read data created in the previous chapter.
```
# In CSV, label is the first column, after the features, followed by the key
CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key']
FEATURES = CSV_COLUMNS[1:len(CSV_COLUMNS) - 1]
LABEL = CSV_COLUMNS[0]
df_train = pd.read_csv('./taxi-train.csv', header = None, names = CSV_COLUMNS)
df_valid = pd.read_csv('./taxi-valid.csv', header = None, names = CSV_COLUMNS)
```
<h2> Input function to read from Pandas Dataframe into tf.constant </h2>
```
def make_input_fn(df, num_epochs):
return tf.estimator.inputs.pandas_input_fn(
x = df,
y = df[LABEL],
batch_size = 128,
num_epochs = num_epochs,
shuffle = True,
queue_capacity = 1000,
num_threads = 1
)
```
### Create feature columns for estimator
```
def make_feature_cols():
input_columns = [tf.feature_column.numeric_column(k) for k in FEATURES]
return input_columns
```
<h3> Linear Regression with tf.Estimator framework </h3>
```
tf.logging.set_verbosity(tf.logging.INFO)
OUTDIR = 'taxi_trained'
shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time
model = tf.estimator.LinearRegressor(
feature_columns = make_feature_cols(), model_dir = OUTDIR)
model.train(input_fn = make_input_fn(df_train, num_epochs = 10))
```
Evaluate on the validation data (we should defer using the test data to after we have selected a final model).
```
def print_rmse(model, name, df):
metrics = model.evaluate(input_fn = make_input_fn(df, 1))
print('RMSE on {} dataset = {}'.format(name, np.sqrt(metrics['average_loss'])))
print_rmse(model, 'validation', df_valid)
```
This is nowhere near our benchmark (RMSE of $6 or so on this data), but it serves to demonstrate what TensorFlow code looks like. Let's use this model for prediction.
```
import itertools
# Read saved model and use it for prediction
model = tf.estimator.LinearRegressor(
feature_columns = make_feature_cols(), model_dir = OUTDIR)
preds_iter = model.predict(input_fn = make_input_fn(df_valid, 1))
print([pred['predictions'][0] for pred in list(itertools.islice(preds_iter, 5))])
```
This explains why the RMSE was so high -- the model essentially predicts the same amount for every trip. Would a more complex model help? Let's try using a deep neural network. The code to do this is quite straightforward as well.
<h3> Deep Neural Network regression </h3>
```
tf.logging.set_verbosity(tf.logging.INFO)
shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time
model = tf.estimator.DNNRegressor(hidden_units = [32, 8, 2],
feature_columns = make_feature_cols(), model_dir = OUTDIR)
model.train(input_fn = make_input_fn(df_train, num_epochs = 100));
print_rmse(model, 'validation', df_valid)
```
We are not beating our benchmark with either model ... what's up? Well, we may be using TensorFlow for Machine Learning, but we are not yet using it well. That's what the rest of this course is about!
But, for the record, let's say we had to choose between the two models. We'd choose the one with the lower validation error. Finally, we'd measure the RMSE on the test data with this chosen model.
<h2> Benchmark dataset </h2>
Let's do this on the benchmark dataset.
```
import datalab.bigquery as bq
import numpy as np
import pandas as pd
def create_query(phase, EVERY_N):
"""
phase: 1 = train 2 = valid
"""
base_query = """
SELECT
(tolls_amount + fare_amount) AS fare_amount,
CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key,
DAYOFWEEK(pickup_datetime)*1.0 AS dayofweek,
HOUR(pickup_datetime)*1.0 AS hourofday,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count*1.0 AS passengers,
FROM
[nyc-tlc:yellow.trips]
WHERE
trip_distance > 0
AND fare_amount >= 2.5
AND pickup_longitude > -78
AND pickup_longitude < -70
AND dropoff_longitude > -78
AND dropoff_longitude < -70
AND pickup_latitude > 37
AND pickup_latitude < 45
AND dropoff_latitude > 37
AND dropoff_latitude < 45
AND passenger_count > 0
"""
if EVERY_N == None:
if phase < 2:
# Training
query = "{0} AND ABS(HASH(pickup_datetime)) % 4 < 2".format(base_query)
else:
# Validation
query = "{0} AND ABS(HASH(pickup_datetime)) % 4 == {1}".format(base_query, phase)
else:
query = "{0} AND ABS(HASH(pickup_datetime)) % {1} == {2}".format(base_query, EVERY_N, phase)
return query
query = create_query(2, 100000)
df = bq.Query(query).to_dataframe()
print_rmse(model, 'benchmark', df)
```
RMSE on benchmark dataset is <b>9.41</b> (your results will vary because of random seeds).
This is not only way more than our original benchmark of 6.00, but it doesn't even beat our distance-based rule's RMSE of 8.02.
Fear not -- you have learned how to write a TensorFlow model, but not to do all the things that you will have to do to your ML model performant. We will do this in the next chapters. In this chapter though, we will get our TensorFlow model ready for these improvements.
In a software sense, the rest of the labs in this chapter will be about refactoring the code so that we can improve it.
Copyright 2017 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 |
```
import styling
styling.go()
```
<img src="http://jcreamer898.github.io/webpack-es6-lab/slides/images/duck.gif"/>
# Use case: Internet search like Google or Facebook
# Goal: entertain the user/ keep the eyes on the page / sell ad impressions
# Imperative: The first few entries *must* be hits or the user will leave!
# This is bad: the user will get frustrated by the initial misses
<div class="outside">
<table class="outside">
<tr>
<td>
<!-- panda -->
<div class="miss">
<img src="https://miro.medium.com/max/11520/0*pAypSD1ZSCCw0NcL" width="100">
</div>
</td>
<td>
<!-- fawn -->
<div class="miss">
<img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/gettyimages-168504892-1568303467.png" width="100">
</div>
</td>
<td>
<!-- kitten -->
<div class="hit">
<img src="https://www.petage.com/wp-content/uploads/2019/09/Depositphotos_74974941_xl-2015-e1569443284386-670x627.jpg" width="100">
</div>
</td>
<td>
<!-- tiger -->
<div class="hit">
<img src="https://cdn.vox-cdn.com/thumbor/GzQa3VMNyAITTPQU7ZYMfOjg6lQ=/1400x1400/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/19873983/GettyImages_137497593.jpg" width="100">
</div>
</td>
<td>
<!-- mommy cat -->
<div class="hit">
<img src="https://static.boredpanda.com/blog/wp-content/uploads/2017/05/mother-shelter-cat-nurtures-orphan-kitten-ember-flame-fb.png" width="100">
</div>
</td>
<td>
<!-- lions -->
<div class="hit">
<img src="https://cosmosmagazine.com/wp-content/uploads/2019/12/GettyImages-691120979-1440x1079.jpg" width="100">
</div>
</td>
<td>
<!-- giraffe -->
<div class="miss">
<img src="https://a-z-animals.com/media/2021/01/mammals-400x300.jpg" width="100">
</div>
</td>
<td>
<!-- penguins -->
<div class="miss">
<img src="https://www.vpr.org/sites/vpr/files/styles/medium/public/202001/emperor-penguins-istock-Mario_Hoppmann.png" width="100">
</div>
</td>
</tr>
</table>
</div>
# This is better: hits at the front
<div class="outside">
<table class="outside">
<tr>
<td>
<!-- tiger -->
<div class="hit">
<img src="https://cdn.vox-cdn.com/thumbor/GzQa3VMNyAITTPQU7ZYMfOjg6lQ=/1400x1400/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/19873983/GettyImages_137497593.jpg" width="100">
</div>
</td>
<td>
<!-- mommy cat -->
<div class="hit">
<img src="https://static.boredpanda.com/blog/wp-content/uploads/2017/05/mother-shelter-cat-nurtures-orphan-kitten-ember-flame-fb.png" width="100">
</div>
</td>
<td>
<!-- giraffe -->
<div class="miss">
<img src="https://a-z-animals.com/media/2021/01/mammals-400x300.jpg" width="100">
</div>
</td>
<td>
<!-- penguins -->
<div class="miss">
<img src="https://www.vpr.org/sites/vpr/files/styles/medium/public/202001/emperor-penguins-istock-Mario_Hoppmann.png" width="100">
</div>
</td>
<td>
<!-- panda -->
<div class="miss">
<img src="https://miro.medium.com/max/11520/0*pAypSD1ZSCCw0NcL" width="100">
</div>
</td>
<td>
<!-- fawn -->
<div class="miss">
<img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/gettyimages-168504892-1568303467.png" width="100">
</div>
</td>
<td>
<!-- lions -->
<div class="hit">
<img src="https://cosmosmagazine.com/wp-content/uploads/2019/12/GettyImages-691120979-1440x1079.jpg" width="100">
</div>
</td>
<td>
<!-- kitten -->
<div class="hit">
<img src="https://www.petage.com/wp-content/uploads/2019/09/Depositphotos_74974941_xl-2015-e1569443284386-670x627.jpg" width="100">
</div>
</td>
</tr>
</table>
</div>
# Sure there are hits ranked last -- who cares? Nobody is going to die!
| github_jupyter |
# Matrix
> Marcos Duarte
> Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/))
> Federal University of ABC, Brazil
A matrix is a square or rectangular array of numbers or symbols (termed elements), arranged in rows and columns. For instance:
$$
\mathbf{A} =
\begin{bmatrix}
a_{1,1} & a_{1,2} & a_{1,3} \\
a_{2,1} & a_{2,2} & a_{2,3}
\end{bmatrix}
$$
$$
\mathbf{A} =
\begin{bmatrix}
1 & 2 & 3 \\
4 & 5 & 6
\end{bmatrix}
$$
The matrix $\mathbf{A}$ above has two rows and three columns, it is a 2x3 matrix.
In Numpy:
```
# Import the necessary libraries
import numpy as np
from IPython.display import display
np.set_printoptions(precision=4) # number of digits of precision for floating point
A = np.array([[1, 2, 3], [4, 5, 6]])
A
```
To get information about the number of elements and the structure of the matrix (in fact, a Numpy array), we can use:
```
print('A:\n', A)
print('len(A) = ', len(A))
print('np.size(A) = ', np.size(A))
print('np.shape(A) = ', np.shape(A))
print('np.ndim(A) = ', np.ndim(A))
```
We could also have accessed this information with the correspondent methods:
```
print('A.size = ', A.size)
print('A.shape = ', A.shape)
print('A.ndim = ', A.ndim)
```
We used the array function in Numpy to represent a matrix. A [Numpy array is in fact different than a matrix](http://www.scipy.org/NumPy_for_Matlab_Users), if we want to use explicit matrices in Numpy, we have to use the function `mat`:
```
B = np.mat([[1, 2, 3], [4, 5, 6]])
B
```
Both array and matrix types work in Numpy, but you should choose only one type and not mix them; the array is preferred because it is [the standard vector/matrix/tensor type of Numpy](http://www.scipy.org/NumPy_for_Matlab_Users). So, let's use the array type for the rest of this text.
## Addition and multiplication
The sum of two m-by-n matrices $\mathbf{A}$ and $\mathbf{B}$ is another m-by-n matrix:
$$
\mathbf{A} =
\begin{bmatrix}
a_{1,1} & a_{1,2} & a_{1,3} \\
a_{2,1} & a_{2,2} & a_{2,3}
\end{bmatrix}
\;\;\; \text{and} \;\;\;
\mathbf{B} =
\begin{bmatrix}
b_{1,1} & b_{1,2} & b_{1,3} \\
b_{2,1} & b_{2,2} & b_{2,3}
\end{bmatrix}
$$
$$
\mathbf{A} + \mathbf{B} =
\begin{bmatrix}
a_{1,1}+b_{1,1} & a_{1,2}+b_{1,2} & a_{1,3}+b_{1,3} \\
a_{2,1}+b_{2,1} & a_{2,2}+b_{2,2} & a_{2,3}+b_{2,3}
\end{bmatrix}
$$
In Numpy:
```
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[7, 8, 9], [10, 11, 12]])
print('A:\n', A)
print('B:\n', B)
print('A + B:\n', A+B);
```
The multiplication of the m-by-n matrix $\mathbf{A}$ by the n-by-p matrix $\mathbf{B}$ is a m-by-p matrix:
$$
\mathbf{A} =
\begin{bmatrix}
a_{1,1} & a_{1,2} \\
a_{2,1} & a_{2,2}
\end{bmatrix}
\;\;\; \text{and} \;\;\;
\mathbf{B} =
\begin{bmatrix}
b_{1,1} & b_{1,2} & b_{1,3} \\
b_{2,1} & b_{2,2} & b_{2,3}
\end{bmatrix}
$$
$$
\mathbf{A} \mathbf{B} =
\begin{bmatrix}
a_{1,1}b_{1,1} + a_{1,2}b_{2,1} & a_{1,1}b_{1,2} + a_{1,2}b_{2,2} & a_{1,1}b_{1,3} + a_{1,2}b_{2,3} \\
a_{2,1}b_{1,1} + a_{2,2}b_{2,1} & a_{2,1}b_{1,2} + a_{2,2}b_{2,2} & a_{2,1}b_{1,3} + a_{2,2}b_{2,3}
\end{bmatrix}
$$
In Numpy:
```
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6, 7], [8, 9, 10]])
print('A:\n', A)
print('B:\n', B)
print('A x B:\n', np.dot(A, B));
```
Note that because the array type is not truly a matrix type, we used the dot product to calculate matrix multiplication.
We can use the matrix type to show the equivalent:
```
A = np.mat(A)
B = np.mat(B)
print('A:\n', A)
print('B:\n', B)
print('A x B:\n', A*B);
```
Same result as before.
The order in multiplication matters, $\mathbf{AB} \neq \mathbf{BA}$:
```
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print('A:\n', A)
print('B:\n', B)
print('A x B:\n', np.dot(A, B))
print('B x A:\n', np.dot(B, A));
```
The addition or multiplication of a scalar (a single number) to a matrix is performed over all the elements of the matrix:
```
A = np.array([[1, 2], [3, 4]])
c = 10
print('A:\n', A)
print('c:\n', c)
print('c + A:\n', c+A)
print('cA:\n', c*A);
```
## Transposition
The transpose of the matrix $\mathbf{A}$ is the matrix $\mathbf{A^T}$ turning all the rows of matrix $\mathbf{A}$ into columns (or columns into rows):
$$
\mathbf{A} =
\begin{bmatrix}
a & b & c \\
d & e & f \end{bmatrix}
\;\;\;\;\;\;\iff\;\;\;\;\;\;
\mathbf{A^T} =
\begin{bmatrix}
a & d \\
b & e \\
c & f
\end{bmatrix} $$
In NumPy, the transpose operator can be used as a method or function:
```
A = np.array([[1, 2], [3, 4]])
print('A:\n', A)
print('A.T:\n', A.T)
print('np.transpose(A):\n', np.transpose(A));
```
## Determinant
The determinant is a number associated with a square matrix.
The determinant of the following matrix:
$$ \left[ \begin{array}{ccc}
a & b & c \\
d & e & f \\
g & h & i \end{array} \right] $$
is written as:
$$ \left| \begin{array}{ccc}
a & b & c \\
d & e & f \\
g & h & i \end{array} \right| $$
And has the value:
$$ (aei + bfg + cdh) - (ceg + bdi + afh) $$
One way to manually calculate the determinant of a matrix is to use the [rule of Sarrus](http://en.wikipedia.org/wiki/Rule_of_Sarrus): we repeat the last columns (all columns but the first one) in the right side of the matrix and calculate the sum of the products of three diagonal north-west to south-east lines of matrix elements, minus the sum of the products of three diagonal south-west to north-east lines of elements as illustrated in the following figure:
<br>
<figure><img src='http://upload.wikimedia.org/wikipedia/commons/6/66/Sarrus_rule.svg' width=300 alt='Rule of Sarrus'/><center><figcaption><i>Figure. Rule of Sarrus: the sum of the products of the solid diagonals minus the sum of the products of the dashed diagonals (<a href="http://en.wikipedia.org/wiki/Rule_of_Sarrus">image from Wikipedia</a>).</i></figcaption></center> </figure>
In Numpy, the determinant is computed with the `linalg.det` function:
```
A = np.array([[1, 2], [3, 4]])
print('A:\n', A);
print('Determinant of A:\n', np.linalg.det(A))
```
## Identity
The identity matrix $\mathbf{I}$ is a matrix with ones in the main diagonal and zeros otherwise. The 3x3 identity matrix is:
$$ \mathbf{I} =
\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1 \end{bmatrix} $$
In Numpy, instead of manually creating this matrix we can use the function `eye`:
```
np.eye(3) # identity 3x3 array
```
## Inverse
The inverse of the matrix $\mathbf{A}$ is the matrix $\mathbf{A^{-1}}$ such that the product between these two matrices is the identity matrix:
$$ \mathbf{A}\cdot\mathbf{A^{-1}} = \mathbf{I} $$
The calculation of the inverse of a matrix is usually not simple (the inverse of the matrix $\mathbf{A}$ is not $1/\mathbf{A}$; there is no division operation between matrices). The Numpy function `linalg.inv` computes the inverse of a square matrix:
numpy.linalg.inv(a)
Compute the (multiplicative) inverse of a matrix.
Given a square matrix a, return the matrix ainv satisfying dot(a, ainv) = dot(ainv, a) = eye(a.shape[0]).
```
A = np.array([[1, 2], [3, 4]])
print('A:\n', A)
Ainv = np.linalg.inv(A)
print('Inverse of A:\n', Ainv);
```
### Pseudo-inverse
For a non-square matrix, its inverse is not defined. However, we can calculate what it's known as the pseudo-inverse.
Consider a non-square matrix, $\mathbf{A}$. To calculate its inverse, note that the following manipulation results in the identity matrix:
$$ \mathbf{A} \mathbf{A}^T (\mathbf{A}\mathbf{A}^T)^{-1} = \mathbf{I} $$
The $\mathbf{A} \mathbf{A}^T$ is a square matrix and is invertible (also [nonsingular](https://en.wikipedia.org/wiki/Invertible_matrix)) if $\mathbf{A}$ is L.I. ([linearly independent rows/columns](https://en.wikipedia.org/wiki/Linear_independence)).
The matrix $\mathbf{A}^T(\mathbf{A}\mathbf{A}^T)^{-1}$ is known as the [generalized inverse or Moore–Penrose pseudoinverse](https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse) of the matrix $\mathbf{A}$, a generalization of the inverse matrix.
To compute the Moore–Penrose pseudoinverse, we could calculate it by a naive approach in Python:
```python
from numpy.linalg import inv
Ainv = A.T @ inv(A @ A.T)
```
But both Numpy and Scipy have functions to calculate the pseudoinverse, which might give greater numerical stability (but read [Inverses and pseudoinverses. Numerical issues, speed, symmetry](http://vene.ro/blog/inverses-pseudoinverses-numerical-issues-speed-symmetry.html)). Of note, [numpy.linalg.pinv](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.pinv.html) calculates the pseudoinverse of a matrix using its singular-value decomposition (SVD) and including all large singular values (using the [LAPACK (Linear Algebra Package)](https://en.wikipedia.org/wiki/LAPACK) routine gesdd), whereas [scipy.linalg.pinv](http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.pinv.html#scipy.linalg.pinv) calculates a pseudoinverse of a matrix using a least-squares solver (using the LAPACK method gelsd) and [scipy.linalg.pinv2](http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.pinv2.html) also uses SVD to find the pseudoinverse (also using the LAPACK routine gesdd).
For example:
```
from scipy.linalg import pinv2
A = np.array([[1, 0, 0], [0, 1, 0]])
Apinv = pinv2(A)
print('Matrix A:\n', A)
print('Pseudo-inverse of A:\n', Apinv)
print('A x Apinv:\n', A@Apinv)
```
## Orthogonality
A square matrix is said to be orthogonal if:
1. There is no linear combination of one of the lines or columns of the matrix that would lead to the other row or column.
2. Its columns or rows form a basis of (independent) unit vectors (versors).
As consequence:
1. Its determinant is equal to 1 or -1.
2. Its inverse is equal to its transpose.
However, keep in mind that not all matrices with determinant equals to one are orthogonal, for example, the matrix:
$$ \begin{bmatrix}
3 & 2 \\
4 & 3
\end{bmatrix} $$
Has determinant equals to one but it is not orthogonal (the columns or rows don't have norm equals to one).
## Linear equations
> A linear equation is an algebraic equation in which each term is either a constant or the product of a constant and (the first power of) a single variable ([Wikipedia](http://en.wikipedia.org/wiki/Linear_equation)).
We are interested in solving a set of linear equations where two or more variables are unknown, for instance:
$$ x + 2y = 4 $$
$$ 3x + 4y = 10 $$
Let's see how to employ the matrix formalism to solve these equations (even that we know the solution is `x=2` and `y=1`).
Let's express this set of equations in matrix form:
$$
\begin{bmatrix}
1 & 2 \\
3 & 4 \end{bmatrix}
\begin{bmatrix}
x \\
y \end{bmatrix}
= \begin{bmatrix}
4 \\
10 \end{bmatrix}
$$
And for the general case:
$$ \mathbf{Av} = \mathbf{c} $$
Where $\mathbf{A, v, c}$ are the matrices above and we want to find the values `x,y` for the matrix $\mathbf{v}$.
Because there is no division of matrices, we can use the inverse of $\mathbf{A}$ to solve for $\mathbf{v}$:
$$ \mathbf{A}^{-1}\mathbf{Av} = \mathbf{A}^{-1}\mathbf{c} \implies $$
$$ \mathbf{v} = \mathbf{A}^{-1}\mathbf{c} $$
As we know how to compute the inverse of $\mathbf{A}$, the solution is:
```
A = np.array([[1, 2], [3, 4]])
Ainv = np.linalg.inv(A)
c = np.array([4, 10])
v = np.dot(Ainv, c)
print('v:\n', v)
```
What we expected.
However, the use of the inverse of a matrix to solve equations is computationally inefficient.
Instead, we should use `linalg.solve` for a determined system (same number of equations and unknowns) or `linalg.lstsq` otherwise:
From the help for `solve`:
numpy.linalg.solve(a, b)[source]
Solve a linear matrix equation, or system of linear scalar equations.
Computes the “exact” solution, x, of the well-determined, i.e., full rank, linear matrix equation ax = b.
```
v = np.linalg.solve(A, c)
print('Using solve:')
print('v:\n', v)
```
And from the help for `lstsq`:
numpy.linalg.lstsq(a, b, rcond=-1)[source]
Return the least-squares solution to a linear matrix equation.
Solves the equation a x = b by computing a vector x that minimizes the Euclidean 2-norm || b - a x ||^2. The equation may be under-, well-, or over- determined (i.e., the number of linearly independent rows of a can be less than, equal to, or greater than its number of linearly independent columns). If a is square and of full rank, then x (but for round-off error) is the “exact” solution of the equation.
```
v = np.linalg.lstsq(A, c)[0]
print('Using lstsq:')
print('v:\n', v)
```
Same solutions, of course.
When a system of equations has a unique solution, the determinant of the **square** matrix associated to this system of equations is nonzero.
When the determinant is zero there are either no solutions or many solutions to the system of equations.
But if we have an overdetermined system:
$$ x + 2y = 4 $$
$$ 3x + 4y = 10 $$
$$ 5x + 6y = 15 $$
(Note that the possible solution for this set of equations is not exact because the last equation should be equal to 16.)
Let's try to solve it:
```
A = np.array([[1, 2], [3, 4], [5, 6]])
print('A:\n', A)
c = np.array([4, 10, 15])
print('c:\n', c);
```
Because the matix $\mathbf{A}$ is not squared, we can calculate its pseudo-inverse or use the function `linalg.lstsq`:
```
v = np.linalg.lstsq(A, c)[0]
print('Using lstsq:')
print('v:\n', v)
```
The functions `inv` and `solve` failed because the matrix $\mathbf{A}$ was not square (overdetermined system). The function `lstsq` not only was able to handle an overdetermined system but was also able to find the best approximate solution.
And if the the set of equations was undetermined, `lstsq` would also work. For instance, consider the system:
$$ x + 2y + 2z = 10 $$
$$ 3x + 4y + z = 13 $$
And in matrix form:
$$
\begin{bmatrix}
1 & 2 & 2 \\
3 & 4 & 1 \end{bmatrix}
\begin{bmatrix}
x \\
y \\
z \end{bmatrix}
= \begin{bmatrix}
10 \\
13 \end{bmatrix}
$$
A possible solution would be `x=2,y=1,z=3`, but other values would also satisfy this set of equations.
Let's try to solve using `lstsq`:
```
A = np.array([[1, 2, 2], [3, 4, 1]])
print('A:\n', A)
c = np.array([10, 13])
print('c:\n', c);
v = np.linalg.lstsq(A, c)[0]
print('Using lstsq:')
print('v:\n', v);
```
This is an approximated solution and as explained in the help of `solve`, this solution, `v`, is the one that minimizes the Euclidean norm $|| \mathbf{c - A v} ||^2$.
| github_jupyter |
## 01 OTU Heatmap
This notebook illustrates the objects and code used to generate OTU heatmaps in [Figure S1](assets/Figure_S1.tif).
***
### 1.1 Clean environment. Load libraries.
```
rm(list = ls())
##-- load libs
suppressMessages(library(ComplexHeatmap))
suppressMessages(library(circlize))
```
### 1.2 Import data files.
```
##-- global variables
rare.depth = 13190
##-- data files
sample.file = '../data/human_16S.sampleinfo.csv'
otu.file = '../data/human_16S.even13190.rel.sig.csv'
##-- import data
sample = read.csv(sample.file, row.names = 1)
otu = read.csv(otu.file, row.names = 1)
print(dim(otu))
```
### 1.3 Transform relative abundance into log scale for plotting. Prepare sample annotation groups (NR and R).
```
##-- convert to log scale
otu = log10(round(otu * rare.depth) + 1)
##-- prep input for heatmap
data.plot = t(scale(t(as.matrix(otu)), scale=FALSE))
##-- add sample annotation
sample.anno = sample[,c('Response'),drop=FALSE]
sample.anno = sample.anno[order(match(row.names(sample.anno),
colnames(data.plot))),,drop=F]
plot.colors = c('NonResponder' = '#0000CC','Responder'='#CC0000')
sample.anno.colors = list(
Response = plot.colors
)
plot.anno = HeatmapAnnotation(df = sample.anno,
col = sample.anno.colors)
print(plot.anno)
```
### 1.4 Draw the heatmap on the OTUs differetially abundant between NR and R groups. OTUs are clustered on the row and patients are clustered on the column.
```
##-- set up R plot display options in notebook
options(jupyter.plot_mimetypes = "image/png")
options(repr.plot.width = 10, repr.plot.height = 8)
##-- draw heatmap
col.title = paste0('Metastatic Melanoma (n=',ncol(data.plot),') ')
row.title = paste0('OTUs (n=',nrow(data.plot),') ')
myheatcol = colorRamp2(c(-0.8, 0, 0.8), c("blue", "white", "red"))
p1 = Heatmap(data.plot,
na_col = "#000000",
col = myheatcol,
rect_gp = gpar(col = '#000000'),
show_heatmap_legend = TRUE,
column_title = col.title,
row_title = row.title,
row_dend_width = unit(2, "cm"),
column_dend_height = unit(2, "cm"),
cluster_rows = TRUE,
cluster_columns = TRUE,
clustering_distance_rows = "euclidean",
clustering_method_rows = "ward.D2",
clustering_distance_columns = "euclidean",
clustering_method_columns = "ward.D2",
show_row_names = TRUE,
column_names_side = 'top',
column_names_gp = gpar(fontsize = 12),
row_names_gp = gpar(fontsize = 8),
top_annotation = plot.anno,
heatmap_legend_param =
list(legend_direction = "horizontal",
legend_width = unit(5, "cm"),
color_bar = 'continuous',
title = '')
)
draw(p1, annotation_legend_side = "left", heatmap_legend_side = "bottom")
sessionInfo()
```
| github_jupyter |
```
import pandas as pd
df = pd.read_csv("scalping.csv")
df.head()
df.tail()
df['timestamp'] = df['Unnamed: 0']
df.index = df.timestamp
df = df.drop(['timestamp', 'Unnamed: 0'], axis=1)
df.head()
df.tail()
df.shorts_count.unique
df.REC_NUM_SHORTS.unique
from matplotlib import pyplot as plt
from matplotlib.dates import MonthLocator, date2num, DateFormatter
df.index = pd.DatetimeIndex(df.index)
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.3)
fig.set_figwidth(16)
fig.set_figheight(8)
ax.plot(df.index, df.algo_volatility)
ax.plot(df.index, df.benchmark_volatility)
lctr = MonthLocator() # every month
frmt = DateFormatter('%b') # %b gives us Jan, Feb...
ax.xaxis.set_major_locator(lctr)
ax.xaxis.set_major_formatter(frmt)
plt.xticks(rotation=70)
plt.tight_layout()
plt.legend()
plt.show();
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.3)
fig.set_figwidth(16)
fig.set_figheight(8)
ax.plot(df.index, df.algorithm_period_return)
ax.plot(df.index, df.benchmark_period_return)
lctr = MonthLocator() # every month
frmt = DateFormatter('%b') # %b gives us Jan, Feb...
ax.xaxis.set_major_locator(lctr)
ax.xaxis.set_major_formatter(frmt)
plt.xticks(rotation=70)
plt.tight_layout()
plt.legend()
plt.show();
df.portfolio_value.plot(figsize=(16, 8));
'${:,.2f}'.format(df.capital_used.sum())
'${:,.2f}'.format(df.portfolio_value[-1])
```
<h1>Section 003<h1>
```
df.pnl.plot(figsize=(16, 8));
df.plot(y=['longs_count', 'shorts_count'], figsize=(16, 8));
df.plot(y=['long_exposure', 'short_exposure'], figsize=(16, 8));
df.plot(y=['long_value', 'short_value'], figsize=(16, 8));
print(df.columns)
df.plot(y=['gross_leverage', 'max_leverage', 'net_leverage'], figsize=(16, 8));
```
<h1>Zipline Metric:</h1>
<p style="font-size:2em;">gross_leverage = position_stats.gross_exposure / portfolio_value</p>
```
df['gross_leverage'].plot(figsize=(16, 8));
```
<h1>Section 005</h1>
```
df.plot(y=['sharpe'], figsize=(16, 8));
import numpy as np
# init figure
fig = plt.figure(figsize=(16, 8))
# create axe
ax1 = fig.add_subplot(111)
# plot cumulative returns
ax1.bar(x=df.index.values, height=df.sharpe, label='Sharpe Ratio')
# plot zero line
ax1.axhline(0, linestyle='dashed', color='g')
# plot one line
ax1.axhline(1, linestyle='dashed', color='r')
# labels legend
ax1.legend()
# display plot
plt.show();
from matplotlib import pyplot as plt
from matplotlib.dates import MonthLocator, date2num, DateFormatter
df.index = pd.DatetimeIndex(df.index)
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.3)
fig.set_figwidth(16)
fig.set_figheight(8)
x = 25
ax.plot(df.index[:x], df.REC_PRICE.values[:x], label='price')
ax.plot(df.index[:x], df.REC_MA1.values[:x], label='ma1')
ax.plot(df.index[:x], df.REC_MA2.values[:x], label='ma2')
ax.plot(df.index[:x], df.REC_BB1.values[:x], label='bb1')
ax.plot(df.index[:x], df.REC_BB2.values[:x], label='bb2')
lctr = MonthLocator() # every month
frmt = DateFormatter('%b') # %b gives us Jan, Feb...
ax.xaxis.set_major_locator(lctr)
ax.xaxis.set_major_formatter(frmt)
plt.xticks(rotation=70)
plt.tight_layout()
plt.legend()
plt.show();
df.transactions.values[10]
df.positions.values[10]
df.plot.bar(y=['returns'], figsize=(16, 8));
# init figure
fig = plt.figure(figsize=(16, 8))
# create axe
ax1 = fig.add_subplot(111)
# plot cumulative returns
ax1.bar(x=df.index.values, height=df.returns.cumsum(), label='Cumulative Returns', color='b')
# plot zero line
ax1.axhline(0, linestyle='dashed', color='r')
# labels legend
ax1.legend()
# display plot
plt.show();
df.returns.sum()
```
| github_jupyter |
```
%load_ext py5
%gui osx
import pandas as pd
import numpy as np
from sciviewer import SCIViewer
import scanpy as sc
print('DOWNLOADING AND EXTRACTING EXAMPLE DATA')
! mkdir -p ../data
! wget https://www.dropbox.com/s/gx9y42m4knyi1cl/pbmc3k_umap_20210420.tsv -O ../data/pbmc3k_umap_20210420.tsv
! wget https://www.dropbox.com/s/afnc6cbedvsez75/pbmc3k_expression_log2TP10K_20210420.tsv -O ../data/pbmc3k_expression_log2TP10K_20210420.tsv
! wget https://www.dropbox.com/s/kmryxbttn7e0wh3/pbmc3k_20210420.h5ad -O ../data/pbmc3k_20210420.h5ad
! ls ../data
```
## Here we illustrate how to run Sciviewer with several potential input types.
- [passing in the 2D embedding data and the gene expression data as Pandas DataFrames](#dataframe)
- [passing a Scanpy AnnData object with dense data ](#denseadata)
- [passing a Scanpy AnnData object with sparse data ](#sparseadata)
- [passing a sparse csc_matrix](#sparse_matrix)
<a id="dataframe"></a>
## Dense Pandas DataFrame
Perhaps the simplest way to pass the data is with Pandas DataFrames. The cell names are learned from the rows and the gene names are learned from the columns. The ordering of the cells in the 2D embedding and the gene expression matrix are assumed to match
```
print("LOADING UMAP DATA...")
umap = pd.read_csv('../data/pbmc3k_umap_20210420.tsv', sep='\t', index_col=0)
umap.head()
print("LOADING GENE EXPRESSION DATA...")
expr = pd.read_csv('../data/pbmc3k_expression_log2TP10K_20210420.tsv', sep='\t', index_col=0)
expr.iloc[:5,:5]
svobj = SCIViewer(expr, umap)
svobj.explore_data()
```
#### The class attributes below get populated in real time and thus can be accessed when the interactive viewer is running
```
## This attribute get updated in real time whenever cells are selected
svobj.selected_cells.head()
## This gets updated in real time when cells are selected in directional mode
svobj.results_proj_correlation.sort_values(by='P').head()
## This gets updated in real time when cells are selected in differential mode
svobj.results_diffexpr.sort_values(by='P').head()
```
<a id="denseadata"></a>
## AnnData with dense input matrix
Alternatively, the data can be passed as a Scanpy AnnData object. By default the expression data is read from the .X attribute and the umap data is read from .obsm with the key 'X_umap'. However alternative embeddings can be provided with the `embedding_name` argument and the expression data can be read from the .raw.X attribute by setting the use_raw attribute to True
```
data = sc.read('../data/pbmc3k_20210420.h5ad')
data
```
#### Here the data in data.X is dense and the data in data.raw.X is sparse. We first illustrate the method with the dense data and subsequently with the sparse data
```
svobj = SCIViewer(data, embedding_name='X_umap', use_raw=False)
svobj.explore_data()
```
<a id="sparseadata"></a>
## AnnData with sparse input matrix
```
data.raw.X
```
#### This data is sparse but is in compressed sparse row format (csr_matrix) rather than csc_matrix, so we need to convert it to csc_matrix format
```
import scipy.sparse as sp
z = sp.csc.csc_matrix(data.raw.X)
data.raw = sc.AnnData(z, var=data.raw.var, obs=data.obs)
data.raw.X
```
#### Now that data.raw.X is in csc_matrix format, it can be passed to sciviewer
```
svobj = SCIViewer(data, embedding_name='X_umap', use_raw=True)
svobj.explore_data()
```
<a id="sparse_matrix"></a>
## Passing a sparse matrix directly
We can also pass a sparse matrix directly. Since no information is provided about the gene and cell names, we pass those as separate arguments
```
umap = pd.DataFrame(data.obsm['X_umap'], index=data.obs.index, columns=['UMAP_1', 'UMAP_2'])
umap.head()
cell_names = list(data.obs.index)
cell_names[:5]
gene_names = list(data.raw.var.index)
gene_names[:5]
expr = data.raw.X
svobj = SCIViewer(expr, umap, gene_names=gene_names, cell_names=cell_names)
svobj.explore_data()
```
| github_jupyter |
# User Songs!
A brief diversion into how exactly the user songs are represented.
```
cd -q '..'
import mido
from commons.messages import controlstate
```
I've recorded one track (track 3) on one user song (user song 2).
```
!python extractor.py documents/data/user_song_tests/1track.syx -S 2
```
What's in the MIDI?
```
!python extractor.py documents/data/user_song_tests/1track.syx -s 2 -n documents/data/user_song_tests/1track_{}.mid
mf = mido.MidiFile('documents/data/user_song_tests/1track_2.mid')
mf
mf.tracks
```
We have the time track, which we put first, and then all the other tracks.
```
mf.print_tracks()
mido.tempo2bpm(400000)
def hexspace(x):
return " ".join(format(b, "02X") for b in x)
def trackprint(track):
s = controlstate.MidiControlState()
t = 0
for m in track:
t += m.time
if m.is_meta:
if m.type == 'sequencer_specific':
print(t, 'Sequencer Specific', hexspace(m.data))
else:
print(t, m)
else:
w = s.feed(m)
if w:
print(t, w)
else:
print(t, m)
trackprint(mf.tracks[0])
```
In the time track, we have the time signature and tempo, along with reverb and chorus type. There's a meta message for YAMAHA text, and some sequencer specific messages; all this happens at time 0.
```
trackprint(mf.tracks[1])
```
I recorded Track 3, with main voice 003 and dual voice 103. It seems the main voice is on Channel 0x2 and the dual voice on channel 0xC (so, Channels 3 and 13).
At the beginning, the controls are set for reverb and chorus type, pitch bend, reverb and chorus levels, voice volume, pan, expression, release time (panel sustain), as wekk as Control 94, which according to the MIDI spec table is Effects 4 (Celeste) depth, which is set to zero. The DGX-505 does not apparently recognise it or emit it, but it's something that's recorded (for compatibility?) Same with the polyphonic aftertouch.
Now, what's sent over the MIDI on Song Out playback?
```
!python slurp.py -gp DGX > documents/data/user_song_tests/1track_2.txt
with open('documents/data/user_song_tests/1track_2.txt') as infile:
played = list(mido_util.readin_strings(infile))
from commons import mido_util
def mprint(seq, tpb=None, bpm=None):
s = controlstate.MidiControlState()
rt = 0
if tpb:
tempo = mido.bpm2tempo(bpm)
for m in seq:
if m.type != 'clock':
if m.type == 'start':
rt = m.time
t = m.time - rt
w = s.feed(m)
if tpb:
t = mido.second2tick(t, tpb, tempo)
if w:
print(format(t, '.2f'), w)
else:
print(format(t, '.2f'), m)
mprint(played, 96, 150)
!python slurp.py -ngp DGX > documents/data/user_song_tests/1track_ini.txt
with open('documents/data/user_song_tests/1track_ini.txt') as infile:
ini1 = list(mido_util.readin_strings(infile))
mprint(ini1, 96, 150)
```
Interesting things to note:
The SONG midi output only includes the Main voice, on channel `5`. The Dual voice is not present (I suspect this is because the is no more room. `0` through `2` are keyboard voice, then `3` through `7` are for song tracks, and `8` through `F` are for style and accompaniment.
The track was recorded with MAIN OCTAVE set to -1, DUAL OCTAVE set to 0. This is reflected in the output from the SONG out, which are shifted one octave down, but not for the data stored in the MID file... This data must be *somewhere*... are they repurposing the polyphonic aftertouch??
If this is indeed the case, then for proper export we must actually parse the messages to correct for this!
```
!python collect.py -g DGX > documents/data/user_song_tests/2track.syx
!python extractor.py documents/data/user_song_tests/2track.syx -S 2 -s 2 -n documents/data/user_song_tests/2track_{}.mid
!python slurp.py -ngp DGX > documents/data/user_song_tests/2track_ini.txt
with open('documents/data/user_song_tests/2track_ini.txt') as infile:
ini2 = list(mido_util.readin_strings(infile))
mprint(ini2)
```
Recorded another track, this time with a different tempo.
The Main voice was voice 205 with octave -2, the dual voice was voice 005 with octave +2.
```
mf2 = mido.MidiFile('documents/data/user_song_tests/2track_2.mid')
trackprint(mf2.tracks[0])
```
The tempo is overwritten, and Whoops, I apparently overwrote the time signature as well.
```
mf2.tracks[1] == mf.tracks[1]
trackprint(mf2.tracks[2])
```
The Main voice was recorded onto channel `4` (5), and dual voice onto channel `E` (15).
The Dual notes are recorded with +2 octave on them, but the main voice is not. Instead, it's got a polytouch message with value 62. Hmmm.
What happens if we try to change the voice while recording?
We can't use the function menus, but what about scrolling the voice.
Do the defaults get set?
What about using values saved in the bank registers?
What happens if we change the reverb and chorus type?
What about transpose?
```
!python extractor.py documents/data/user_song_tests/2track.syx -R 2,2 3,2
```
|Main Voice |M Volume|M Octave|M Reverb Lv|M Chorus Lv|Dual Voice |D Volume|D Octave|D Reverb Lv|D Chorus Lv|
|:-----------------------------------|-------:|-------:|----------:|----------:|:------------------------------|-------:|-------:|----------:|----------:|
|085 Trombone Section | 110| -1| 34| 0|088 Brass Section | 90| -1| 32| 0|
|086 French Horn | 80| 0| 40| 0|084 Trombone | 70| 0| 36| 0|
|087 Tuba | 127| -2| 18| 0|045 Acoustic Bass | 84| -2| 0| 0|
|119 Music Box | 100| +1| 20| 0|108 SweetHeaven | 60| 0| 42| 0|
|075 Baritone Sax | 112| -2| 28| 0|088 Brass Section | 100| -1| 24| 0|
|025 16'+2' Organ | 70| -1| 28| 34|026 16'+4' Organ | 30| +1| 28| 0|
Let's record track 4, starting with the chorus and reverb types set to something different. Then, cycle through voices 085, 086, 087, 119, 075, 025, with dual ON.
```
!python collect.py -g DGX > documents/data/user_song_tests/3track.syx
!python extractor.py documents/data/user_song_tests/3track.syx -S 2 -s 2 -n documents/data/user_song_tests/3track_{}.mid
mf3 = mido.MidiFile('documents/data/user_song_tests/3track_2.mid')
mf3.tracks[1] == mf2.tracks[1]
mf3.tracks[3] == mf2.tracks[2]
trackprint(mf3.tracks[0])
```
The reverb and chorus type got overwritten. Also, I tried setting the time signature to 0, and it's at 1/4, which makes sense.
```
trackprint(mf3.tracks[2])
```
Okay, it definitely looks like the default settings get set. The Dual octave affects the dual notes directly, while the Main octave is signalled by a polytouch message, with offset from 64. The program changes etc. are recorded for both main and dual, even if dual is not activated. Transpose is completely ignored.
Question: Does the polytouch message work for songs in the flash memory?
What happens if we send a GM_ON or set the reverb in the middle? Does that reset the reverb and chorus types? How about regular reverb chorus messages?
Also, it seems that the durations are indeed in measures, and affected by the time signature on the time track.
Does setting LOCAL have any effect?
```
o = mido.open_output('DGX-505 MIDI 1')
from commons.messages import controls
import time
def test():
o.send(controls.reverb_type(00, 00))
time.sleep(2)
o.send(controls.chorus_type(00, 00))
time.sleep(4)
o.send(controls.gm_on())
time.sleep(2)
o.send(controls.local(False))
time.sleep(5)
o.send(controls.local(True))
time.sleep(3)
o.send(controls.master_tune_val(100))
time.sleep(3)
o.send(controls.xg_reset())
test()
!python collect.py -g DGX > documents/data/user_song_tests/4track.syx
!python extractor.py documents/data/user_song_tests/4track.syx -S 2 -s 2 -n documents/data/user_song_tests/4track_{}.mid
o.close()
mf4 = mido.MidiFile('documents/data/user_song_tests/4track_2.mid')
mf4.tracks[2:] == mf3.tracks[1:]
trackprint(mf4.tracks[0])
trackprint(mf4.tracks[1])
```
The reverb and chorus type don't get changed while the thing is recording. LOCAL and so on do not seem to have an effect on what is recorded
```
with open('documents/data/user_song_tests/4track_rec.txt') as infile:
recd = list(mido_util.readin_strings(infile))
mprint(recd, 96, 100)
```
Questions: How is the Harmony handled?
How does the Octave work with drum kits?
Now recording both a style and track 1 at the same time. It's gonna sound terrible, but we aren't listening to this for fun.
Initial settings:
- Style no: 102 (6/8 March)
- Pattern: Intro A - I'll be changing this several times: Intro A - Main A - Fill B - Main B - Ending - Ending rit. Fill A, Main A, Ending, and then trying to prolong the ending by switching styles (Style switches don't get recorded, do they?)
- Style volume: 30
- Reverb Type: 06 Stage1
- Chorus Type: 2 Chorus2
Initial Voice settings
- Harmony: ON,
- Harmony Type: Trio
- Harmony Volume: 96
- M. Octave: -1
- D. Octave: 0
- D. Voice: 007 CP-80
- M.Voice: 301 Warm Trumpet
Okay, so it seems they don't let you change the style while recording. Makes sense.
```
!python collect.py -g DGX > documents/data/user_song_tests/5track.syx
!python extractor.py documents/data/user_song_tests/5track.syx -S 2 -s 2 -n documents/data/user_song_tests/5track_{}.mid
mf5 = mido.MidiFile('documents/data/user_song_tests/5track_2.mid')
mf5.tracks[2:] == mf4.tracks[1:]
trackprint(mf5.tracks[1])
with open('documents/data/user_song_tests/5track_rec.txt') as infile:
in5 = list(mido_util.readin_strings(infile))
def channelize(msgs, ch=frozenset([0, 1, 2])):
for m in msgs:
try:
c = m.channel
except AttributeError:
yield m
else:
if c in ch:
yield m
def cprint(msgs, ch=frozenset([0, 1, 2]), *args, **kwargs):
return mprint(channelize(msgs, ch), *args, **kwargs)
cprint(in5, {0,1,2}, 96, 100)
```
We have the Main Voice on channel `0` (1) and the dual voice on channel `A` (11). The Harmony voice is also on channel `0`, with the same (non-)offset octave as the main voice. This means the notes are hardcoded, and will survive getting the chords changed on them. (I suspect something similar works with the Performance Assistant for this.)
The Harmony Volume is a simple reduction of velocity, with it seems like applying Main velocity*(Harmony Volume/127) or something like it.
Interesting to note in the captured MIDI output, there are a few Portamento Control events for the harmony notes, I think when the chords changed.
```
o = mido.open_output('DGX-505 MIDI 1')
o.send(mido.Message('note_off', channel=0, note=60))
def pulse(o=o, t=0.5, n=60, v=100, c=0):
o.send(mido.Message('note_on', channel=c, note=n, velocity=v))
time.sleep(t)
o.send(mido.Message('note_on', channel=c, note=n, velocity=0))
time.sleep(t)
pulse(o)
o.send(mido.Message('polytouch', note=0, value=63, channel=0))
pulse(o)
```
Sending polytouch does nothing.
How about the chords and part information?
```
trackprint(mf5.tracks[0])
```
The chords go like this:
C, E, F, C, F, C, F, C, D.
Unlike the chords in the provided CD MIDI songs, these use sequencer specific meta messages instead of SysEx for the chords. The basic format seems to be the same, but using the extended-root system so C=`31`, D=`32`, E=`33`, F=`34` and so on.
The sequencer specific messages are `43 76 1A 03 RR TT RR TT`, which is that of the PSR-225.
The equivalent SysEx, as found in the CD MIDI, is `43 7E 02 RR TT RR TT`.
The style part starts with three messages
0 Sequencer Specific 43 76 1A 04 00 65
0 Sequencer Specific 43 76 1A 02 1E
0 Sequencer Specific 43 76 1A 01 03
In all previous recordings they had different values:
0 Sequencer Specific 43 76 1A 04 00 00
0 Sequencer Specific 43 76 1A 02 64
0 Sequencer Specific 43 76 1A 01 00
```
0x65
0x1E
```
So `43 76 1A 04 xx xx` is the style number, `43 76 1A 02 xx` is the style volume.
`43 76 1A 01 xx` is a style part, which is set by default to be `00` (Main A?)
The style parts were recorded as thus:
Intro A, Main A, Fill B, Main B, Ending (B), Fill A, Main A, Fill B, Ending (B), Ending rit.(B), Fill A, Main A, Ending (A).
```
trackprint(m for m in mf5.tracks[0] if m.type == 'sequencer_specific' and m.data[3] == 1 or m.type=='set_tempo')
```
Intro A = `03`, Main A = `00`, Fill (A→)B = `02`, Main B = `05`, Ending B = `09`, Fill (B→)A = `06`, Ending A = `04`
This matches the PSR, except that we don't have fills AA and BB. AB and BA only.
Note that Ending A and B are separate, even though the display just says 'ENDING'.
Ending rit. isn't a special mode, it's just Ending with rit. appied through tempo.
What about the ones we encountered in the CD MIDI?
<meta message sequencer_specific data=(67, 123, 12, 1, 2) time=0>
<meta message sequencer_specific data=(67, 123, 0, 88, 70, 48, 50, 0, 27) time=0>
```
print(hexspace((67, 123, 12, 1, 2)))
print(hexspace((67, 123, 0, 88, 70, 48, 50, 0, 27)))
```
No idea what these are.
What happens when we clear out the style tempo track?
```
!python collect.py -g DGX > documents/data/user_song_tests/6track.syx
!python extractor.py documents/data/user_song_tests/6track.syx -S 2 -s 2 -n documents/data/user_song_tests/6track_{}.mid
trackprint(mido.MidiFile('documents/data/user_song_tests/6track_2.mid').tracks[0])
```
Looks like it erased all the chords a nd so on, but not the tempo. It even left the style number and volume intact.
Let's see if we can get the other status messages.
Start with Intro B, and maybe we try to get Fill AA somehow? Also set the style number > 127, to overflow into the previous byte,
```
!python collect.py -g DGX > documents/data/user_song_tests/7track.syx
!python extractor.py documents/data/user_song_tests/7track.syx -S 2 -s 2 -n documents/data/user_song_tests/7track_{}.mid
trackprint(mido.MidiFile('documents/data/user_song_tests/7track_2.mid').tracks[0])
```
It turns out the piano accompaniments don't have a fill. Oh well.
Also, meta messages can handle values >127.
So here we have confirmation that Intro B is `08`.
Now, to double-check the ticks per beat, and also see when the duration overflows.
Let's record User Song 1, but with time signature 1/4 and tempo 280 bpm.
With harmony on Tremolo 1/4, so that the notes should turn on every beat, record >256 measures.
Also while we're at it try to check drum kit octaves, maybe.
```
!python collect.py -g DGX > documents/data/user_song_tests/8track.syx
!python extractor.py documents/data/user_song_tests/8track.syx -S 1 -s 1 -n documents/data/user_song_tests/8track_{}.mid
t0 = mido.MidiFile('documents/data/user_song_tests/8track_1.mid')
t0
trackprint(t0.tracks[0])
trackprint(t0.tracks[1])
trackprint(t0.tracks[1][38:384])
pulse_messages = t0.tracks[1][38:384]
from collections import Counter
Counter(m.time for m in pulse_messages)
```
There are 48 ticks between each note-on and note-off (excepting some weirdness at the start), which gives 48×2=96 ticks between each note_on, or 96 ticks per beat.
Changing to the registry voice with everything the same except the octave sends out the octave change (polytouch) message, as well as pitch bend range changes for both main and dual voices.
And the drum kit does behave like any other voice with respect to the octave offset (in this case, -1); the messages recorded are not the actual notes played (eg. if a midi player or using mido-play to send back over MIDI to the keyboard). I wonder if this will be recognised for flash memory MIDI; I know that the style number meta-messages are not but the chord changes are, from an older experiment.
The next experiment is to play every chord. I attempted to play every chord that appears in the manual, as well as the weird one that isn't, and the non-chord that happens if you mash keys. Fun!
```
!python collect.py -g DGX > documents/data/user_song_tests/9track.syx
!python extractor.py documents/data/user_song_tests/9track.syx -S 1 -s 1 -n documents/data/user_song_tests/9track_{}.mid
t1 = mido.MidiFile('documents/data/user_song_tests/9track_1.mid')
t0.tracks[1] == t1.tracks[1]
trackprint(t1.tracks[0])
```
Note: mashing the A/B button will not allow you to access FILL AA. I guess we don't support it.
```
tmetas = [m for m in t1.tracks[0] if m.type == 'sequencer_specific']
for i, m in enumerate(tmetas):
print("{:3d}: {:4d} | {:<14} #".format(i, m.time, hexspace(m.data[3:])))
```
Now, let's attempt to annotate. First, I tried to do all the recognised chords in the manual order, then some other things, and then all the keys in order, and then I tried to get some weird looking chords.
Seq: delta| Bytes
0: 0 | 04 00 36 # Style No.
1: 0 | 02 64 # Style Vol
2: 0 | 01 05 # MAIN B
3: 481 | 01 06 # FILL A
4: 150 | 01 02 # FILL B
5: 97 | 01 06 # FILL A
6: 100 | 01 02 # FILL B
7: 132 | 01 06 # FILL A
8: 87 | 01 02 # FILL B
9: 393 | 01 05 # MAIN B
10: 486 | 01 06 # FILL A
11: 474 | 01 00 # MAIN A
12: 91 | 03 31 00 31 00 # C Major
13: 1823 | 03 31 04 31 04 # C(9)
14: 478 | 03 31 01 31 01 # C6
15: 962 | 03 31 04 31 04 # (intermittent C9)
16: 3 | 03 31 06 31 06 # C6(9)
17: 958 | 03 31 02 31 02 # CM7
18: 957 | 03 31 05 31 05 # CM7(9)
19: 961 | 03 31 03 31 03 # CM7(#11)
20: 953 | 03 44 27 31 1E # (Forgot to press E and ended up with some F# chords)
21: 968 | 03 44 29 31 1E #
22: 1441 | 03 31 24 31 24 # Cb5
23: 960 | 03 31 23 31 23 # CM7b5
24: 959 | 03 31 20 31 20 # Csus4
25: 1116 | 03 31 07 31 07 # Caug
26: 807 | 03 31 1C 31 1C # CM7aug
27: 955 | 03 31 08 31 08 # Cm
28: 658 | 03 31 0C 31 0C # Cm(9)
29: 787 | 03 31 09 31 09 # Cm6
30: 962 | 03 31 0A 31 0A # Cm7
31: 961 | 03 31 0D 31 0D # Cm7(9)
32: 1435 | 03 23 21 23 21 # (intermittent chord)
33: 3 | 03 31 0E 31 0E # Cm7(11)
34: 1242 | 03 31 0F 31 0F # CmM7
35: 857 | 03 23 00 23 00 # (intermittent chord)
36: 2 | 03 31 10 31 10 # CmM7(9)
37: 1252 | 03 31 0B 31 0B # Cm7b5
38: 965 | 03 31 25 31 25 # CmM7b5
39: 1917 | 03 31 11 31 11 # Cdim
40: 480 | 03 31 12 31 12 # Cdim7
41: 483 | 03 31 13 31 13 # C7
42: 957 | 03 31 19 31 19 # C7(b9)
43: 963 | 03 31 1A 31 1A # C7(b13)
44: 969 | 03 31 16 31 16 # C7(9)
45: 1913 | 03 31 17 31 17 # C7(#11)
46: 959 | 03 31 18 31 18 # C7(13)
47: 1122 | 03 31 19 31 19 # C7(b9) again
48: 791 | 03 31 1B 31 1B # C7(#9)
49: 1337 | 03 31 13 31 13 # (intermittent)
50: 3 | 03 31 15 31 15 # C7b5
51: 1060 | 03 31 1D 31 1D # C7aug
52: 482 | 03 31 14 31 14 # C7sus4
53: 960 | 03 31 21 31 21 # Csus2
54: 963 | 03 31 1F 31 1F # C1+5
55: 957 | 03 31 1E 31 1E # C1+8
56: 2097 | 03 31 26 31 26 # C* (C + Db + Eb)
57: 788 | 03 22 00 22 00 # (intermittent)
58: 3 | 03 31 27 31 27 # C* (C + Db +
59: 958 | 03 31 28 31 28 # C* (C + Db +
60: 586 | 01 02 #
61: 376 | 01 05 #
62: 4 | 03 31 00 31 00 # C
63: 460 | 03 22 00 22 00 # Db
64: 489 | 03 32 00 32 00 # D
65: 482 | 03 23 00 23 00 # Eb
66: 479 | 03 33 00 33 00 # E
67: 486 | 03 34 00 34 00 # F
68: 99 | 03 44 00 44 00 # F#
69: 96 | 03 35 00 35 00 # G
70: 95 | 03 45 00 45 00 # G#
71: 190 | 03 36 00 36 00 # A
72: 104 | 03 27 00 27 00 # Bb
73: 178 | 03 37 00 37 00 # B
74: 191 | 03 31 00 31 00 # C
75: 549 | 03 31 1E 31 1E # C1+8
76: 224 | 03 37 1E 37 1E # B1+8
77: 194 | 03 27 1E 27 1E # B♭1+8
78: 282 | 03 36 1E 36 1E # A1+8
79: 186 | 03 45 1E 45 1E # G♯1+8
80: 288 | 03 35 00 35 00 # (intermittent G)
81: 3 | 03 35 1E 35 1E # G1+8
82: 194 | 03 44 00 44 00 # (intermittent F#)
83: 3 | 03 44 1E 44 1E # F♯1+8
84: 278 | 03 34 1E 34 1E # F1+8
85: 205 | 03 33 00 33 00 # (intermittent E)
86: 4 | 03 33 1E 33 1E # E1+8
87: 276 | 03 23 00 23 00 # (intermittent Eb)
88: 2 | 03 23 1E 23 1E # Eb1+8
89: 191 | 03 32 1E 32 1E # D1+8
90: 285 | 03 22 1E 22 1E # Db1+8
91: 200 | 03 31 1E 31 1E # C1+8
92: 485 | 03 31 00 35 1E # C/G (you get this with a fourth)
93: 467 | 03 22 00 45 1E # Db/G#
94: 291 | 03 32 00 36 1E # D/A
95: 194 | 03 23 00 27 1E # Eb/Bb
96: 289 | 03 33 00 37 1E # E/B
97: 191 | 03 34 00 34 00 # (intermittent F)
98: 2 | 03 34 00 31 1E # F/C
99: 285 | 03 44 00 22 1E # F#/Db
100: 193 | 03 35 00 35 00 # (intermittent G)
101: 3 | 03 35 00 32 1E # G/D
102: 275 | 03 45 00 23 1E # G#/Eb
103: 194 | 03 36 00 36 00 # (intermittent A)
104: 3 | 03 36 00 33 1E # A/E
105: 287 | 03 27 00 27 00 # (intermittent Bb)
106: 3 | 03 27 00 34 1E # Bb/F
107: 196 | 03 37 00 44 1E # B/F#
108: 286 | 03 31 00 35 1E # C/G
109: 191 | 03 33 08 33 08 # (intermittent Em)
110: 2 | 03 31 00 31 00 # C (C alone)
111: 482 | 03 31 13 31 13 # C7 (C with adjacent B shortcut)
112: 280 | 03 31 08 31 08 # Cm (C with adjacent Bb shortcut)
113: 197 | 03 36 08 36 08 # Am (A + C)
114: 285 | 03 45 00 45 00 # G# (G#+C)
115: 198 | 03 31 00 35 1E # C/G (G + C)
116: 272 | 03 44 24 44 24 # F#b5 (F# + C)
117: 206 | 03 34 1F 34 1F # F1+5 (F + C)
118: 291 | 03 31 00 33 1E # C/E (E + C)
119: 184 | 03 32 13 32 13 # D7
120: 479 | 03 31 04 31 04 # C9
121: 388 | 03 32 00 32 00 # (intermittent D)
122: 3 | 03 31 04 31 04 # C9
123: 87 | 03 32 00 32 00 # D
124: 109 | 03 31 04 31 04 #
296: 3 | 03 23 26 34 1E #
297: 960 | 03 33 00 33 00 #
298: 3 | 03 23 22 23 22 # The Mysterious Chord 22
299: 2 | 03 33 0F 34 1E #
306: 195 | 03 34 00 34 00 #
307: 4 | 03 23 28 34 1E # Chord 28
308: 146 | 03 34 00 34 00 #
336: 3 | 03 45 23 33 1E #
337: 175 | 03 22 00 37 1E #
338: 2 | 03 37 22 34 1E # Chord 22, but with a bottom accompaniment
339: 207 | 03 27 08 27 08 #
Time for even more testing?
```
!python collect.py -g DGX > documents/data/user_song_tests/10track.syx
trackprint(t1.tracks[1])
!python extractor.py documents/data/user_song_tests/10track.syx -S 1 -s 1 -n documents/data/user_song_tests/10track_{}.mid
!python extractor.py documents/data/user_song_tests/8track.syx -S 1
```
What's going on with the durations?
344 measures in 1/4 should be ~68 measures in 5/4 right? Why is Track 1 longer than Track A?
```
tr8 = mido.MidiFile('documents/data/user_song_tests/8track_1.mid')
trackprint(tr8.tracks[0])
tr9 = mido.MidiFile('documents/data/user_song_tests/9track_1.mid')
trackprint(tr9.tracks[0])
trackprint(tr8.tracks[1])
tr10 = mido.MidiFile('documents/data/user_song_tests/10track_1.mid')
tr10.tracks[0] == tr9.tracks[0]
tr10.tracks[0][5:] == tr9.tracks[0][5:]
trackprint(tr10.tracks[0][:5])
trackprint(tr9.tracks[0][:5])
trackprint(tr10.tracks[2])
```
I recorded Track 2 with LOCAL OFF, Performance Assistant ON melody mode, the reverb and chorus types set OFF but the reverb and chorus levels set to maximum. Local OFF did nothing but make it impossible to hear what you're playing.
The performance assistant actually affects the notes being played, so that is hard coded into the track.
Changing the reverb and chorus types actually overwrites the reverb and chorus types on track A.
Back to those durations...
```
# measures = (ticks) * (beats / tick) * (measures / beats)
# = (ticks) / (ticks / beat) / (beats / measure)
def measures(midifile, track_no):
ticks = sum(m.time for m in midifile.tracks[track_no])
timesig = midifile.tracks[0][0]
return int(ticks / midifile.ticks_per_beat / timesig.numerator)
measures(tr8, 1)
measures(tr8, 0)
measures(tr9, 1)
measures(tr9, 0)
[measures(tr10, i) for i in range(3)]
!python extractor.py documents/data/user_song_tests/10track.syx -S 1
def measures2(midifile, track_no):
ticks = sum(m.time for m in midifile.tracks[track_no])
timesig = midifile.tracks[0][0]
return (ticks / (timesig.numerator * midifile.ticks_per_beat))
measures2(tr10, 0)
```
... maybe they round up and subtract 1?
```
import struct
def binspace(x):
return " ".join(format(b, "08b") for b in x)
def bprint(x, f='>L'):
print(binspace(struct.pack('>L', x)))
bprint(344)
bprint(68)
bprint(275)
```
*Interesting*, are these really weird values...
Is it a coincidence that 275 is 68 shifted up two places with ones inserted??
```
68 << 2 | 0b11
```
I dunno. Probably.
Additional tests:
1. New track with a different tempo and chorus type
- What about overwriting the tempo?
- When we overwrite the Reverb and Chorus types, does it affect playback for all tracks?
2. Overwrite the style track with a new style with a different time signature
- Can we get even weirder durations?
- What exactly are the chord codes for the following combinations:
- C* (C + D♭ + E♭)
- C* (C + D♭ + F♯)
- C* (C + D♭ + G)
- C* (C + D♭ + B♭)
- C* (C + D + E)
- Weird bass only chord (C + D♭ + D + E♭)
- Weird bass only chord with bottom note (C + D + E♭ + E) (same as above)?
- Weird bass only chord with bottom note (G + C + D♭ + D + E♭) (same as above)?
- Weird bass only chord with bottom note (G + C + D♭ + B) (same as above)?
- No chord? (C + D♭ + B)
- Transpositions of the above
- Versions with various bottom notes added
```
!python collect.py -g DGX > documents/data/user_song_tests/11track.syx
!python extractor.py documents/data/user_song_tests/11track.syx -S 1 -s 1 -n documents/data/user_song_tests/11track_{}.mid
tr11 = mido.MidiFile('documents/data/user_song_tests/11track_1.mid')
[tr10.tracks[i] == tr11.tracks[i] for i in range(3)]
trackprint(x for x, y in zip(tr11.tracks[0], tr10.tracks[0]) if x != y)
trackprint(tr11.tracks[3])
```
You can't change the tempo if a style track is recorded, but the chorus and reverb types are overwritten... and yes, upon hearing the playback, it affects the whole instrument, not just per track.
Now, we overwrite the style track with a style with a different time signature and tempo, and accompany with some weird chords.
Let's try JazzWaltz2 (115).
```
!python collect.py -g DGX > documents/data/user_song_tests/12track.syx
!python extractor.py documents/data/user_song_tests/12track.syx -S 1 -s 1 -n documents/data/user_song_tests/12track_{}.mid
5/3 * 275
tr12 = mido.MidiFile('documents/data/user_song_tests/12track_1.mid')
[tr11.tracks[i] == tr12.tracks[i] for i in range(4)]
[measures(tr12, x) for x in range(4)]
[5/3 * measures(tr11, x) for x in range(4)]
bprint(30)
bprint(38)
```
Yeah, I don't know what's going on with the numbers.
```
trackprint(tr12.tracks[0])
for i, m in enumerate(m for m in tr12.tracks[0] if m.type =='sequencer_specific'):
print("{:3d}: {:4d} | {:<14} # ".format(i, m.time, hexspace(m.data[3:])))
```
Again, we look for the chords
0: 0 | 04 00 72 # Style no.
1: 0 | 02 64 # vol.
2: 0 | 01 00 # Main A
3: 0 | 03 31 00 31 00 # C
4: 2868 | 03 23 08 23 08 # (int)
5: 5 | 03 31 26 31 26 # C*: C + D♭ + E♭
6: 1735 | 03 31 27 31 27 # C*: C + D♭ + F♯
7: 1208 | 03 31 28 31 28 # C*: C + D♭ + G
8: 1103 | 03 31 29 31 29 # C*: C + D♭ + B♭
9: 1138 | 03 37 22 37 22 # no chord: C + D♭ + B: -> B-C-D♭ Chord 22 -> Bx
10: 2299 | 03 22 13 22 13 # (int)
11: 7 | 03 22 22 31 1E # C bass: C + D♭ + D + E♭ -> C + D♭-D-E♭ Chord 22 -> D♭x/C
12: 2022 | 03 31 00 31 00 # C
13: 559 | 03 23 22 31 1E # C bass: C + D + E♭ + E -> C + D-E♭-E Chord 22 -> Dx/C
14: 598 | 03 31 00 31 00 # C
15: 559 | 03 44 22 31 1E # C bass: F♯x/C
16: 579 | 03 31 00 31 00 # C
17: 1741 | 03 22 22 35 1E # G bass: D♭x/G
18: 567 | 03 32 13 32 13 # (int)
19: 4 | 03 22 22 44 1E # F♯ bass: D♭x/F♯
20: 566 | 03 31 22 34 1E # (int)
21: 4 | 03 22 22 34 1E # F bass: D♭x/F
22: 290 | 03 33 00 33 00 # (int)
23: 4 | 03 22 22 33 1E # E bass: D♭x/E
24: 295 | 03 31 22 23 1E # (int)
25: 4 | 03 22 22 23 1E # E♭ bass: D♭x/E♭
26: 269 | 03 31 26 32 1E # (int)
27: 4 | 03 22 22 32 1E # D bass: D♭x/D
28: 280 | 03 22 22 22 1E # D♭ bass: "D♭x/D♭" ?
29: 293 | 03 22 22 31 1E # C bass: C♭x/C
30: 1144 | 03 37 22 37 22 # no chord: Bx
31: 2318 | 03 31 26 31 26 # C*: C + D♭ + E♭
32: 573 | 03 31 2A 31 2A # C*: C + D + E
33: 581 | 03 31 26 31 26 # C*: C + D♭ + E♭
34: 577 | 03 31 2A 31 2A # C*: C + D + E
35: 577 | 03 31 26 31 26 # C*: C + D♭ + E♭
36: 565 | 03 31 26 22 1E # C*/D♭: D♭ + C + (D♭?) + E♭
37: 578 | 03 22 0F 22 0F # D♭mM7: E + C + D♭?
38: 289 | 03 31 26 22 1E # C*/D♭
39: 283 | 03 22 05 22 1E # D♭M7(9): E + C + D♭ + E♭?
40: 290 | 03 22 1E 22 1E # (int) D♭1+8
41: 5 | 03 31 26 22 1E # C*/D♭: D♭ + E♭ + C + D♭?
42: 278 | 03 23 0A 22 1E # E♭m7/D♭: D♭ + C + D♭ + E♭ + F♯
43: 290 | 03 31 26 22 1E # C*/D♭: D♭ + C + D♭ + E♭
44: 293 | 03 23 0A 35 1E # E♭m7/G: G + C + D♭ + E♭ + F♯
45: 293 | 03 31 27 35 1E # C*/G: G + C + D♭ + F♯
46: 871 | 03 31 28 44 1E # C*/F♯: F♯ + C + D♭ + G
47: 1142 | 03 31 27 44 1E # C*/F♯: F♯ + C + D♭ + F♯
48: 558 | 03 22 0F 44 1E # D♭mM7/F♯: F♯ + C + D♭ + E
49: 334 | 03 44 00 44 00 # (int) F♯
50: 5 | 03 31 26 44 1E # C*/F♯: F♯ + C + D♭ + E♭
51: 342 | 03 31 22 44 1E # F♯ bass: F♯ + B + C + D♭
52: 491 | 03 32 16 32 16 # D7(9): F♯ + C + D + E
53: 1153 | 03 36 00 36 00 # (int) A
54: 4 | 03 36 0E 36 0E # Am7(11): A + C + D + E
55: 290 | 03 31 04 31 04 # C(9): G + C + D + E
56: 218 | 03 32 16 32 16 # D7(9): F♯ + C + D + E
57: 115 | 03 32 0D 32 0D # Dm(7(9): F + C + D + E
58: 242 | 03 33 00 33 00 # (int)
59: 4 | 03 31 2A 33 1E # C*/E: E + C + D + E
60: 99 | 03 32 29 23 1E # (int) E♭ + C + D
61: 4 | 03 31 2A 23 1E # C*/E♭: E♭ + C + D + E
62: 120 | 03 33 00 33 00 # (int) E
63: 9 | 03 31 2A 33 1E # C*/E
64: 614 | 03 35 02 35 02 # GM7: G + F♯ + ?
65: 581 | 03 33 26 35 1E # E*/G: G + E + F + (G?)
66: 569 | 03 23 2A 35 1E # E♭*/G: G + E♭ + F + (G?)
67: 1183 | 03 35 00 35 00 # G: (G + G + B)?
68: 546 | 03 35 29 35 29 # G*: G + F + G♯
69: 655 | 03 35 00 35 00 # (int) G
70: 5 | 03 44 22 44 22 # F♯x: G + F♯ + G♯
| github_jupyter |
```
import sys
sys.version
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
#第一个参数是起始坐标,第二个参数是中点坐标, 第三个参数是分割的段数
c, s = np.cos(x), np.sin(x)
#c, s 分别为x 对应的正弦余弦值
plt.plot(x, c)
plt.plot(x, s)
plt.show()
fig = plt.figure(figsize=(10, 6), dpi=80)
plt.plot(x, c, 'b-', lw=2.5)
plt.plot(x, s, 'r-', lw=2.5)
#这里增加了两个参数,'b-' 是 `color="blue",linestyle="-"`的简写形式
#'lw'是'linewidth', 线宽的简写形式
plt.show()
plt.xlim(x.min()*1.1, x.max()*1.1)
plt.ylim(c.min()*1.1, c.max()*1.1)
#这里plt.xlim 和 plt.ylim 分别是 x_limit 和 y_limit
#这个方法用来调整x, y 轴的最大高度,两个参数分别是上限和下限
fig
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, 1])
#这里的两个方法xticks, yticks可以修改坐标的标签
#传入一个list对象,坐标轴将只显示list中给出的坐标
fig
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$',r'$+\pi$'])
#这里的xticks方法穿了两个List 作为参数,第一个是显示的数值,第二个是这个数值对应的别名
#其中第二个参数会按照第一个参数的个数n取前n个
#第二个list的内容前后应该有'$'符号
fig
fig = plt.figure(figsize=(10, 6), dpi=80)
ax=plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#这里把右边和上边的边界设置为不可见
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
#把下边界和左边界移动到0点
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$',r'$+\pi$'])
plt.xlim(x.min()*1.1, x.max()*1.1)
plt.ylim(c.min()*1.1, c.max()*1.1)
plt.plot(x, c, 'b-',lw=2.5)
plt.plot(x, s, 'r-',lw=2.5)
fig
plt.plot(x, c, 'b-', lw=2.5, label='cosine')
plt.plot(x, s, 'r-', lw=2.5, label='sine')
plt.legend(loc='upper left')
#这里又增加了一个参数 label是线的标签
#plt.legend方法给标签设置位置 ,其中loc字段可选
'''
lower right
center right
upper right
right
upper center
lower left
lower center
center left
center
best
upper left
'''
fig
t = 2*np.pi/3
plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue') #画出需要标注的点
plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
#给这个点添加注释,下同
plt.plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.sin(t),], 50, color ='red')
plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
#annotate 参数中比较需要注意的一点就是数学表达式的书写
fig
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='w', edgecolor='None',alpha=0.4))
fig
```
| github_jupyter |
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-59152712-8');
</script>
# [Brill-Lindquist](https://journals.aps.org/pr/abstract/10.1103/PhysRev.131.471) Initial data
## Author: Zach Etienne
### Formatting improvements courtesy Brandon Clark
<font color='green'>**This module has been validated to exhibit convergence to zero of the Hamiltonian constraint violation at the expected order to the exact solution (see plot at bottom of [the exact initial data validation start-to-finish tutorial notebook](Tutorial-Start_to_Finish-BSSNCurvilinear-Setting_up_Exact_Initial_Data.ipynb); momentum constraint is zero), and all quantities have been validated against the [original SENR code](https://bitbucket.org/zach_etienne/nrpy).**</font>
### NRPy+ Source Code for this module: [BrillLindquist.py](../edit/BSSN/BrillLindquist.py)
## Introduction:
This module sets up initial data for a merging black hole system in Cartesian coordinates.
<a id='toc'></a>
# Table of Contents
$$\label{toc}$$
This notebook is organized as follows
1. [Step 1](#initializenrpy): Initialize core Python/NRPy+ modules
1. [Step 2](#initialdata): Setting up Brill-Lindquist initial data
1. [Step 3](#code_validation): Code Validation against BSSN/BrillLindquist NRPy+ module
1. [Step 4](#latex_pdf_output): Output this notebook to $\LaTeX$-formatted PDF file
<a id='initializenrpy'></a>
# Step 1: Initialize core Python/NRPy+ modules \[Back to [top](#toc)\]
$$\label{initializenrpy}$$
Let's start by importing all the needed modules from Python/NRPy+:
```
# Step 1: Initialize core Python/NRPy+ modules
import sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends
import NRPy_param_funcs as par # NRPy+: Parameter interface
import indexedexp as ixp # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
```
<a id='initialdata'></a>
# Step 2: Setting up Brill-Lindquist initial data \[Back to [top](#toc)\]
$$\label{initialdata}$$
Here we set up Brill-Lindquist initial data ([Brill & Lindquist, Phys. Rev. 131, 471, 1963](https://journals.aps.org/pr/abstract/10.1103/PhysRev.131.471); see also Eq. 1 of [Brandt & Brügmann, arXiv:gr-qc/9711015v1](https://arxiv.org/pdf/gr-qc/9711015v1.pdf)):
The conformal factor $\psi$ for Brill-Lindquist initial data is given by
$$\psi = e^{\phi} = 1 + \sum_{i=1}^N \frac{m_{(i)}}{2 \left|\vec{r}_{(i)} - \vec{r}\right|};\quad K_{ij}=0,$$
where $\psi$ is written in terms of the 3-metric $\gamma_{ij}$ as
$$
\gamma_{ij} = \psi^4 \delta_{ij}.
$$
The extrinsic curvature is zero:
$$
K_{ij} = 0
$$
These data consist of $N$ nonspinning black holes initially at rest. This module restricts to the case of two such black holes, positioned anywhere. Here, we implement $N=2$.
**Inputs for $\psi$**:
* The position and (bare) mass of black hole 1: $\left(x_{(1)},y_{(1)},z_{(1)}\right)$ and $m_{(1)}$, respectively
* The position and (bare) mass of black hole 2: $\left(x_{(2)},y_{(2)},z_{(2)}\right)$ and $m_{(2)}$, respectively
**Additional variables needed for spacetime evolution**:
* Desired coordinate system
* Desired initial lapse $\alpha$ and shift $\beta^i$. We will choose our gauge conditions as $\alpha=\psi^{-2}$ and $\beta^i=B^i=0$.
```
# Step 2: Setting up Brill-Lindquist initial data
thismodule = "Brill-Lindquist"
BH1_posn_x,BH1_posn_y,BH1_posn_z = par.Cparameters("REAL", thismodule,
["BH1_posn_x","BH1_posn_y","BH1_posn_z"],
[ 0.0, 0.0, +0.5])
BH1_mass = par.Cparameters("REAL", thismodule, ["BH1_mass"],1.0)
BH2_posn_x,BH2_posn_y,BH2_posn_z = par.Cparameters("REAL", thismodule,
["BH2_posn_x","BH2_posn_y","BH2_posn_z"],
[ 0.0, 0.0, -0.5])
BH2_mass = par.Cparameters("REAL", thismodule, ["BH2_mass"],1.0)
# Step 2.a: Set spatial dimension (must be 3 for BSSN)
DIM = 3
par.set_parval_from_str("grid::DIM",DIM)
Cartxyz = ixp.declarerank1("Cartxyz")
# Step 2.b: Set psi, the conformal factor:
psi = sp.sympify(1)
psi += BH1_mass / ( 2 * sp.sqrt((Cartxyz[0]-BH1_posn_x)**2 + (Cartxyz[1]-BH1_posn_y)**2 + (Cartxyz[2]-BH1_posn_z)**2) )
psi += BH2_mass / ( 2 * sp.sqrt((Cartxyz[0]-BH2_posn_x)**2 + (Cartxyz[1]-BH2_posn_y)**2 + (Cartxyz[2]-BH2_posn_z)**2) )
# Step 2.c: Set all needed ADM variables in Cartesian coordinates
gammaCartDD = ixp.zerorank2()
KCartDD = ixp.zerorank2() # K_{ij} = 0 for these initial data
for i in range(DIM):
gammaCartDD[i][i] = psi**4
alphaCart = 1/psi**2
betaCartU = ixp.zerorank1() # We generally choose \beta^i = 0 for these initial data
BCartU = ixp.zerorank1() # We generally choose B^i = 0 for these initial data
```
<a id='code_validation'></a>
# Step 3: Code Validation against BSSN/BrillLindquist NRPy+ module \[Back to [top](#toc)\]
$$\label{code_validation}$$
Here, as a code validation check, we verify agreement in the SymPy expressions for Brill-Lindquist initial data between
1. this tutorial and
2. the NRPy+ [BSSN/BrillLindquist.py](../edit/BSSN/BrillLindquist.py) module.
```
# Step 3: Code Validation against BSSN.BrillLindquist NRPy+ module
# First we import reference_metric, which is
# needed since BSSN.BrillLindquist calls
# BSSN.ADM_Exact_Spherical_or_Cartesian_to_BSSNCurvilinear, which
# depends on reference_metric:
import reference_metric as rfm # NRPy+: Reference metric support
rfm.reference_metric()
import BSSN.BrillLindquist as bl
bl.BrillLindquist()
print("Consistency check between Brill-Lindquist tutorial and NRPy+ BSSN.BrillLindquist module. ALL SHOULD BE ZERO.")
print("alphaCart - bl.alphaCart = "+str(sp.simplify(alphaCart - bl.alphaCart)))
for i in range(DIM):
print("betaCartU["+str(i)+"] - bl.betaCartU["+str(i)+"] = "+\
str(sp.simplify(betaCartU[i] - bl.betaCartU[i])))
print("BCartU["+str(i)+"] - bl.BaCartU["+str(i)+"] = "+str(sp.simplify(BCartU[i] - bl.BCartU[i])))
for j in range(DIM):
print("gammaCartDD["+str(i)+"]["+str(j)+"] - bl.gammaCartDD["+str(i)+"]["+str(j)+"] = "+\
str(sp.simplify(gammaCartDD[i][j] - bl.gammaCartDD[i][j])))
print("KCartDD["+str(i)+"]["+str(j)+"] - bl.KCartDD["+str(i)+"]["+str(j)+"] = "+\
str(sp.simplify(KCartDD[i][j] - bl.KCartDD[i][j])))
```
<a id='latex_pdf_output'></a>
# Step 4: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](#toc)\]
$$\label{latex_pdf_output}$$
The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename
[Tutorial-ADM_Initial_Data-Brill-Lindquist](Tutorial-ADM_Initial_Data-Brill-Lindquist.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.)
```
import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface
cmd.output_Jupyter_notebook_to_LaTeXed_PDF("Tutorial-ADM_Initial_Data-Brill-Lindquist")
```
| github_jupyter |
```
## Financial timeseries data
# Import pandas as pd
import pandas as pd
# Read in the csv file and parse dates
StockPrices = pd.read_csv(fpath_csv, parse_dates=['Date'])
# Ensure the prices are sorted by Date
StockPrices = StockPrices.sort_values(by='Date')
# Print only the first five rows of StockPrices
print(StockPrices.head())
## Calculating financial returns
# Calculate the daily returns of the adjusted close price
StockPrices['Returns'] = StockPrices['Adjusted'].pct_change()
# Check the first five rows of StockPrices
print(StockPrices.head())
# Plot the returns column over time
StockPrices['Returns'].plot()
plt.show()
## Return distributions
# Convert the decimal returns into percentage returns
percent_return = StockPrices['Returns']*100
# Drop the missing values
returns_plot = percent_return.dropna()
# Plot the returns histogram
plt.hist(returns_plot, bins=75)
plt.show()
Average Annualized Return = ((1 + μ) ^ 252) − 1
## First moment: Mu
# Import numpy as np
import numpy as np
# Calculate the average daily return of the stock
mean_return_daily = np.mean(StockPrices['Returns'])
print(mean_return_daily)
# Calculate the implied annualized average return
mean_return_annualized = ((1+mean_return_daily)**252)-1
print(mean_return_annualized)
# <script.py> output:
# 0.0003777754643575774
# 0.09985839482858783
## The average daily return of the stock (mu) is 0.04% per day.
## This works out to an annualized return of 9.99% per year.
## Second moment: Variance
# Calculate the standard deviation of daily return of the stock
sigma_daily = np.std(StockPrices['Returns'])
print(sigma_daily)
# Calculate the daily variance
variance_daily = sigma_daily**2
print(variance_daily)
# <script.py> output:
# 0.019341100408708317
# 0.00037407816501973704
# The average daily volatility of the stock (sigma) is 1.93% per day.
# The average daily variance of the stock (the second moment) is 0.04%.
## Annualizing variance
# Annualize the standard deviation
sigma_annualized = sigma_daily*np.sqrt(252)
print(sigma_annualized)
# Calculate the annualized variance
variance_annualized = sigma_annualized**2
print(variance_annualized)
# <script.py> output:
# 0.3070304505826315
# 0.09426769758497373
# This works out to an annualized volatility (sigma) of 30.7% per year.
# And an annualized variance of 9.43% per year
## Third moment: Skewness
# Import skew from scipy.stats
from scipy.stats import skew
# Drop the missing values
clean_returns = StockPrices['Returns'].dropna()
# Calculate the third moment (skewness) of the returns distribution
returns_skewness = skew(clean_returns)
print(returns_skewness)
## Fourth moment: Kurtosis
# Import kurtosis from scipy.stats
from scipy.stats import kurtosis
# Calculate the excess kurtosis of the returns distribution
excess_kurtosis = kurtosis(clean_returns)
print(excess_kurtosis)
# Derive the true fourth moment of the returns distribution
fourth_moment = excess_kurtosis+3
print(fourth_moment)
## Statistical tests for normality
# Import shapiro from scipy.stats
from scipy.stats import shapiro
# Run the Shapiro-Wilk test on the stock returns
shapiro_results = shapiro(clean_returns)
print("Shapiro results:", shapiro_results)
# Extract the p-value from the shapiro_results
p_value = shapiro_results[1]
print("P-value: ", p_value)
# <script.py> output:
# Shapiro results: (0.9003633260726929, 0.0)
# P-value: 0.0
# The p-value is 0, so null hypothesis of normality is rejected. The data are non-normal.
```
```
## Calculating portfolio returns
# Finish defining the portfolio weights as a numpy array
portfolio_weights = np.array([0.12, 0.15, 0.08, 0.05, 0.09, 0.10, 0.11, 0.14, 0.16])
# Calculate the weighted stock returns
WeightedReturns = StockReturns.mul(portfolio_weights, axis=1)
# Calculate the portfolio returns
StockReturns['Portfolio'] = WeightedReturns.sum(axis=1)
# Plot the cumulative portfolio returns over time
CumulativeReturns = ((1+StockReturns["Portfolio"]).cumprod()-1)
CumulativeReturns.plot()
plt.show()
## Equal weighted portfolios
# How many stocks are in your portfolio?
numstocks = 9
# Create an array of equal weights across all assets
portfolio_weights_ew = np.repeat(1/numstocks, numstocks)
# Calculate the equally-weighted portfolio returns
StockReturns['Portfolio_EW'] = StockReturns.iloc[:, 0:numstocks].mul(portfolio_weights_ew, axis=1).sum(axis=1)
cumulative_returns_plot(['Portfolio', 'Portfolio_EW'])
## Market-cap weighted portfolios
# Create an array of market capitalizations (in billions)
market_capitalizations = np.array([601.51, 469.25, 349.5, 310.48, 299.77, 356.94, 268.88, 331.57, 246.09])
# Calculate the market cap weights
mcap_weights = market_capitalizations / sum(market_capitalizations)
# Calculate the market cap weighted portfolio returns
StockReturns['Portfolio_MCap'] = StockReturns.iloc[:, 0:9].mul(mcap_weights, axis=1).sum(axis=1)
cumulative_returns_plot(['Portfolio', 'Portfolio_EW', 'Portfolio_MCap'])
## The correlation matrix
# Calculate the correlation matrix
correlation_matrix = StockReturns.corr()
# Print the correlation matrix
print(correlation_matrix)
_____________________________________________
# Import seaborn as sns
import seaborn as sns
# Create a heatmap
sns.heatmap(correlation_matrix,
annot=True,
cmap="YlGnBu",
linewidths=0.3,
annot_kws={"size": 8})
# Plot aesthetics
plt.xticks(rotation=90)
plt.yticks(rotation=0)
plt.show()
## The co-variance matrix
# Calculate the covariance matrix
cov_mat = StockReturns.cov()
# Annualize the co-variance matrix
cov_mat_annual = cov_mat*252
# Print the annualized co-variance matrix
print(cov_mat_annual)
## Portfolio standard deviation
# Import numpy as np
import numpy as np
# Calculate the portfolio standard deviation
portfolio_volatility = np.sqrt(np.dot(portfolio_weights.T,
np.dot(cov_mat_annual,
portfolio_weights)))
print(portfolio_volatility)
```
```
## Sharpe ratios
# Risk free rate
risk_free = 0
# Calculate the Sharpe Ratio for each asset
RandomPortfolios['Sharpe'] = (RandomPortfolios['Returns'] - risk_free) / RandomPortfolios['Volatility']
# Print the range of Sharpe ratios
print(RandomPortfolios['Sharpe'].describe()[['min', 'max']])
# <script.py> output:
# min 0.742884
# max 2.270462
# Name: Sharpe, dtype: float64
## The MSR portfolio (maximum Sharpe ratio or MSR)
# Sort the portfolios by Sharpe ratio
sorted_portfolios = RandomPortfolios.sort_values(by=['Sharpe'], ascending=False)
# Extract the corresponding weights
MSR_weights = sorted_portfolios.iloc[0, 0:numstocks]
# Cast the MSR weights as a numpy array
MSR_weights_array = np.array(MSR_weights)
# Calculate the MSR portfolio returns
StockReturns['Portfolio_MSR'] = StockReturns.iloc[:, 0:numstocks].mul(MSR_weights_array, axis=1).sum(axis=1)
# Plot the cumulative returns
cumulative_returns_plot(['Portfolio_EW', 'Portfolio_MCap', 'Portfolio_MSR'])
## The GMV portfolio (global minimum volatility portfolio or GMV)
# Sort the portfolios by volatility
sorted_portfolios = RandomPortfolios.sort_values(by=['Volatility'], ascending=True)
# Extract the corresponding weights
GMV_weights = sorted_portfolios.iloc[0, 0:numstocks]
# Cast the GMV weights as a numpy array
GMV_weights_array = np.array(GMV_weights)
# Calculate the GMV portfolio returns
StockReturns['Portfolio_GMV'] = StockReturns.iloc[:, 0:numstocks].mul(GMV_weights_array, axis=1).sum(axis=1)
# Plot the cumulative returns
cumulative_returns_plot(['Portfolio_EW', 'Portfolio_MCap',
'Portfolio_MSR', 'Portfolio_GMV'])
```
```
## Excess returns
# Calculate excess portfolio returns
FamaFrenchData['Portfolio_Excess'] = FamaFrenchData['Portfolio'] - FamaFrenchData['RF']
# Plot returns vs excess returns
CumulativeReturns = ((1+FamaFrenchData[['Portfolio','Portfolio_Excess']]).cumprod()-1)
CumulativeReturns.plot()
plt.show()
## Calculating beta using co-variance
# Calculate the co-variance matrix between Portfolio_Excess and Market_Excess
covariance_matrix = FamaFrenchData[['Portfolio_Excess', 'Market_Excess']].cov()
# Extract the co-variance co-efficient
covariance_coefficient = covariance_matrix.iloc[0, 1]
print(covariance_coefficient)
# Calculate the benchmark variance
benchmark_variance = FamaFrenchData['Market_Excess'].var()
print(benchmark_variance)
# Calculating the portfolio market beta
portfolio_beta = covariance_coefficient / benchmark_variance
print(portfolio_beta)
# Portfolio_Excess Market_Excess
# Portfolio_Excess 1.225759 1.000000
# Market_Excess 1.000000 1.026931
# <script.py> output:
# 5.7261263381549724e-05
# 5.880335088211895e-05
# 0.973775516574547
## Calculating beta with CAPM (Capital Asset Pricing Model) ##
E(RP)−RF=βP(E(RM)−RF)
E(RP)−RF: The excess expected return of a stock or portfolio P
E(RM)−RF: The excess expected return of the broad market portfolio B
RF: The regional risk free-rate
βP: Portfolio beta, or exposure, to the broad market portfolio B
## Calculating beta with CAPM
# Import statsmodels.formula.api
import statsmodels.formula.api as smf
# Define the regression formula
CAPM_model = smf.ols(formula='Portfolio_Excess ~ Market_Excess', data=FamaFrenchData)
# Print adjusted r-squared of the fitted regression
CAPM_fit = CAPM_model.fit()
print(CAPM_fit.rsquared_adj)
# Extract the beta
regression_beta = CAPM_fit.params['Market_Excess']
print(regression_beta)
```
```
The Fama-French model famously adds two additional factors to the CAPM model to describe asset returns:
RP = RF + βM(RM − RF) + bSMB*SMB + bHML*HML + α
SMB: The small minus big factor
bSMB: Exposure to the SMB factor
HML: The high minus low factor
bHML: Exposure to the HML factor
α: Performance which is unexplained by any other factors
βM: Beta to the broad market portfolio B
## The Fama French 3-factor model
# Import statsmodels.formula.api
import statsmodels.formula.api as smf
# Define the regression formula
FamaFrench_model = smf.ols(formula='Portfolio_Excess ~ Market_Excess + SMB + HML', data=FamaFrenchData)
# Fit the regression
FamaFrench_fit = FamaFrench_model.fit()
# Extract the adjusted r-squared
regression_adj_rsq = FamaFrench_fit.rsquared_adj
print(regression_adj_rsq)
## p-values and coefficients
# Extract the p-value of the SMB factor
smb_pval = FamaFrench_fit.pvalues['SMB']
# If the p-value is significant, print significant
if smb_pval < 0.05:
significant_msg = 'significant'
else:
significant_msg = 'not significant'
# Print the SMB coefficient
smb_coeff = FamaFrench_fit.params['SMB']
print("The SMB coefficient is ", smb_coeff, " and is ", significant_msg)
## <script.py> output:
## The SMB coefficient is -0.2621515274319268 and is significant
## The efficient market and alpha
# Calculate your portfolio alpha
portfolio_alpha = FamaFrench_fit.params['Intercept']
print(portfolio_alpha)
# Annualize your portfolio alpha
portfolio_alpha_annualized = ((1+portfolio_alpha)**252)-1
print(portfolio_alpha_annualized)
## The 5-factor model
# Import statsmodels.formula.api
import statsmodels.formula.api as smf
# Define the regression formula
FamaFrench5_model = smf.ols(formula='Portfolio_Excess ~ Market_Excess + SMB + HML + RMW + CMA', data=FamaFrenchData)
# Fit the regression
FamaFrench5_fit = FamaFrench5_model.fit()
# Extract the adjusted r-squared
regression_adj_rsq = FamaFrench5_fit.rsquared_adj
print(regression_adj_rsq)
## Historical drawdown
# Calculate the running maximum
running_max = np.maximum.accumulate(cum_rets)
# Ensure the value never drops below 1
running_max[running_max < 1] = 1
# Calculate the percentage drawdown
drawdown = (cum_rets)/running_max - 1
# Plot the results
drawdown.plot()
plt.show()
## Historical value at risk
# Calculate historical VaR(95)
var_95 = np.percentile(StockReturns_perc, 5 )
print(var_95)
# Sort the returns for plotting
sorted_rets = StockReturns_perc.sort_values(ascending=True)
# Plot the probability of each sorted return quantile
plt.hist(sorted_rets, normed=True)
# Denote the VaR 95 quantile
plt.axvline(x=var_95, color='r', linestyle='-', label="VaR 95: {0:.2f}%".format(var_95))
plt.show()
## Historical expected shortfall
# Historical CVaR 95
cvar_95 = StockReturns_perc[StockReturns_perc <= var_95].mean()
print(cvar_95)
# Sort the returns for plotting
sorted_rets = sorted(StockReturns_perc)
# Plot the probability of each return quantile
plt.hist(sorted_rets, normed=True)
# Denote the VaR 95 and CVaR 95 quantiles
plt.axvline(x=var_95, color="r", linestyle="-",
label='VaR 95: {0:.2f}%'.format(var_95))
plt.axvline(x=cvar_95, color='b', linestyle='-',
label='CVaR 95: {0:.2f}%'.format(cvar_95))
plt.show()
## Changing VaR and CVaR quantiles
# Historical VaR(90) quantiles
var_90 = np.percentile(StockReturns_perc, 10)
print(var_90)
# Historical CVaR(90) quantiles
cvar_90 = StockReturns_perc[StockReturns_perc <= var_90].mean()
print(cvar_90)
# Plot to compare
plot_hist()
## Parametric VaR
# Import norm from scipy.stats
from scipy.stats import norm
# Estimate the average daily return
mu = np.mean(StockReturns)
# Estimate the daily volatility
vol = np.std(StockReturns)
# Set the VaR confidence level
confidence_level = .05
# Calculate Parametric VaR
var_95 = norm.ppf(confidence_level, mu, vol)
print('Mean: ', str(mu), '\nVolatility: ', str(vol), '\nVaR(95): ', str(var_95))
# <script.py> output:
# Mean: -0.0002863895624021478
# Volatility: 0.02188808712970886
# VaR(95): -0.03628908906473362
## Scaling risk estimates
# Aggregate forecasted VaR
forecasted_values = np.empty([100, 2])
# Loop through each forecast period
for i in range(100):
# Save the time horizon i
forecasted_values[i, 0] = i
# Save the forecasted VaR 95
forecasted_values[i, 1] = var_95*np.sqrt(i+1)
# Plot the results
plot_var_scale()
## A random walk simulation
# Set the simulation parameters
mu = np.mean(StockReturns)
vol = np.std(StockReturns)
T = 252
S0 = 10
# Add one to the random returns
rand_rets = np.random.normal(mu, vol, T) + 1
# Forecasted random walk
forecasted_values = S0*rand_rets.cumprod()
# Plot the random walk
plt.plot(range(0, T), forecasted_values)
plt.show()
## Monte Carlo simulations
# Loop through 100 simulations
for i in range(100):
# Generate the random returns
rand_rets = np.random.normal(mu, vol, T) + 1
# Create the Monte carlo path
forecasted_values = S0*(rand_rets).cumprod()
# Plot the Monte Carlo path
plt.plot(range(T), forecasted_values)
# Show the simulations
plt.show()
## Monte Carlo VaR
# Aggregate the returns
sim_returns = []
# Loop through 100 simulations
for i in range(100):
# Generate the Random Walk
rand_rets = np.random.normal(mu, vol, T)
# Save the results
sim_returns.append(rand_rets)
# Calculate the VaR(99)
var_99 = np.percentile(sim_returns, 1)
print("Parametric VaR(99): ", round(100*var_99, 2),"%")
```
| github_jupyter |
```
import pandas as pd
from scipy.stats.stats import pearsonr
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="white")
dff = pd.read_csv('./results/results.csv')
dff = dff.set_index('model')
dff.index
col = 'etc_rmse'
v = dff[col].apply(lambda x:float(x.split('±')[0]))
err = dff[col].apply(lambda x:float(x.split('±')[1]))
dfb = v.to_frame(name = col).join(err.to_frame(name = 'err'))
dfb.index.name = 'model'
dfb = dfb.reset_index()
dfb = dfb.sort_values(col)
col1 = 'etc_pcc'
v1 = dff[col1].apply(lambda x:float(x.split('±')[0]))
err1 = dff[col1].apply(lambda x:float(x.split('±')[1]))
dfp = v1.to_frame(name = col1).join(err1.to_frame(name = 'err'))
dfp.index.name = 'model'
dfp = dfp.reset_index()
dfp = dfp.sort_values(col1, ascending = False)
colors = sns.color_palette("rainbow", len(dfb)).as_hex()
f, (ax1, ax2) = plt.subplots(1,2,figsize=(16,6))
dfb.plot(kind='bar',x="model", y= col, yerr= 'err', color = colors, ax = ax1,capsize=10, edgecolor='black', error_kw=dict(ecolor='black',elinewidth=0.5),width=0.8)
dfp.plot(kind='bar',x="model", y= col1, yerr= 'err', color = colors, ax = ax2, capsize=10, edgecolor='black', error_kw=dict(ecolor='black',elinewidth=0.5),width=0.8)
_ = ax1.set_xticklabels(
ax1.get_xticklabels(),
rotation=45,
horizontalalignment='right')
_ = ax2.set_xticklabels(
ax2.get_xticklabels(),
rotation=45,
horizontalalignment='right')
ax1.set_ylabel('Root Mean Squared Error')
ax2.set_ylabel('Pearson Correlation Coefficient')
plt.savefig('./results/prediction_on_etc_data.png', bbox_inches="tight", dpi = 300)
col = 'test_rmse'
v = dff[col].apply(lambda x:float(x.split('±')[0]))
err = dff[col].apply(lambda x:float(x.split('±')[1]))
dfb = v.to_frame(name = col).join(err.to_frame(name = 'err'))
dfb.index.name = 'model'
dfb = dfb.reset_index()
dfb = dfb.sort_values(col)
col1 = 'test_pcc'
v1 = dff[col1].apply(lambda x:float(x.split('±')[0]))
err1 = dff[col1].apply(lambda x:float(x.split('±')[1]))
dfp = v1.to_frame(name = col1).join(err1.to_frame(name = 'err'))
dfp.index.name = 'model'
dfp = dfp.reset_index()
dfp = dfp.sort_values(col1, ascending = False)
colors = sns.color_palette("rainbow", len(dfb)).as_hex()
f, (ax1, ax2) = plt.subplots(1,2,figsize=(16,6))
dfb.plot(kind='bar',x="model", y= col, yerr= 'err', color = colors, ax = ax1,capsize=10, edgecolor='black', error_kw=dict(ecolor='black',elinewidth=0.5),width=0.8)
dfp.plot(kind='bar',x="model", y= col1, yerr= 'err', color = colors, ax = ax2, capsize=10, edgecolor='black', error_kw=dict(ecolor='black',elinewidth=0.5),width=0.8)
_ = ax1.set_xticklabels(
ax1.get_xticklabels(),
rotation=45,
horizontalalignment='right')
_ = ax2.set_xticklabels(
ax2.get_xticklabels(),
rotation=45,
horizontalalignment='right')
ax1.set_ylabel('Root Mean Squared Error')
ax2.set_ylabel('Pearson Correlation Coefficient')
plt.savefig('./results/prediction_on_test_data.png', bbox_inches="tight", dpi = 300)
col = 'valid_rmse'
v = dff[col].apply(lambda x:float(x.split('±')[0]))
err = dff[col].apply(lambda x:float(x.split('±')[1]))
dfb = v.to_frame(name = col).join(err.to_frame(name = 'err'))
dfb.index.name = 'model'
dfb = dfb.reset_index()
dfb = dfb.sort_values(col)
col1 = 'valid_pcc'
v1 = dff[col1].apply(lambda x:float(x.split('±')[0]))
err1 = dff[col1].apply(lambda x:float(x.split('±')[1]))
dfp = v1.to_frame(name = col1).join(err1.to_frame(name = 'err'))
dfp.index.name = 'model'
dfp = dfp.reset_index()
dfp = dfp.sort_values(col1, ascending = False)
colors = sns.color_palette("rainbow", len(dfb)).as_hex()
f, (ax1, ax2) = plt.subplots(1,2,figsize=(16,6))
dfb.plot(kind='bar',x="model", y= col, yerr= 'err', color = colors, ax = ax1,capsize=10, edgecolor='black', error_kw=dict(ecolor='black',elinewidth=0.5),width=0.8)
dfp.plot(kind='bar',x="model", y= col1, yerr= 'err', color = colors, ax = ax2, capsize=10, edgecolor='black', error_kw=dict(ecolor='black',elinewidth=0.5),width=0.8)
_ = ax1.set_xticklabels(
ax1.get_xticklabels(),
rotation=45,
horizontalalignment='right')
_ = ax2.set_xticklabels(
ax2.get_xticklabels(),
rotation=45,
horizontalalignment='right')
ax1.set_ylabel('Root Mean Squared Error')
ax2.set_ylabel('Pearson Correlation Coefficient')
plt.savefig('./results/prediction_on_valid_data.png', bbox_inches="tight", dpi = 300)
col = 'train_rmse'
v = dff[col].apply(lambda x:float(x.split('±')[0]))
err = dff[col].apply(lambda x:float(x.split('±')[1]))
dfb = v.to_frame(name = col).join(err.to_frame(name = 'err'))
dfb.index.name = 'model'
dfb = dfb.reset_index()
dfb = dfb.sort_values(col)
col1 = 'train_pcc'
v1 = dff[col1].apply(lambda x:float(x.split('±')[0]))
err1 = dff[col1].apply(lambda x:float(x.split('±')[1]))
dfp = v1.to_frame(name = col1).join(err1.to_frame(name = 'err'))
dfp.index.name = 'model'
dfp = dfp.reset_index()
dfp = dfp.sort_values(col1, ascending = False)
colors = sns.color_palette("rainbow", len(dfb)).as_hex()
f, (ax1, ax2) = plt.subplots(1,2,figsize=(16,6))
dfb.plot(kind='bar',x="model", y= col, yerr= 'err', color = colors, ax = ax1,capsize=10, edgecolor='black', error_kw=dict(ecolor='black',elinewidth=0.5),width=0.8)
dfp.plot(kind='bar',x="model", y= col1, yerr= 'err', color = colors, ax = ax2, capsize=10, edgecolor='black', error_kw=dict(ecolor='black',elinewidth=0.5),width=0.8)
_ = ax1.set_xticklabels(
ax1.get_xticklabels(),
rotation=45,
horizontalalignment='right')
_ = ax2.set_xticklabels(
ax2.get_xticklabels(),
rotation=45,
horizontalalignment='right')
ax1.set_ylabel('Root Mean Squared Error')
ax2.set_ylabel('Pearson Correlation Coefficient')
plt.savefig('./results/prediction_on_train_data.png', bbox_inches="tight", dpi = 300)
df_etc_pred = pd.read_csv('./etc_pred.csv', index_col = 0)
idxs = df_etc_pred.corr()['Exp_LogS'][1:].sort_values(ascending = False).index
# colors = sns.color_palette("rainbow", len(idxs)).as_hex()
# color_dict = dict(zip(idxs,colors))
for i in idxs:
#color = color_dict.get(i)
jg = sns.jointplot('Exp_LogS', i, data=df_etc_pred, kind="reg", stat_func = pearsonr)
jg.fig.savefig('./results/000_%s_etc_scatter.png' % i, dpi = 300, bbox_inches="tight")
df_etc_pred = df_etc_pred.rename(columns={'MolMapNet':'MolMapNet-D'})
dfcorr = df_etc_pred.corr().sort_values('Exp_LogS', ascending =False).T.sort_values('Exp_LogS', ascending =False)
f, ax = plt.subplots(1,1,figsize=(10,8))
sns.heatmap(dfcorr, cmap = 'rainbow', annot = True,fmt='.3g', ax = ax)
plt.savefig('./results/etc_pred_corr.png', bbox_inches="tight", dpi = 300)
```
| github_jupyter |
# IHA1 - Assignment
Welcome to the first individual home assignment!
This assignment consists of two parts:
* Python and NumPy exercises
* Build a deep neural network for forward propagation
The focus of this assignment is for you to gain practical knowledge with implementing forward propagation of deep neural networks without using any deep learning framework. You will also gain practical knowledge in two of Python's scientific libraries [NumPy](https://docs.scipy.org/doc/numpy-1.13.0/index.html) and [Matplotlib](https://matplotlib.org/devdocs/index.html).
Skeleton code is provided for most tasks and every part you are expected to implement is marked with **TODO**
We expect you to search and learn by yourself any commands you think are useful for these tasks. Don't limit yourself to only what was taught in CL1. Use the help function, [stackoverflow](https://stackoverflow.com/), google, the [python documentation](https://docs.python.org/3.5/library/index.html) and the [NumPy](https://docs.scipy.org/doc/numpy-1.13.0/index.html) documentation to your advantage.
**IMPORTANT NOTE**: The tests available are not exhaustive, meaning that if you pass a test you have avoided the most common mistakes, but it is still not guaranteed that you solution is 100% correct.
Lets start by importing the necessary libraries below
```
import numpy as np
import matplotlib.pyplot as plt
from utils.tests.iha1Tests import *
```
## 1. Lists and arrays introduction
First, we will warm up with a Python exercise and few NumPy exercises
### 1.1 List comprehensions
Examine the code snippet provided below
```
myList = []
for i in range(25):
if i % 2 == 0:
myList.append(i**2)
print(myList)
```
This is not a very "[pythonic](http://docs.python-guide.org/en/latest/writing/style/)" way of writing. Lets re-write the code above using a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions). The result will be less code, more readable and elegant. Your solution should be able to fit into one line of code.
```
myList = None # TODO
print(myList)
# sample output from cell above for reference
```
### 1.2 Numpy array vs numpy vectors
Run the cell below to create a numpy array.
```
myArr = np.array([1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529])
print(myArr)
print(myArr.shape)
```
One of the core features of numpy is to efficiently perform linear algebra operations.
There are two types of one-dimensional representations in numpy: arrays of shape (x,) and vectors of shape (x,1)
The the above result indicates that **myArr** is an array of 12 elements with shape (12,).
Numpy's arrays and vectors both have the type of `numpy.ndarray` but have in some cases different characteristics and it is important to separate the two types because it will save a lot of debugging time later on. Read more about numpy shapes [here](https://stackoverflow.com/a/22074424)
Run the code below to see how the transpose operation behaves differently between an array and vector
```
# print the shape of an array and the shape of a transposed array
print('myArr is an array of shape:')
print(myArr.shape)
print('The transpose of myArr has the shape:')
print(myArr.T.shape)
# print the shape of a vector and the transpose of a vector
myVec = myArr.reshape(12,1)
print('myVec is a vector of shape:')
print(myVec.shape)
print('The transpose of myVec has the shape:')
print(myVec.T.shape)
```
### 1.3 Numpy exercises
Now run the cell below to create the numpy array `numbers` and then complete the exercises sequentially
```
numbers = np.arange(24)
print(numbers)
# TODO: reshape numbers into a 6x4 matrix
print(numbers)
# sample output from cell above for reference
# test case
test_numpy_reshape(numbers)
# TODO: set the element of the last row of the last column to zero
# Hint: Try what happends when indices are negative
print(numbers)
# sample output from cell above for reference
# test case
test_numpy_neg_ix(numbers)
# TODO: set every element of the 0th row to 0
print(numbers)
# sample output from cell above for reference
# test case
test_numpy_row_ix(numbers)
# TODO: append a 1x4 row vector of zeros to `numbers`,
# resulting in a 7x4 matrix where the new row of zeros is the last row
# Hint: A new matrix must be created in the procedure. Numpy arrays are not dynamic.
print(numbers)
print(numbers.shape)
# sample output from cell above for reference
# test case
test_numpy_append_row(numbers)
# TODO: set all elements above 10 to the value 1
print(numbers)
# sample output from cell above for reference
# test case
test_numpy_bool_matrix(numbers)
# TODO: compute the sum of every row and replace `numbers` with the answer
# `numbers` will be a (7,) array as a result
print(numbers.shape)
print(numbers)
# sample output from cell above for reference
# test case
test_numpy_sum(numbers)
```
## 2 Building your deep neural network
It is time to start implementing your first feed-forward neural network. In this lab you will only focus on implementing the forward propagation procedure.
When using a neural network, you can not forward propagate the entire dataset at once. Therefore, you divide the dataset into a number of sets/parts called batches. A batch will make up for the first dimension of every input to a layer and the notation `(BATCH_SIZE, NUM_FEATURES)` simply means the dimension of a batch of samples where every sample has `NUM_FEATURES` features
### 2.1 activation functions
You will start by defining a few activation functions that are later needed by the neural network.
#### 2.1.1 ReLU
The neural network will use the ReLU activation function in every layer except for the last. ReLU does element-wise comparison of the input matrix. For example, if the input is `X`, and `X[i,j] == 2` and `X[k,l] == -1`, then after applying ReLU, `X[i,j] == 2` and `X[k,l] == 0` should be true.
The formula for implementing ReLU for a single neuron $i$ is:
\begin{equation}
relu(z_i) =
\begin{cases}
0, & \text{if}\ z_i \leq 0 \\
z_i, & \text{otherwise}
\end{cases}
\end{equation}
Now implement `relu` in vectorized form
```
def relu(z):
""" Implement the ReLU activation function
Arguments:
z - the input of the activation function. Has a type of `numpy.ndarray`
Returns:
a - the output of the activation function. Has a type of numpy.ndarray and the same shape as `z`
"""
a = None # TODO
return a
# test case
test_relu(relu)
```
#### 2.1.2 Sigmoid
The sigmoid activation function is common for binary classification. This is because it squashes its input to the range [0,1].
Implement the activation function `sigmoid` using the formula:
\begin{equation}
\sigma(z) = \frac{1}{1 + e^{-z}}
\end{equation}
```
def sigmoid(z):
""" Implement the sigmoid activation function
Arguments:
z - the input of the activation function. Has a type of `numpy.ndarray`
Returns:
a - the output of the activation function. Has a type of `numpy.ndarray` and the same shape as `z`
"""
a = None # TODO
return a
# test case
test_sigmoid(sigmoid)
```
#### 2.1.3 Visualization
Make a plot using matplotlib to visualize the activation functions between the input interval [-3,3]. The plot should have the following properties
* one plot should contain a visualization of both `ReLU` and `sigmoid`
* x-axis: range of values between [-3,3], **hint**: np.linspace
* y-axis: the value of the activation functions at a given input `x`
* a legend explaining which line represents which activation function
```
# TODO: make a plot of ReLU and sigmoid values in the interval [-3,3]
# sample output from cell above for reference
```
#### 2.1.4 Softmax
You will use the softmax activation function / classifier as the final layer of your neural network later in the assignment. Implement `softmax` according the the formula below. The subtraction of the maximum value is there solely to avoid overflows in a practical implementation.
\begin{equation}
softmax(z_i) = \frac{e^{z_i - max(\mathbf{z})}}{ \sum^j e^{z_j - max(\mathbf{z})}}
\end{equation}
```
def softmax(z):
""" Implement the softmax activation function
Arguments:
z - the input of the activation function, shape (BATCH_SIZE, FEATURES) and type `numpy.ndarray`
Returns:
a - the output of the activation function, shape (BATCH_SIZE, FEATURES) and type umpy.ndarray
"""
a = None # TODO
return a
# test case
test_softmax(softmax)
```
### 2.2 Initialize weights
You will implement a helper function that takes the shape of a layer as input, and returns an initialized weight matrix $\mathbf{W}$ and bias vector $\mathbf{b}$ as output. $\mathbf{W}$ should be sampled from a normal distribution of mean 0 and standard deviation 2, and $\mathbf{b}$ should be initialized to all zeros.
```
def initialize_weights(layer_shape):
""" Implement initialization of the weight matrix and biases
Arguments:
layer_shape - a tuple of length 2, type (int, int), that determines the dimensions of the weight matrix: (input_dim, output_dim)
Returns:
w - a weight matrix with dimensions of `layer_shape`, (input_dim, output_dim), that is normally distributed with
properties mu = 0, stddev = 2. Has a type of `numpy.ndarray`
b - a vector of initialized biases with shape (1,output_dim), all of value zero. Has a type of `numpy.ndarray`
"""
w = None # TODO
b = None # TODO
return w, b
# test case
test_initialize_weights(initialize_weights)
```
### 2.3 Feed-forward neural network layer module
To build a feed-forward neural network of arbitrary depth you are going to define a neural network layer as a module that can be used to stack upon eachother.
Your task is to complete the `Layer` class by following the descriptions in the comments.
Recall the formula for forward propagation of an arbitrary layer $l$:
\begin{equation}
\mathbf{a}^{[l]} = g(\mathbf{z}^{[l]}) = g(\mathbf{a}^{[l-1]}\mathbf{w}^{[l]} +\mathbf{b}^{[l]})
\end{equation}
$g$ is the activation function given by `activation_fn`, which can be relu, sigmoid or softmax.
```
class Layer:
"""
TODO: Build a class called Layer that satisfies the descriptions of the methods
Make sure to utilize the helper functions you implemented before
"""
def __init__(self, input_dim, output_dim, activation_fn=relu):
"""
Arguments:
input_dim - the number of inputs of the layer. type int
output_dim - the number of outputs of the layer. type int
activation_fn - a reference to the activation function to use. Should be `relu` as a default
possible values are the `relu`, `sigmoid` and `softmax` functions you implemented earlier.
Has the type `function`
Attributes:
w - the weight matrix of the layer, should be initialized with `initialize_weights`
and has the shape (INPUT_FEATURES, OUTPUT_FEATURES) and type `numpy.ndarray`
b - the bias vector of the layer, should be initialized with `initialize_weights`
and has the shape (1, OUTPUT_FEATURES) and type `numpy.ndarray`
activation_fn - a reference to the activation function to use.
Has the type `function`
"""
self.w, self.b = None, None # TODO
self.activation_fn = None # TODO
def forward_prop(self, a_prev):
""" Implement the forward propagation module of the neural network layer
Should use whatever activation function that `activation_fn` references to
Arguments:
a_prev - the input to the layer, which may be the data `X`, or the output from the previous layer.
a_prev has the shape of (BATCH_SIZE, INPUT_FEATURES) and the type `numpy.ndarray`
Returns:
a - the output of the layer when performing forward propagation. Has the type `numpy.ndarray`
"""
a = None # TODO
return a
# test case, be sure that you pass the previous activation function tests before running this test
test_layer(Layer, relu, sigmoid, softmax)
```
### 2.4 Logistic regression
Binary logistic regression is a classifier where classification is performed by applying the sigmoid activation function to a linear combination of input values. You will now try out your neural network layer by utilizing it as a linear combination of input values and apply the sigmoid activation function to classify a simple problem.
The cell below defines a dataset of 5 points of either class `0` or class `1`. Your assignment is to:
1. Create an instance of a `Layer` with sigmoid activation function
2. Manually tune the weights `w` and `b` of your layer
You can use `test_logistic` to visually inspect how your classifier is performing.
```
# Run this cell to create the dataset
X_s = np.array([[1, 2],
[5, 3],
[8, 8],
[7, 5],
[3, 6]])
Y_s = np.array([0,0,1,0,1])
test_logistic(X_s, Y_s)
# create an instance of layer
l = Layer(2,1,sigmoid)
# TODO: manually tune weights
l.w = None
l.b = None
# testing your choice of weights with this function
test_logistic(X_s,Y_s,l,sigmoid)
# sample output from cell above for reference
```
### 2.5 Feed-forward neural network
Now define the actual neural network class. It is an L-layer neural network, meaning that the number of layers and neurons in each layer is specified as input by the user. Once again, you will only focus on implementing the forward propagation part.
Read the descriptions in the comments and complete the todos
```
class NeuralNetwork:
"""
TODO: Implement an L-layer neural network class by utilizing the Layer module defined above
Each layer should use `relu` activation function, except for the output layer, which should use `softmax`
"""
def __init__(self, input_n, layer_dims):
"""
Arguments:
input_n - the number of inputs to the network. Should be the same as the length of a data sample
Has type int
layer_dims - a python list or tuple of the number of neurons in each layer. Layer `l` should have a weight matrix
with the shape (`layer_dims[l-1]`, `layer_dims[l]`).
`layer_dims[-1]` is the dimension of the output layer.
Layer 1 should have the dimensions (`input_n`, `layer_dims[0]`).
len(layer_dims) is the depth of the neural network
Attributes:
input_n - the number of inputs to the network. Has type int
layers - a python list of each layer in the network. Each layer should use the `relu` activation function,
except for the last layer, which should use `softmax`.
Has type `list` containing layers of type `Layer`
"""
self.input_n = None # TODO
self.layers = None # TODO
def forward_prop(self, x):
"""
Implement the forward propagation procedure through the entire network, from input to output.
You will now connect each layer's forward propagation function into a chain of layer-wise forward propagations.
Arguments:
x - the input data, which has the shape (BATCH_SIZE, NUM_FEATURES) and type `numpy.ndarray`
Returns:
a - the output of the last layer after forward propagating through the every layer in `layers`.
Should have the dimension (BATCH_SIZE, layers[-1].w.shape[1]) and type `numpy.ndarray`
"""
a = None # TODO
return a
# test case
test_neuralnetwork(NeuralNetwork)
```
## 3 Making predictions with a neural network
In practice, its common to load weights to your neural network that has already been trained.
In this section, you will create an instance of your neural network, load trained weights from disk, and perform predictions.
### 3.1 Load weights from disk
Create an instance of `NeuralNetwork` with input size $28 \times 28 = 784$, two hidden layers of size 100 and an output layer of size 10. Thereafter, load the weights contained in `./utils/ann_weights.npz` to your network.
```
ann = None # TODO: create instance of ann
# load weights
weights = np.load('./utils/ann_weights.npz')
for l in range(len(ann.layers)):
ann.layers[l].w = weights['w' + str(l)]
ann.layers[l].b = weights['b' + str(l)]
```
### 3.2 Prediction
Now, implement the function `predict_and_correct` which does the following:
1. Load `./utils/test_data.npz` from disk
2. Extract test data `X` and `Y` from file
2. Perform for every pair of data:
a. plot the image `x`
b. make a prediction using your neural network by forward propagating and picking the most probable class
c. check wether the prediction is correct (compare with the ground truth number `y`)
d. print the predicted label and wether it was correct or not
```
def predict_and_correct(ann):
""" Load test data from file and predict using your neural network.
Make a prediction for ever data sample and print it along with wether it was a correct prediction or not
Arguments:
ann - the neural network to use for prediction. Has type `NeuralNetwork`
Returns: # for test case purposes
A `numpy.ndarray` of predicted classes (integers [0-9]) with shape (11,)
"""
data = np.load('./utils/test_data.npz')
X, cls = data['X'], data['Y']
cls_preds = None # TODO: make a predicted number for every image in X
for i in range(len(X)):
plt.imshow(X[i].reshape(28,28), cmap='gray')
plt.show()
correct = cls_preds[i] == cls[i]
print('The prediction was {0}, it was {1}!'.format(cls_preds[i], 'correct' if correct else 'incorrect'))
return cls_preds
cls_pred = predict_and_correct(ann)
# final test case
test_predict_and_correct_answer(cls_pred)
# sample output from cell above for reference
```
## Congratulations!
You have successfully implemented a neural network from scratch using only NumPy!
| github_jupyter |
```
import numpy as np
import tensorflow as tf
from sklearn.utils import shuffle
import re
import time
import collections
import os
def build_dataset(words, n_words, atleast=1):
count = [['GO', 0], ['PAD', 1], ['EOS', 2], ['UNK', 3]]
counter = collections.Counter(words).most_common(n_words)
counter = [i for i in counter if i[1] >= atleast]
count.extend(counter)
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
index = dictionary.get(word, 0)
if index == 0:
unk_count += 1
data.append(index)
count[0][1] = unk_count
reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reversed_dictionary
lines = open('movie_lines.txt', encoding='utf-8', errors='ignore').read().split('\n')
conv_lines = open('movie_conversations.txt', encoding='utf-8', errors='ignore').read().split('\n')
id2line = {}
for line in lines:
_line = line.split(' +++$+++ ')
if len(_line) == 5:
id2line[_line[0]] = _line[4]
convs = [ ]
for line in conv_lines[:-1]:
_line = line.split(' +++$+++ ')[-1][1:-1].replace("'","").replace(" ","")
convs.append(_line.split(','))
questions = []
answers = []
for conv in convs:
for i in range(len(conv)-1):
questions.append(id2line[conv[i]])
answers.append(id2line[conv[i+1]])
def clean_text(text):
text = text.lower()
text = re.sub(r"i'm", "i am", text)
text = re.sub(r"he's", "he is", text)
text = re.sub(r"she's", "she is", text)
text = re.sub(r"it's", "it is", text)
text = re.sub(r"that's", "that is", text)
text = re.sub(r"what's", "that is", text)
text = re.sub(r"where's", "where is", text)
text = re.sub(r"how's", "how is", text)
text = re.sub(r"\'ll", " will", text)
text = re.sub(r"\'ve", " have", text)
text = re.sub(r"\'re", " are", text)
text = re.sub(r"\'d", " would", text)
text = re.sub(r"\'re", " are", text)
text = re.sub(r"won't", "will not", text)
text = re.sub(r"can't", "cannot", text)
text = re.sub(r"n't", " not", text)
text = re.sub(r"n'", "ng", text)
text = re.sub(r"'bout", "about", text)
text = re.sub(r"'til", "until", text)
text = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", "", text)
return ' '.join([i.strip() for i in filter(None, text.split())])
clean_questions = []
for question in questions:
clean_questions.append(clean_text(question))
clean_answers = []
for answer in answers:
clean_answers.append(clean_text(answer))
min_line_length = 2
max_line_length = 5
short_questions_temp = []
short_answers_temp = []
i = 0
for question in clean_questions:
if len(question.split()) >= min_line_length and len(question.split()) <= max_line_length:
short_questions_temp.append(question)
short_answers_temp.append(clean_answers[i])
i += 1
short_questions = []
short_answers = []
i = 0
for answer in short_answers_temp:
if len(answer.split()) >= min_line_length and len(answer.split()) <= max_line_length:
short_answers.append(answer)
short_questions.append(short_questions_temp[i])
i += 1
question_test = short_questions[500:550]
answer_test = short_answers[500:550]
short_questions = short_questions[:500]
short_answers = short_answers[:500]
concat_from = ' '.join(short_questions+question_test).split()
vocabulary_size_from = len(list(set(concat_from)))
data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)
print('vocab from size: %d'%(vocabulary_size_from))
print('Most common words', count_from[4:10])
print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])
print('filtered vocab size:',len(dictionary_from))
print("% of vocab used: {}%".format(round(len(dictionary_from)/vocabulary_size_from,4)*100))
concat_to = ' '.join(short_answers+answer_test).split()
vocabulary_size_to = len(list(set(concat_to)))
data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)
print('vocab from size: %d'%(vocabulary_size_to))
print('Most common words', count_to[4:10])
print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])
print('filtered vocab size:',len(dictionary_to))
print("% of vocab used: {}%".format(round(len(dictionary_to)/vocabulary_size_to,4)*100))
GO = dictionary_from['GO']
PAD = dictionary_from['PAD']
EOS = dictionary_from['EOS']
UNK = dictionary_from['UNK']
for i in range(len(short_answers)):
short_answers[i] += ' EOS'
class Chatbot:
def __init__(self, size_layer, num_layers, embedded_size,
from_dict_size, to_dict_size, learning_rate,
batch_size, dropout = 0.5):
def cells(reuse=False):
return tf.nn.rnn_cell.GRUCell(size_layer, reuse=reuse)
def attention(encoder_out, seq_len, reuse=False):
attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer,
memory = encoder_out,
memory_sequence_length = seq_len)
return tf.contrib.seq2seq.AttentionWrapper(
cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse) for _ in range(num_layers)]),
attention_mechanism = attention_mechanism,
attention_layer_size = size_layer)
self.X = tf.placeholder(tf.int32, [None, None])
self.Y = tf.placeholder(tf.int32, [None, None])
self.X_seq_len = tf.placeholder(tf.int32, [None])
self.Y_seq_len = tf.placeholder(tf.int32, [None])
# encoder
encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))
encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)
encoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])
self.encoder_out, self.encoder_state = tf.nn.dynamic_rnn(cell = encoder_cells,
inputs = encoder_embedded,
sequence_length = self.X_seq_len,
dtype = tf.float32)
self.encoder_state = tuple(self.encoder_state[-1] for _ in range(num_layers))
main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])
decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)
# decoder
decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))
decoder_cell = attention(self.encoder_out, self.X_seq_len)
dense_layer = tf.layers.Dense(to_dict_size)
training_helper = tf.contrib.seq2seq.TrainingHelper(
inputs = tf.nn.embedding_lookup(decoder_embeddings, decoder_input),
sequence_length = self.Y_seq_len,
time_major = False)
training_decoder = tf.contrib.seq2seq.BasicDecoder(
cell = decoder_cell,
helper = training_helper,
initial_state = decoder_cell.zero_state(batch_size, tf.float32).clone(cell_state=self.encoder_state),
output_layer = dense_layer)
training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
decoder = training_decoder,
impute_finished = True,
maximum_iterations = tf.reduce_max(self.Y_seq_len))
predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(
embedding = decoder_embeddings,
start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),
end_token = EOS)
predicting_decoder = tf.contrib.seq2seq.BasicDecoder(
cell = decoder_cell,
helper = predicting_helper,
initial_state = decoder_cell.zero_state(batch_size, tf.float32).clone(cell_state=self.encoder_state),
output_layer = dense_layer)
predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
decoder = predicting_decoder,
impute_finished = True,
maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))
self.training_logits = training_decoder_output.rnn_output
self.predicting_ids = predicting_decoder_output.sample_id
masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)
self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,
targets = self.Y,
weights = masks)
self.optimizer = tf.train.AdamOptimizer(learning_rate).minimize(self.cost)
size_layer = 256
num_layers = 2
embedded_size = 128
learning_rate = 0.001
batch_size = 16
epoch = 20
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from),
len(dictionary_to), learning_rate,batch_size)
sess.run(tf.global_variables_initializer())
def str_idx(corpus, dic):
X = []
for i in corpus:
ints = []
for k in i.split():
try:
ints.append(dic[k])
except Exception as e:
print(e)
ints.append(UNK)
X.append(ints)
return X
X = str_idx(short_questions, dictionary_from)
Y = str_idx(short_answers, dictionary_to)
X_test = str_idx(question_test, dictionary_from)
Y_test = str_idx(answer_test, dictionary_from)
def pad_sentence_batch(sentence_batch, pad_int):
padded_seqs = []
seq_lens = []
max_sentence_len = max([len(sentence) for sentence in sentence_batch])
for sentence in sentence_batch:
padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))
seq_lens.append(len(sentence))
return padded_seqs, seq_lens
def check_accuracy(logits, Y):
acc = 0
for i in range(logits.shape[0]):
internal_acc = 0
count = 0
for k in range(len(Y[i])):
try:
if Y[i][k] == logits[i][k]:
internal_acc += 1
count += 1
if Y[i][k] == EOS:
break
except:
break
acc += (internal_acc / count)
return acc / logits.shape[0]
for i in range(epoch):
total_loss, total_accuracy = 0, 0
for k in range(0, (len(short_questions) // batch_size) * batch_size, batch_size):
batch_x, seq_x = pad_sentence_batch(X[k: k+batch_size], PAD)
batch_y, seq_y = pad_sentence_batch(Y[k: k+batch_size], PAD)
predicted, loss, _ = sess.run([model.predicting_ids, model.cost, model.optimizer],
feed_dict={model.X:batch_x,
model.Y:batch_y,
model.X_seq_len:seq_x,
model.Y_seq_len:seq_y})
total_loss += loss
total_accuracy += check_accuracy(predicted,batch_y)
total_loss /= (len(short_questions) // batch_size)
total_accuracy /= (len(short_questions) // batch_size)
print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))
for i in range(len(batch_x)):
print('row %d'%(i+1))
print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))
print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))
print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\n')
batch_x, seq_x = pad_sentence_batch(X_test[:batch_size], PAD)
batch_y, seq_y = pad_sentence_batch(Y_test[:batch_size], PAD)
predicted = sess.run(model.predicting_ids, feed_dict={model.X:batch_x,model.X_seq_len:seq_x})
for i in range(len(batch_x)):
print('row %d'%(i+1))
print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))
print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))
print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\n')
```
| github_jupyter |
## Quiz #0701 (Solution)
### "TensorFlow machine learning with Calilfornia housing data"
```
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import scale
import matplotlib.pyplot as plt
import tensorflow as tf
import warnings
%matplotlib inline
warnings.filterwarnings('ignore') # Turn the warnings off.
```
#### Answer the following question by providing Python code:
```
# Bring the data.
housing_data = fetch_california_housing()
# Read the description.
print(housing_data['DESCR'])
```
1). Explore the data:
- Display the dataset as a DataFrame with column labels.
```
# X and y.
header = housing_data.feature_names
X = housing_data['data']
y = housing_data['target'].reshape(-1,1) # reshape
# Show the shapes.
print(X.shape)
print(y.shape)
# Display as a DataFrame.
df = pd.DataFrame( np.concatenate((X,y),axis=1), columns = header + ['Value'])
np.round(df.head(5),2)
```
2). Build a machine learning model with TensorFlow.
- Preprocess the data if necessary.
- Build a linear regression model.
- Train the model.
- Calculate the error metrics such as MSE and RMSE (in-sample and out-of-sample). Target: RMSE < 1.
```
# Scale the X data.
X = scale(X)
# Split the data into training and testing sets.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=123)
# Display the shapes.
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
n_train_size = y_train.shape[0]
```
Do the necessary definitions.
```
# Hyperparameters.
batch_size = 4
n_epochs = 5001
learn_rate = 0.0001
# Variables.
b = tf.Variable(np.random.randn(8,1),dtype='float32') # There are 8 input variables.
b0 = tf.Variable(np.ones((1,1),dtype='float32')) # Intercept.
# Placeholders.
X_ph = tf.placeholder(tf.float32, shape=(None,8))
y_ph = tf.placeholder(tf.float32, shape=(None,1))
# Linear regression model.
y_model = tf.matmul(X_ph,b) + b0
loss = tf.reduce_mean(tf.square(y_ph - y_model))
# You may replace with another optimizer of your choice!
optimizer = tf.train.MomentumOptimizer(learning_rate = learn_rate, momentum=0.9)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
```
Train the model and estimate the error metrics:
```
with tf.Session() as sess:
sess.run(init)
for i in range(n_epochs):
idx_rnd = np.random.choice(range(n_train_size),batch_size,replace=False) # Random sampling w/o replacement for the batch indices.
batch_X, batch_y = X_train[idx_rnd,:] , y_train[idx_rnd] # Sample a batch!
my_feed = {X_ph:batch_X, y_ph:batch_y}
sess.run(train, feed_dict = my_feed)
if i % 500 == 0:
print("Step : {}".format(i))
mse = tf.reduce_mean(tf.square(y_ph - y_model)) # MSE.
mse_in = sess.run(mse, feed_dict = {X_ph:X_train, y_ph:y_train}) # In-sample MSE.
mse_out = sess.run(mse, feed_dict = {X_ph:X_test, y_ph:y_test}) # Out-of-sample MSE.
```
Display the error results.
```
print("In-Sample MSE = {:5.3f}".format(mse_in))
print("In-Sample RMSE = {:5.3f}".format(np.sqrt(mse_in)))
print("Out-of-Sample MSE = {:5.3f}".format(mse_out))
print("Out-of-Sample RMSE = {:5.3f}".format(np.sqrt(mse_out)))
```
| github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.

# Train and hyperparameter tune with Chainer
In this tutorial, we demonstrate how to use the Azure ML Python SDK to train a Convolutional Neural Network (CNN) on a single-node GPU with Chainer to perform handwritten digit recognition on the popular MNIST dataset. We will also demonstrate how to perform hyperparameter tuning of the model using Azure ML's HyperDrive service.
## Prerequisites
* If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [Configuration](../../../../configuration.ipynb) notebook to install the Azure Machine Learning Python SDK and create an Azure ML `Workspace`
```
# Check core SDK version number
import azureml.core
print("SDK version:", azureml.core.VERSION)
```
## 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](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#workspace) object from the existing workspace you created in the Prerequisites step. `Workspace.from_config()` creates a workspace object from the details stored in `config.json`.
```
from azureml.core.workspace import Workspace
ws = Workspace.from_config()
print('Workspace name: ' + ws.name,
'Azure region: ' + ws.location,
'Subscription id: ' + ws.subscription_id,
'Resource group: ' + ws.resource_group, sep = '\n')
```
## Create or Attach existing AmlCompute
You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource.
> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.
**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.
As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota.
```
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# choose a name for your cluster
cluster_name = "gpu-cluster"
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_NC6',
max_nodes=4)
# create the cluster
compute_target = ComputeTarget.create(ws, cluster_name, compute_config)
compute_target.wait_for_completion(show_output=True)
# use get_status() to get a detailed status for the current cluster.
print(compute_target.get_status().serialize())
```
The above code creates a GPU cluster. If you instead want to create a CPU cluster, provide a different VM size to the `vm_size` parameter, such as `STANDARD_D2_V2`.
## Train model on the remote compute
Now that you have your data and training script prepared, you are ready to train on your remote compute cluster. You can take advantage of Azure compute to leverage GPUs to cut down your training time.
### Create a project directory
Create a directory that will contain all the necessary code from your local machine that you will need access to on the remote resource. This includes the training script and any additional files your training script depends on.
```
import os
project_folder = './chainer-mnist'
os.makedirs(project_folder, exist_ok=True)
```
### Prepare training script
Now you will need to create your training script. In this tutorial, the training script is already provided for you at `chainer_mnist.py`. In practice, you should be able to take any custom training script as is and run it with Azure ML without having to modify your code.
However, if you would like to use Azure ML's [tracking and metrics](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#metrics) capabilities, you will have to add a small amount of Azure ML code inside your training script.
In `chainer_mnist.py`, we will log some metrics to our Azure ML run. To do so, we will access the Azure ML `Run` object within the script:
```Python
from azureml.core.run import Run
run = Run.get_context()
```
Further within `chainer_mnist.py`, we log the batchsize and epochs parameters, and the highest accuracy the model achieves:
```Python
run.log('Batch size', np.int(args.batchsize))
run.log('Epochs', np.int(args.epochs))
run.log('Accuracy', np.float(val_accuracy))
```
These run metrics will become particularly important when we begin hyperparameter tuning our model in the "Tune model hyperparameters" section.
Once your script is ready, copy the training script `chainer_mnist.py` into your project directory.
```
import shutil
shutil.copy('chainer_mnist.py', project_folder)
shutil.copy('chainer_score.py', project_folder)
shutil.copy('utils.py', project_folder)
```
### Create an experiment
Create an [Experiment](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#experiment) to track all the runs in your workspace for this Chainer tutorial.
```
from azureml.core import Experiment
experiment_name = 'chainer-mnist'
experiment = Experiment(ws, name=experiment_name)
```
### Create an environment
Define a conda environment YAML file with your training script dependencies and create an Azure ML environment.
```
%%writefile conda_dependencies.yml
channels:
- conda-forge
dependencies:
- python=3.6.2
- pip=21.3.1
- pip:
- azureml-defaults
- azureml-opendatasets
- chainer==5.1.0
- cupy-cuda100==5.1.0
- mpi4py==3.0.0
- pytest
from azureml.core import Environment
from azureml.core.runconfig import DockerConfiguration
chainer_env = Environment.from_conda_specification(name = 'chainer-5.1.0-gpu', file_path = './conda_dependencies.yml')
# Specify a GPU base image
chainer_env.docker.base_image = 'mcr.microsoft.com/azureml/openmpi3.1.2-cuda10.0-cudnn7-ubuntu18.04'
docker_config = DockerConfiguration(use_docker=True)
```
### Configure your training job
Create a ScriptRunConfig object to specify the configuration details of your training job, including your training script, environment to use, and the compute target to run on.
```
from azureml.core import ScriptRunConfig
src = ScriptRunConfig(source_directory=project_folder,
script='chainer_mnist.py',
arguments=['--epochs', 10, '--batchsize', 128, '--output_dir', './outputs'],
compute_target=compute_target,
environment=chainer_env,
docker_runtime_config=docker_config)
```
### Submit job
Run your experiment by submitting your ScriptRunConfig object. Note that this call is asynchronous.
```
run = experiment.submit(src)
```
### Monitor your run
You can monitor the progress of the run with a Jupyter widget. Like the run submission, the widget is asynchronous and provides live updates every 10-15 seconds until the job completes.
```
from azureml.widgets import RunDetails
RunDetails(run).show()
# to get more details of your run
print(run.get_details())
```
## Tune model hyperparameters
Now that we've seen how to do a simple Chainer training run using the SDK, let's see if we can further improve the accuracy of our model. We can optimize our model's hyperparameters using Azure Machine Learning's hyperparameter tuning capabilities.
### Start a hyperparameter sweep
First, we will define the hyperparameter space to sweep over. Let's tune the batch size and epochs parameters. In this example we will use random sampling to try different configuration sets of hyperparameters to maximize our primary metric, accuracy.
Then, we specify the early termination policy to use to early terminate poorly performing runs. Here we use the `BanditPolicy`, which will terminate any run that doesn't fall within the slack factor of our primary evaluation metric. In this tutorial, we will apply this policy every epoch (since we report our `Accuracy` metric every epoch and `evaluation_interval=1`). Notice we will delay the first policy evaluation until after the first `3` epochs (`delay_evaluation=3`).
Refer [here](https://docs.microsoft.com/azure/machine-learning/service/how-to-tune-hyperparameters#specify-an-early-termination-policy) for more information on the BanditPolicy and other policies available.
```
from azureml.train.hyperdrive.runconfig import HyperDriveConfig
from azureml.train.hyperdrive.sampling import RandomParameterSampling
from azureml.train.hyperdrive.policy import BanditPolicy
from azureml.train.hyperdrive.run import PrimaryMetricGoal
from azureml.train.hyperdrive.parameter_expressions import choice
param_sampling = RandomParameterSampling( {
"--batchsize": choice(128, 256),
"--epochs": choice(5, 10, 20, 40)
}
)
hyperdrive_config = HyperDriveConfig(run_config=src,
hyperparameter_sampling=param_sampling,
primary_metric_name='Accuracy',
policy=BanditPolicy(evaluation_interval=1, slack_factor=0.1, delay_evaluation=3),
primary_metric_goal=PrimaryMetricGoal.MAXIMIZE,
max_total_runs=8,
max_concurrent_runs=4)
```
Finally, lauch the hyperparameter tuning job.
```
# start the HyperDrive run
hyperdrive_run = experiment.submit(hyperdrive_config)
```
### Monitor HyperDrive runs
You can monitor the progress of the runs with the following Jupyter widget.
```
RunDetails(hyperdrive_run).show()
hyperdrive_run.wait_for_completion(show_output=True)
assert(hyperdrive_run.get_status() == "Completed")
```
### Warm start a Hyperparameter Tuning experiment and resuming child runs
Often times, finding the best hyperparameter values for your model can be an iterative process, needing multiple tuning runs that learn from previous hyperparameter tuning runs. Reusing knowledge from these previous runs will accelerate the hyperparameter tuning process, thereby reducing the cost of tuning the model and will potentially improve the primary metric of the resulting model. When warm starting a hyperparameter tuning experiment with Bayesian sampling, trials from the previous run will be used as prior knowledge to intelligently pick new samples, so as to improve the primary metric. Additionally, when using Random or Grid sampling, any early termination decisions will leverage metrics from the previous runs to determine poorly performing training runs.
Azure Machine Learning allows you to warm start your hyperparameter tuning run by leveraging knowledge from up to 5 previously completed hyperparameter tuning parent runs.
Additionally, there might be occasions when individual training runs of a hyperparameter tuning experiment are cancelled due to budget constraints or fail due to other reasons. It is now possible to resume such individual training runs from the last checkpoint (assuming your training script handles checkpoints). Resuming an individual training run will use the same hyperparameter configuration and mount the storage used for that run. The training script should accept the "--resume-from" argument, which contains the checkpoint or model files from which to resume the training run. You can also resume individual runs as part of an experiment that spends additional budget on hyperparameter tuning. Any additional budget, after resuming the specified training runs is used for exploring additional configurations.
For more information on warm starting and resuming hyperparameter tuning runs, please refer to the [Hyperparameter Tuning for Azure Machine Learning documentation](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-tune-hyperparameters)
### Find and register best model
When all jobs finish, we can find out the one that has the highest accuracy.
```
best_run = hyperdrive_run.get_best_run_by_primary_metric()
print(best_run.get_details()['runDefinition']['arguments'])
```
Now, let's list the model files uploaded during the run.
```
print(best_run.get_file_names())
```
We can then register the folder (and all files in it) as a model named `chainer-dnn-mnist` under the workspace for deployment
```
model = best_run.register_model(model_name='chainer-dnn-mnist', model_path='outputs/model.npz')
```
## Deploy the model in ACI
Now, we are ready to deploy the model as a web service running in Azure Container Instance, [ACI](https://azure.microsoft.com/en-us/services/container-instances/). Azure Machine Learning accomplishes this by constructing a Docker image with the scoring logic and model baked in.
### Create scoring script
First, we will create a scoring script that will be invoked by the web service call.
+ Now that the scoring script must have two required functions, `init()` and `run(input_data)`.
+ In `init()`, you typically load the model into a global object. This function is executed only once when the Docker contianer is started.
+ In `run(input_data)`, the model is used to predict a value based on the input data. The input and output to `run` uses NPZ as the serialization and de-serialization format because it is the preferred format for Chainer, but you are not limited to it.
Refer to the scoring script `chainer_score.py` for this tutorial. Our web service will use this file to predict. When writing your own scoring script, don't forget to test it locally first before you go and deploy the web service.
```
shutil.copy('chainer_score.py', project_folder)
```
### Create myenv.yml
We also need to create an environment file so that Azure Machine Learning can install the necessary packages in the Docker image which are required by your scoring script. In this case, we need to specify conda package `numpy` and pip install `chainer`. Please note that you must indicate azureml-defaults with verion >= 1.0.45 as a pip dependency, because it contains the functionality needed to host the model as a web service.
```
from azureml.core.runconfig import CondaDependencies
cd = CondaDependencies.create()
cd.add_conda_package('numpy')
cd.add_pip_package('chainer==5.1.0')
cd.add_pip_package("azureml-defaults")
cd.add_pip_package("azureml-opendatasets")
cd.save_to_file(base_directory='./', conda_file_path='myenv.yml')
print(cd.serialize_to_string())
```
### Deploy to ACI
We are almost ready to deploy. Create the inference configuration and deployment configuration and deploy to ACI. This cell will run for about 7-8 minutes.
```
from azureml.core.webservice import AciWebservice
from azureml.core.model import InferenceConfig
from azureml.core.webservice import Webservice
from azureml.core.model import Model
from azureml.core.environment import Environment
myenv = Environment.from_conda_specification(name="myenv", file_path="myenv.yml")
inference_config = InferenceConfig(entry_script="chainer_score.py", environment=myenv,
source_directory=project_folder)
aciconfig = AciWebservice.deploy_configuration(cpu_cores=1,
auth_enabled=True, # this flag generates API keys to secure access
memory_gb=1,
tags={'name': 'mnist', 'framework': 'Chainer'},
description='Chainer DNN with MNIST')
service = Model.deploy(workspace=ws,
name='chainer-mnist-1',
models=[model],
inference_config=inference_config,
deployment_config=aciconfig)
service.wait_for_deployment(True)
print(service.state)
print(service.scoring_uri)
```
**Tip: If something goes wrong with the deployment, the first thing to look at is the logs from the service by running the following command:**
```
print(service.get_logs())
```
This is the scoring web service endpoint:
```
print(service.scoring_uri)
```
### Test the deployed model
Let's test the deployed model. Pick a random sample from the test set, and send it to the web service hosted in ACI for a prediction. Note, here we are using the an HTTP request to invoke the service.
We can retrieve the API keys used for accessing the HTTP endpoint and construct a raw HTTP request to send to the service. Don't forget to add key to the HTTP header.
```
# retreive the API keys. two keys were generated.
key1, Key2 = service.get_keys()
print(key1)
%matplotlib inline
import matplotlib.pyplot as plt
import urllib
import gzip
import numpy as np
import struct
import requests
# load compressed MNIST gz files and return numpy arrays
def load_data(filename, label=False):
with gzip.open(filename) as gz:
struct.unpack('I', gz.read(4))
n_items = struct.unpack('>I', gz.read(4))
if not label:
n_rows = struct.unpack('>I', gz.read(4))[0]
n_cols = struct.unpack('>I', gz.read(4))[0]
res = np.frombuffer(gz.read(n_items[0] * n_rows * n_cols), dtype=np.uint8)
res = res.reshape(n_items[0], n_rows * n_cols)
else:
res = np.frombuffer(gz.read(n_items[0]), dtype=np.uint8)
res = res.reshape(n_items[0], 1)
return res
data_folder = os.path.join(os.getcwd(), 'data/mnist')
os.makedirs(data_folder, exist_ok=True)
urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/t10k-images-idx3-ubyte.gz',
filename=os.path.join(data_folder, 't10k-images-idx3-ubyte.gz'))
urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/t10k-labels-idx1-ubyte.gz',
filename=os.path.join(data_folder, 't10k-labels-idx1-ubyte.gz'))
X_test = load_data(os.path.join(data_folder, 't10k-images-idx3-ubyte.gz'), False) / np.float32(255.0)
y_test = load_data(os.path.join(data_folder, 't10k-labels-idx1-ubyte.gz'), True).reshape(-1)
# send a random row from the test set to score
random_index = np.random.randint(0, len(X_test)-1)
input_data = "{\"data\": [" + str(random_index) + "]}"
headers = {'Content-Type':'application/json', 'Authorization': 'Bearer ' + key1}
# send sample to service for scoring
resp = requests.post(service.scoring_uri, input_data, headers=headers)
print("label:", y_test[random_index])
print("prediction:", resp.text[1])
plt.imshow(X_test[random_index].reshape((28,28)), cmap='gray')
plt.axis('off')
plt.show()
```
Let's look at the workspace after the web service was deployed. You should see
+ a registered model named 'chainer-dnn-mnist' and with the id 'chainer-dnn-mnist:1'
+ a webservice called 'chainer-mnist-svc' with some scoring URL
```
model = ws.models['chainer-dnn-mnist']
print("Model: {}, ID: {}".format('chainer-dnn-mnist', model.id))
webservice = ws.webservices['chainer-mnist-1']
print("Webservice: {}, scoring URI: {}".format('chainer-mnist-1', webservice.scoring_uri))
```
## Clean up
You can delete the ACI deployment with a simple delete API call.
```
service.delete()
```
| github_jupyter |
# Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten digits!
GANs were [first reported on](https://arxiv.org/abs/1406.2661) in 2014 from Ian Goodfellow and others in Yoshua Bengio's lab. Since then, GANs have exploded in popularity. Here are a few examples to check out:
* [Pix2Pix](https://affinelayer.com/pixsrv/)
* [CycleGAN](https://github.com/junyanz/CycleGAN)
* [A whole list](https://github.com/wiseodd/generative-models)
The idea behind GANs is that you have two networks, a generator $G$ and a discriminator $D$, competing against each other. The generator makes fake data to pass to the discriminator. The discriminator also sees real data and predicts if the data it's received is real or fake. The generator is trained to fool the discriminator, it wants to output data that looks _as close as possible_ to real data. And the discriminator is trained to figure out which data is real and which is fake. What ends up happening is that the generator learns to make data that is indistiguishable from real data to the discriminator.

The general structure of a GAN is shown in the diagram above, using MNIST images as data. The latent sample is a random vector the generator uses to contruct it's fake images. As the generator learns through training, it figures out how to map these random vectors to recognizable images that can fool the discriminator.
The output of the discriminator is a sigmoid function, where 0 indicates a fake image and 1 indicates an real image. If you're interested only in generating new images, you can throw out the discriminator after training. Now, let's see how we build this thing in TensorFlow.
```
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
```
## Model Inputs
First we need to create the inputs for our graph. We need two inputs, one for the discriminator and one for the generator. Here we'll call the discriminator input `inputs_real` and the generator input `inputs_z`. We'll assign them the appropriate sizes for each of the networks.
>**Exercise:** Finish the `model_inputs` function below. Create the placeholders for `inputs_real` and `inputs_z` using the input sizes `real_dim` and `z_dim` respectively.
```
def model_inputs(real_dim, z_dim):
inputs_real =
inputs_z =
return inputs_real, inputs_z
```
## Generator network

Here we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero output for negative input values.
#### Variable Scope
Here we need to use `tf.variable_scope` for two reasons. Firstly, we're going to make sure all the variable names start with `generator`. Similarly, we'll prepend `discriminator` to the discriminator variables. This will help out later when we're training the separate networks.
We could just use `tf.name_scope` to set the names, but we also want to reuse these networks with different inputs. For the generator, we're going to train it, but also _sample from it_ as we're training and after training. The discriminator will need to share variables between the fake and real input images. So, we can use the `reuse` keyword for `tf.variable_scope` to tell TensorFlow to reuse the variables instead of creating new ones if we build the graph again.
To use `tf.variable_scope`, you use a `with` statement:
```python
with tf.variable_scope('scope_name', reuse=False):
# code here
```
Here's more from [the TensorFlow documentation](https://www.tensorflow.org/programmers_guide/variable_scope#the_problem) to get another look at using `tf.variable_scope`.
#### Leaky ReLU
TensorFlow doesn't provide an operation for leaky ReLUs, so we'll need to make one . For this you can just take the outputs from a linear fully connected layer and pass them to `tf.maximum`. Typically, a parameter `alpha` sets the magnitude of the output for negative values. So, the output for negative input (`x`) values is `alpha*x`, and the output for positive `x` is `x`:
$$
f(x) = max(\alpha * x, x)
$$
#### Tanh Output
The generator has been found to perform the best with $tanh$ for the generator output. This means that we'll have to rescale the MNIST images to be between -1 and 1, instead of 0 and 1.
>**Exercise:** Implement the generator network in the function below. You'll need to return the tanh output. Make sure to wrap your code in a variable scope, with 'generator' as the scope name, and pass the `reuse` keyword argument from the function to `tf.variable_scope`.
```
def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01):
''' Build the generator network.
Arguments
---------
z : Input tensor for the generator
out_dim : Shape of the generator output
n_units : Number of units in hidden layer
reuse : Reuse the variables with tf.variable_scope
alpha : leak parameter for leaky ReLU
Returns
-------
out, logits:
'''
with tf.variable_scope # finish this
# Hidden layer
h1 =
# Leaky ReLU
h1 =
# Logits and tanh output
logits =
out =
return out
```
## Discriminator
The discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer.
>**Exercise:** Implement the discriminator network in the function below. Same as above, you'll need to return both the logits and the sigmoid output. Make sure to wrap your code in a variable scope, with 'discriminator' as the scope name, and pass the `reuse` keyword argument from the function arguments to `tf.variable_scope`.
```
def discriminator(x, n_units=128, reuse=False, alpha=0.01):
''' Build the discriminator network.
Arguments
---------
x : Input tensor for the discriminator
n_units: Number of units in hidden layer
reuse : Reuse the variables with tf.variable_scope
alpha : leak parameter for leaky ReLU
Returns
-------
out, logits:
'''
with tf.variable_scope # finish this
# Hidden layer
h1 =
# Leaky ReLU
h1 =
logits =
out =
return out, logits
```
## Hyperparameters
```
# Size of input image to discriminator
input_size = 784 # 28x28 MNIST images flattened
# Size of latent vector to generator
z_size = 100
# Sizes of hidden layers in generator and discriminator
g_hidden_size = 128
d_hidden_size = 128
# Leak factor for leaky ReLU
alpha = 0.01
# Label smoothing
smooth = 0.1
```
## Build network
Now we're building the network from the functions defined above.
First is to get our inputs, `input_real, input_z` from `model_inputs` using the sizes of the input and z.
Then, we'll create the generator, `generator(input_z, input_size)`. This builds the generator with the appropriate input and output sizes.
Then the discriminators. We'll build two of them, one for real data and one for fake data. Since we want the weights to be the same for both real and fake data, we need to reuse the variables. For the fake data, we're getting it from the generator as `g_model`. So the real data discriminator is `discriminator(input_real)` while the fake discriminator is `discriminator(g_model, reuse=True)`.
>**Exercise:** Build the network from the functions you defined earlier.
```
tf.reset_default_graph()
# Create our input placeholders
input_real, input_z =
# Generator network here
g_model =
# g_model is the generator output
# Disriminator network here
d_model_real, d_logits_real =
d_model_fake, d_logits_fake =
```
## Discriminator and Generator Losses
Now we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, `d_loss = d_loss_real + d_loss_fake`. The losses will by sigmoid cross-entropies, which we can get with `tf.nn.sigmoid_cross_entropy_with_logits`. We'll also wrap that in `tf.reduce_mean` to get the mean for all the images in the batch. So the losses will look something like
```python
tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))
```
For the real image logits, we'll use `d_logits_real` which we got from the discriminator in the cell above. For the labels, we want them to be all ones, since these are all real images. To help the discriminator generalize better, the labels are reduced a bit from 1.0 to 0.9, for example, using the parameter `smooth`. This is known as label smoothing, typically used with classifiers to improve performance. In TensorFlow, it looks something like `labels = tf.ones_like(tensor) * (1 - smooth)`
The discriminator loss for the fake data is similar. The logits are `d_logits_fake`, which we got from passing the generator output to the discriminator. These fake logits are used with labels of all zeros. Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that.
Finally, the generator losses are using `d_logits_fake`, the fake image logits. But, now the labels are all ones. The generator is trying to fool the discriminator, so it wants to discriminator to output ones for fake images.
>**Exercise:** Calculate the losses for the discriminator and the generator. There are two discriminator losses, one for real images and one for fake images. For the real image loss, use the real logits and (smoothed) labels of ones. For the fake image loss, use the fake logits with labels of all zeros. The total discriminator loss is the sum of those two losses. Finally, the generator loss again uses the fake logits from the discriminator, but this time the labels are all ones because the generator wants to fool the discriminator.
```
# Calculate losses
d_loss_real =
d_loss_fake =
d_loss =
g_loss =
```
## Optimizers
We want to update the generator and discriminator variables separately. So we need to get the variables for each part and build optimizers for the two parts. To get all the trainable variables, we use `tf.trainable_variables()`. This creates a list of all the variables we've defined in our graph.
For the generator optimizer, we only want to generator variables. Our past selves were nice and used a variable scope to start all of our generator variable names with `generator`. So, we just need to iterate through the list from `tf.trainable_variables()` and keep variables that start with `generator`. Each variable object has an attribute `name` which holds the name of the variable as a string (`var.name == 'weights_0'` for instance).
We can do something similar with the discriminator. All the variables in the discriminator start with `discriminator`.
Then, in the optimizer we pass the variable lists to the `var_list` keyword argument of the `minimize` method. This tells the optimizer to only update the listed variables. Something like `tf.train.AdamOptimizer().minimize(loss, var_list=var_list)` will only train the variables in `var_list`.
>**Exercise: ** Below, implement the optimizers for the generator and discriminator. First you'll need to get a list of trainable variables, then split that list into two lists, one for the generator variables and another for the discriminator variables. Finally, using `AdamOptimizer`, create an optimizer for each network that update the network variables separately.
```
# Optimizers
learning_rate = 0.002
# Get the trainable_variables, split into G and D parts
t_vars =
g_vars =
d_vars =
d_train_opt =
g_train_opt =
```
## Training
```
batch_size = 100
epochs = 100
samples = []
losses = []
saver = tf.train.Saver(var_list = g_vars)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for e in range(epochs):
for ii in range(mnist.train.num_examples//batch_size):
batch = mnist.train.next_batch(batch_size)
# Get images, reshape and rescale to pass to D
batch_images = batch[0].reshape((batch_size, 784))
batch_images = batch_images*2 - 1
# Sample random noise for G
batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size))
# Run optimizers
_ = sess.run(d_train_opt, feed_dict={input_real: batch_images, input_z: batch_z})
_ = sess.run(g_train_opt, feed_dict={input_z: batch_z})
# At the end of each epoch, get the losses and print them out
train_loss_d = sess.run(d_loss, {input_z: batch_z, input_real: batch_images})
train_loss_g = g_loss.eval({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))
# Sample from generator as we're training for viewing afterwards
sample_z = np.random.uniform(-1, 1, size=(16, z_size))
gen_samples = sess.run(
generator(input_z, input_size, n_units=g_hidden_size, reuse=True, alpha=alpha),
feed_dict={input_z: sample_z})
samples.append(gen_samples)
saver.save(sess, './checkpoints/generator.ckpt')
# Save training generator samples
with open('train_samples.pkl', 'wb') as f:
pkl.dump(samples, f)
```
## Training loss
Here we'll check out the training losses for the generator and discriminator.
```
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
losses = np.array(losses)
plt.plot(losses.T[0], label='Discriminator')
plt.plot(losses.T[1], label='Generator')
plt.title("Training Losses")
plt.legend()
```
## Generator samples from training
Here we can view samples of images from the generator. First we'll look at images taken while training.
```
def view_samples(epoch, samples):
fig, axes = plt.subplots(figsize=(7,7), nrows=4, ncols=4, sharey=True, sharex=True)
for ax, img in zip(axes.flatten(), samples[epoch]):
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
im = ax.imshow(img.reshape((28,28)), cmap='Greys_r')
return fig, axes
# Load samples from generator taken while training
with open('train_samples.pkl', 'rb') as f:
samples = pkl.load(f)
```
These are samples from the final training epoch. You can see the generator is able to reproduce numbers like 5, 7, 3, 0, 9. Since this is just a sample, it isn't representative of the full range of images this generator can make.
```
_ = view_samples(-1, samples)
```
Below I'm showing the generated images as the network was training, every 10 epochs. With bonus optical illusion!
```
rows, cols = 10, 6
fig, axes = plt.subplots(figsize=(7,12), nrows=rows, ncols=cols, sharex=True, sharey=True)
for sample, ax_row in zip(samples[::int(len(samples)/rows)], axes):
for img, ax in zip(sample[::int(len(sample)/cols)], ax_row):
ax.imshow(img.reshape((28,28)), cmap='Greys_r')
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
```
It starts out as all noise. Then it learns to make only the center white and the rest black. You can start to see some number like structures appear out of the noise. Looks like 1, 9, and 8 show up first. Then, it learns 5 and 3.
## Sampling from the generator
We can also get completely new images from the generator by using the checkpoint we saved after training. We just need to pass in a new latent vector $z$ and we'll get new samples!
```
saver = tf.train.Saver(var_list=g_vars)
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
sample_z = np.random.uniform(-1, 1, size=(16, z_size))
gen_samples = sess.run(
generator(input_z, input_size, n_units=g_hidden_size, reuse=True, alpha=alpha),
feed_dict={input_z: sample_z})
view_samples(0, [gen_samples])
```
| github_jupyter |
# The big reset
So I went ahead and cleared the memory.
```
import sys
sys.path.append('..')
import collections
import mido
from commons import dgxdump
from commons.dumpdata import messages, songdata, regdata, regvalues
old_syx_messages = mido.read_syx_file('../data/syxout5.syx')
clear_syx_messages = mido.read_syx_file('../data/clear_bulk.txt')
o_dump = dgxdump.DgxDump(old_syx_messages)
c_dump = dgxdump.DgxDump(clear_syx_messages)
# songs slices
songslices = collections.OrderedDict([
('songs', slice(0x00, 0x01)),
('mystery', slice(0x01, 0x15D)),
('tracks', slice(0x15D, 0x167)),
('durations', slice(0x167, 0x17B)),
('trackdurations', slice(0x17B, 0x1F3)),
('presetstyle', slice(0x1F3, 0x22F)),
('beginningblocks', slice(0x22F, 0x24D)),
('nextblocks', slice(0x24D, 0x2CF)),
('startmarker', slice(0x2CF, 0x2D5)),
('blockdata', slice(0x2D5, 0x106D5)),
('endmarker', slice(0x106D5, None)),
])
EXPECTED_SIZE = 0x106DB
PRESETSTYLE = b'PresetStyle\0'*5
MARKER = b'PK0001'
def hex_string(data):
return " ".join("{:02X}".format(b) for b in data)
def bin_string(data):
return " ".join("{:08b}".format(b) for b in data)
def line_hex(data, head=None, tail=0):
if head is None:
head = len(data)
tailstart = len(data) - tail
if tailstart <= head:
return (hex_string(data))
else:
return ("{} .. {}".format(hex_string(data[:head]), hex_string(data[tailstart:])))
def song_section(dump, section):
return dump.song_data.data[songslices[section]]
for sec in songslices:
print(sec)
print(line_hex(song_section(o_dump, sec), 32, 4))
print(line_hex(song_section(c_dump, sec), 32, 4))
song_section(o_dump, 'mystery') == song_section(c_dump, 'mystery')
```
The mystery section remains the same.
```
all(b==0 for b in song_section(c_dump, 'nextblocks'))
all(b==0 for b in song_section(c_dump, 'blockdata'))
```
All the blocks are empty.
```
bytes(song_section(c_dump, 'presetstyle'))
```
The 'PresetStyle' settings are empty, too.
```
print(line_hex(o_dump.reg_data.data, 32, 4))
print(line_hex(c_dump.reg_data.data, 32, 4))
for bank in range(1, 8+1):
for button in range(1, 2+1):
print(bank, button)
print(line_hex(o_dump.reg_data.settings.get_setting(bank, button).data))
print(line_hex(c_dump.reg_data.settings.get_setting(bank, button).data))
```
Each of the registry settings are completely blank.
Interesting things to note: the first byte is 0 instead of 1, which probably indicates that the setting is unused.
The bytes that were FF in each recorded setting are 00 here.
## Investigating FUNCTION backup
According to the manual (page 49), the following settings can be saved to *backup*, i.e. persistent memory for startup bu holding the FUNCTION button:
- User songs (These are saved when recorded anyway)
- Style files (the ones loaded using SmartMedia)
- Touch response (ON/OFF)
- Registration memory
- These function settings:
- Tuning
- Split point
- Touch sensitivity
- Style volume
- Song volume
- Metronome volume
- Grade
- Demo cancel
- Language
- Media Select
- Panel Sustain.
These backup settings are also cleared with the rest of the memory.
The default values for these settings are as follows:
| setting | default |
|-------------------|--------------|
| Touch response | ON |
| Tuning | 000 |
| Split point | 54 (F#2) |
| Touch sensitivity | 2 (Medium) |
| Style volume | 100 |
| Song volume | 100 |
| Metronome volume | 100 |
| Grade | ON |
| Demo cancel | OFF |
| Language | English |
| Media Select | Flash Memory |
| Panel sustain | OFF |
As an experiment, I changed the values of the function settings:
| setting | new value |
|-------------------|--------------|
| Touch response | ON |
| Tuning | 057 |
| Split point | 112 (E7) |
| Touch sensitivity | 3 (Hard) |
| Style volume | 045 |
| Song volume | 079 |
| Metronome volume | 121 |
| Grade | OFF |
| Demo cancel | ON |
| Language | Japanese |
| Media Select | Smart Media |
| Panel sustain | ON |
and without making a backup:
- took a bulk dump. (cb1.txt),
- then made the backup, took another bulk dump, (cb2.txt),
- restarted with the new settings, took another (cb3.txt),
- reset everything to default without backup (cb4.txt),
- made a backup again and took another dump (cb5.txt),
- then restarted again (cb6.txt).
All of these files were identical to each other, which suggests that these backup settings are not stored any part we can retrieve.
However, there is one thing interesting about these files, in that they differ from the dump I got immediately after resetting the memory (clear_bulk.txt).
```
for x in range(2, 7):
!diff -qs ../data/backup_experiment/cb1.txt ../data/backup_experiment/cb{x}.txt
!diff -qs ../data/backup_experiment/cb1.txt ../data/clear_bulk.txt
c2_syx_messages = mido.read_syx_file('../data/backup_experiment/cb1.txt')
c2_dump = dgxdump.DgxDump(c2_syx_messages)
c_dump.song_data.data == c2_dump.song_data.data
c_dump.reg_data.data == c2_dump.reg_data.data
for sec in songslices:
c_sec = song_section(c_dump, sec)
c2_sec = song_section(c2_dump, sec)
if c_sec != c2_sec:
print(sec)
print(line_hex(c_sec, 32, 4))
print(line_hex(c2_sec, 32, 4))
for n, (a, b) in enumerate(zip(c_dump.song_data.data, c2_dump.song_data.data)):
if a != b:
print("{0:02X}: {1:02X} {2:02X} ({1:03d} {2:03d})".format(n, a, b))
```
The only difference seems to be two bytes in the mystery section, at offsets 0x07 and 0x08.
Perhaps this has to do with some kind of internal wear levelling or something.
## Registration extension
Now that the memory has been cleared, we can hopefully figure out more about the registration settings.
Recording Bank 3, Button 2 as the following settings:
| setting | value |
|------------------|-------|
| Style | 092 |
| Accompaniment | ON |
| Split point | 053 |
| Main A/B | A |
| Style vol | 050 |
| Main voice | 060 |
| Main Octave | -1 |
| Main Volume | 054 |
| Main Pan | 092 |
| Main Reverb | 078 |
| Main Chorus | 103 |
| Split | ON |
| Split voice | 003 |
| Split Octave | 0 |
| Split Volume | 108 |
| Split Pan | 064 |
| Split Reverb | 032 |
| Split Chorus | 127 |
| Dual | OFF |
| Dual voice | 201 |
| Dual Octave | +2 |
| Dual Volume | 095 |
| Dual Pan | 048 |
| Dual Reverb | 017 |
| Dual Chorus | 082 |
| Pitch bend range | 05 |
| Reverb type | --(Room) |
| Chorus type | --(Celeste) |
| Harmony | OFF |
| Harmony type | 06(Trill1/4) |
| Harmony volume | 085/---* |
| Transpose | +03 |
| Tempo | 080 |
| Panel Sustain | ON |
*This was set using a different Harmony type setting.
```
r1_dump = dgxdump.DgxDump(mido.read_syx_file('../data/post_clear/1reg.syx'))
c2_dump.song_data.data == r1_dump.song_data.data
c2_dump.reg_data.data == r1_dump.reg_data.data
for bank in range(1, 8+1):
for button in range(1, 2+1):
if not all(x == 0 for x in r1_dump.reg_data.settings.get_setting(bank, button).data):
print(bank, button)
line_hex(r1_dump.reg_data.settings.get_setting(3, 2).data)
for bb in [(3, 2), (1, 1)]:
sets = r1_dump.reg_data.settings.get_setting(*bb)
print(line_hex(sets.data))
sets.print_settings()
sets.print_unusual()
```
I believe the only real way to get unrecorded settings is to reset the memory, which clears all the values to zero.
This means that the first byte which has a value of `01` for all recorded settings can indeed be used as a flag... along with the `FF` byte at offset `24`, and any other setting that cannot be set to a value of zero, such as the Pitch Bend range, Reverb type, Chorus type, and panel Sustain.
Personally, I think it makes more sense for the first byte to act as the recorded flag, so I think I'll use that.
```
r2_dump = dgxdump.DgxDump(mido.read_syx_file('../data/post_clear/2reg.txt'))
sets = r2_dump.reg_data.settings.get_setting(2,2)
sets.print_settings()
sets.print_unusual()
```
The voice number 000 is used for the default voice for the whichever song or style is selected. If saved to a registration setting, the number 000 is not actually recorded, but rather the actual voice settings are saved.
## Song Stuff
According to the manual, page 45, the following data is recorded in melody tracks:
- Notes on/off and velocity
- Voice number
- Reverb and chorus type, (at beginning only, i.e. no changes)
- Harmony notes
- Pedal sustain and Function sustain
- Tempo and time signature (at beginning only, and only when style track not recorded)
- I believe this is what gets recorded onto the actual time track when Track A has not been selected for recording,
which suggests that this gets overwritten by Track A. We could test this by recording then deleting A, which
should then remove the old time information entirely
- Pitch bend and pitch bend range
- Dual voice on/off
- Main/Dual voice volume/octave/pan/reverb/chorus levels
And on the style track (A):
- Chord changes and timing
- Style pattern changes (Intro/Main A/B etc)
- Style number (at beginning only)
- Reverb and chorus type (at beginning only)
- Tempo
- Time signature (at beginning only)
- Style volume (at beginning only)
Note that the split voice and notes are not recorded at all (p.46). I suspect this may be because with five tracks each with main and dual, plus accompaniment, plus the actual keyboard voices, there aren't enough MIDI channels to accomodate them.
| github_jupyter |
```
from IPython.display import HTML
import numpy as np
import matplotlib.pyplot as plt
import math as m
import warnings
warnings.filterwarnings('ignore')
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
The raw code for this Jupyter notebook is by default hidden for easier reading.
To toggle on/off the raw code, click <a href="javascript:code_toggle()">here</a>.
<style>
.output_png {
display: table-cell;
text-align: center;
vertical-align: middle;
}
</style>
''')
```

### <h1><center>Module 12: Introduction to Z-transforms</center></h1>
To date we have looked at a number of transforms (i.e., Fourier Transform, Discrete Fourier Fourier) that are useful approaches for examining signals in a different domain. The purpose of this set of notes is to introduce a powerful **generalization** of these: the **Z-transform**. Studying this transform will allow us to introduce new tools for filtering signals (e.g., low-pass, high-pass, band-pass and band-reject filters).
## Z-transforms
The [Z-Transform](https://en.wikipedia.org/wiki/Z-transform) is used to convert a **discrete-time** signal (i.e., a sequence of real or complex numbers) into a complex frequency-domain representation. The Z-Transform, here written symbolically as $\mathcal{Z}[\cdot]$, is commonly given as the **bilateral** or **two-sided** transformation of a discrete time-series $x[n]$ into the [formal power series](https://en.wikipedia.org/wiki/Formal_power_series) $X(z)$ defined as:
<div class="alert alert-info" role="alert">
$$
X(z) = \mathcal{Z} \left\{ x[n] \right\} = \sum_{n=-\infty}^{\infty} x[n] z^{-n}, \tag{1}$$
</div>
where $n$ is an integer and $z$ is in general a complex number $ z=r\mathrm{e}^{i\phi} = r \left( \mathrm{cos}\,\phi + i\,\mathrm{sin}\,\phi \right).$ For clarity let's explicitly put this expression into the function:
$$
X(z) = \mathcal{Z} \left\{ x[n] \right\} = \sum_{n=-\infty}^{\infty} x[n] r^{-n}e^{-i\phi n}, \tag{2}$$
In some cases - and particularly for causal signals (i.e., $x[n]=0$ for $n\lt 0$), one often finds the **unilateral or one-sided Z-Transform**:
<div class="alert alert-info" role="alert">
$$
X(z) = \mathcal{Z} \left\{ x[n] \right\} = \sum_{n=0}^{\infty} x[n] z^{-n} = \sum_{n=0}^{\infty} x[n] r^{-n}e^{-i\phi n}, \tag{3}$$
</div>
which is commonly used for evaluating the unit impulse response of a discrete-time **causal** system.
### Connection with Discrete Fourier Transform
An interesting immediate question is "What is the connection between the Z-transform and the DFT we studied previously?". The answer is the that Z-transform **reduces** to the DFT for scenarios obeying the following three conditions:
1. A signal where $x[n]=0$ for $n<0$ and $n>N$;
2. A $\phi$ defined as $\phi=2\pi k/N$; and
3. A $r$ value defined as $r=1$.
Given these three conditions, we **exactly** recover the **Discrete Fourier Transform (DFT)**. Thus, the **Z-Transform** can be seen as a generalization of the **DFT**. It turns out that this generalization is very powerful and leads to a whole range of tools that are useful for filtering!
**Geophysical Definition**: In geophysics the Z-transform is commonly described as a power series in $z$ as opposed to $z^{-1}$. While the two equations are equivalent, the do result in a number of changes that I will mention these below. Because most of the DSP literature uses the former definition, I will use this terminology in this section.
## Example 1 - Unit Delay
**Q:** What happens when we take the Z-transform of signal $x[n]$ ($n\ge0$) that has been delayed by $k$ samples (i.e., $x[n-k]$)?
**A:** Let's evaluate this using the definition of the unilateral or one-sided Z-transform.
$$
\begin{array}{ll}
\mathcal{Z}\left\{x[n-k]\right\}
&=&
\sum_{n=0}^{\infty} x[n-k]z^{-n} \\
\,&=&
\sum_{j=-k}^{\infty} x[j]z^{-n}\quad \quad j=n-k \\
\,&=&
\sum_{j=-k}^{\infty} x[j]z^{-(j+k)} \\
\,&=&
\sum_{j=-k}^{\infty} x[j]z^{-j}z^{-k} \\
\,&=&
z^{-k}\sum_{j=-k}^{\infty} x[j]z^{-j} \\
\,&=&
z^{-k}\sum_{j=0}^{\infty} x[j]z^{-j}\quad\quad x[j]=0, j<0 \\
\,&=&
z^{-k}X(z) \\
\end{array}\tag{4}
$$
where $X(z)$ is the Z-transform of $x[n]$. Thus, $z^{-k}$ can be interpreted as an operator that **delays** a sequence by $k$ samples. Correspondingly, $z^k$ is an operator that **advances** a sequency by $k$ samples.
A consequence of this interpretation is that it can be used to represent regularly sampled time-series. For example, if we have a sequence of numbers $x[n]=[2,4,6,8,10]$ for $n=[0,1,2,3,4]$ then we can think about representing this sequence as the following $X(z)$ time-series:
$$X(z) = 2z^{0} + 4z^{-1} + 6z^{-2} + 8z^{-3} + 10z^{-4}, \tag{5a} $$
where the nth term in the advancing time series corresponds to the power $z^{-n}$.
## Linear Constant Cofficient Difference Equations (LCCDE)
Previously in the class we mentioned linear constant coefficient difference equations (LCCDE) in the context of linear time-invariant (LTI) systems. In any LTI system, its input $x[n]$ and output $y[n]$ can be related via a Nth order linear constant coefficient [difference equation](https://en.wikipedia.org/wiki/Linear_difference_equation):
$$ \sum_{k=0}^{N} a_k y[n-k] = \sum_{k=0}^{M} b_k x[n-k]. \tag{5b} $$
Let's explore what happens when we apply the Z-transform concept that we discussed above. Apply this to both side of equation 5 yields the following
$$\mathcal{Z} \left[ \sum_{k=0}^{N} a_k y[n-k] \right]
=
\mathcal{Z} \left[ \sum_{k=0}^{M} b_k x[n-k] \right]. \tag{6a}$$
However, because this is a linear operation we may write
$$ \sum_{k=0}^{N} a_k \mathcal{Z} \left[ y[n-k] \right]
=
\sum_{k=0}^{M} b_k \mathcal{Z} \left[ x[n-k] \right]. \tag{6b}$$
and then apply the definition of the Z-transform as the unit delay operator
$$\sum_{k=0}^N a_k z^{-k}Y(z) = \sum_{k=0}^{M} b_k z^{-k} X(z). \tag{6c}$$
Realizing that $Y(z)$ and $X(z)$ do not depend on $k$ allows us to write:
$$Y(z) \sum_{k=0}^N a_k z^{-k} = X(z) \sum_{k=0}^{M} b_k z^{-k}. \tag{7}$$
Let's now rewrite this equation by dividing both sides of equation 7 by $X(z)$ and by the series on the left. This results in the following expression:
$$H(z) \equiv \frac{Y(z)}{X(z)} = \frac{\sum_{k=0}^{M} b_k z^{-k}}{\sum_{k=0}^N a_k z^{-k} }, \tag{8a} $$
where $H(z)$ is known as the [transfer function](https://en.wikipedia.org/wiki/Transfer_function) and effectively describes how the input and output are related in Z-space:
$$Y(z) = H(z) X(z). \tag{8b}$$
Applying $H(z)$ may also be thought of as applying a **filtering** operation that transforms an input signal represented by $X(z)$ into an output signal represented by $Y(z)$.
We have seen something like this before when we discussed the convolution theorem. In the case where the Z-transform becomes a Fourier Transform the operation in equation 8b effectively represents the **convolution theorem in the frequency domain**. Thus, this may be thought of as an extension of the convolution theorem to the Z-transform.
### FIR and IIR systems
There are two classes of transfer function that are commonly applied in digital signal processing:
1. A system with coefficients $a_k=0, k\ge 1$ does not have feedback, and is called a **nonrecursive filter** or a [finite-impulse response (FIR)](https://en.wikipedia.org/wiki/Finite_impulse_response) filter.
2. A system with coefficients $a_k\neq 0, k\ge 1$ is said to have **feedback** since the current output value depends on the *previous* output values. A filter exhibiting such a characteristic is called both a **recursive filter** or an [infinite-impulse response (IIR)](https://en.wikipedia.org/wiki/Infinite_impulse_response) filter.
Let's now make a connection with the LCCDE studied previously:
1. An averaging filter depends only on the input sequence and not on the previous filtered output and thus an averaging operator may be considered as a FIR filtering operator.
2. Your current bank account or mortage balance depends on what is was in months previous and thus compound interest or mortgage ammortization operators may be considered as a recursive IIR filtering operator.
## Fundamental Theorem of Algebra
The [Fundamental Theorem of Algebra](https://en.wikipedia.org/wiki/Fundamental_theorem_of_algebra) states that
"Every non-zero, single-variable, degree n polynomial with complex coefficients has, counted with multiplicity, exactly n complex roots. The equivalence of the two statements can be proven through the use of successive polynomial division."
What is the implication here? This means that a $n$-order polynomial expanded about some complex value $z_0$,
$$p(z)=\sum_{k=0}^{n}c_k(z-z_0)^k = c_0+c_{1}(z-z_{0})^{1}+c_{2}(z-z_{0})^{2}+\cdots +c_{n}(z-z_{0})^{n}, \tag{9}$$
can be rewritten as
$$p(z)= a_0 \Pi_{k=1}^n (z-z_k) = a_0(z-z_{1})(z-z_{2})\cdots (z-z_{n}). \tag{10}$$
where the $\Pi$ represents Pi summation notation [e.g., $\Pi_{k=3}^{5} k =3 \times 4 \times 5=60$]. Thus, we can write the above transfer function $H(z)$ as:
<div class="alert alert-info" role="alert">
$$H(z) \equiv \frac{Y(z)}{X(z)} = \frac{ p_0\Pi_{k=1}^{M} (z-p_k)}{ q_0 \Pi_{k=1}^{N}(z-q_k) }. \tag{11} $$
</div>
You may (should!) be concerned about what's going on in the denominator. In particular, what is happening whenever $z=q_k$: division by zero! Thus, we must examine the **stability** of these transfer functions as well as determine in which region of the complex plane these series converge.
## Poles and Zeros
Starting from the $H(z)$ defined in equation 11, let's examine a few different important values.
**Zeros:** are the values of $z$ for which $H(z)=0$. These occur when by $z=p_k$ in equation 11. These **do not cause** any stability issues; however, they cause certain parts of the output spectrum to be equal to zero.
**Poles:** are the values of $z$ for which $H(z)=\infty$. These occur when $z=q_k$ in equation 11. These **do cause** stability issues since division by zero will cause an infinite output!
An important concept is that by specifying the locations of where we put $p_k$ and $q_k$ we can design filters (e.g., low-pass, high-pass, band-pass) that will take our input data $x[n]$ and give us the desired output signals $y[n]$ (e.g., low-passed, high-passed or band-passed data).
**Q:** How many zeros and poles are there in equation 11?
**A:**: There are $M$ zeros and $N$ poles.
## Thinking about convergence
Let's first refresh ourselves about the concept of convergence and (infinite) geometric series. We can start with the following $N$ term **finite geometric series**:
$$y = \sum_{n=0}^{N-1} ax^n = a \left(\frac{1-x^N}{1-x}\right), \tag{11a}$$
where we have used a [geometric sum](https://en.wikipedia.org/wiki/Geometric_progression#Geometric_series) to evaluate on the right hand side. There are no issues here in terms of stability (i.e., $y<\infty$) even at $x=1$ because this just results in a sum of $y=aN$.
What happens when we now consider an **infinite geometric series**?
$$y = \sum_{n=0}^{\infty} ax^n = a \left(\frac{1-x^\infty}{1-x}\right), \tag{11b}$$
Clearly, there is now a different concern because for $y<\infty$ we now have to put restrictions on $|x|\le 1$ because otherwise $x^\infty$ will lead to $y=\infty$. The restriction $-1\le x \le 1$ is thus the **region of convergence** of this infinite sum along the real $x$ axis.
What happens if we now have the follow **infinite geometric series**?
$$y = \sum_{n=0}^{\infty} (ax)^n = a \left(\frac{1-(ax)^\infty}{1-(ax)}\right). \tag{11c}$$
In this case we see that $|ax|<1$ or better yet $|a||x|<1$. Thus, for this to be stable (i.e., $y<\infty$) we need to have $|x|< |a|^{-1}$.
## Region of Convergence
The region of convergence (ROC) indicates when Z-transforms of a sequence converges. Generally, there exists some $z$ such that
$$\left| X(z) \right| =\left|\sum_{k=-\infty}^{\infty} x[n]z^{-n}\right|\rightarrow \infty \tag{12}$$
where the Z-transform **does not converge**. The set of values for $z$ for which $X(z)$ converges,
<div class="alert alert-info" role="alert">
$$\left| X(z) \right| =\left|\sum_{k=-\infty}^{\infty} x[n]z^{-n}\right| \le \sum_{k=-\infty}^{\infty} \left|x[n]z^{-n}\right| < \infty \tag{13}$$
</div>
is called the ROC. The ROC must be specified along with $X(z)$ in order for the Z-transform to be considered "complete".
Assuming that $x[n]$ is of infinite length, let's decompose $X(z)$ as the following:
$$\begin{eqnarray}
X(z) &=& X_{-}(z) + X_+(z), \tag{14}
\end{eqnarray}$$
where these two contributions are the anticausal ($X_-(z)$) and causal ($X_+(z)$) components of $X(z)$:
$$\begin{eqnarray}
X_{-}(z) &=& \sum_{n=-\infty}^{-1}x[n]z^{-n} \tag{15a}\\
X_{+}(z) &=& \sum_{n=0}^{\infty}x[n]z^{-n} \tag{15b}\\
\end{eqnarray}$$
where it is clear that the sum of equations 15a and 15b satisfy equation 14.
### Convergence of $X_+(z)$
For a series to converge, the series
$$\begin{eqnarray}
X_+(z) &=& x[0]z^{-0} + x[1]z^{-1} +\dots + x[n]z^{-n}+ ... \tag{16a}\\
\, &=& f_0(z)+f_1(z)+ \dots + f_n(z) + \dots \tag{16b}\\
\end{eqnarray}$$
has to satisfy the following [ratio test](https://en.wikipedia.org/wiki/Ratio_test) behaviour:
$$\lim_{n\rightarrow\infty}
\left|
\frac{f_{n+1}(z)}{f_n(z)}
\right|
< 1.\tag{17}
$$
Thus, assuming that the input sequence $x[n]$ converges to a value finite value $R_+$
$$
\lim_{n\rightarrow\infty}
\left|
\frac{x[n+1]}{x[n]}
\right|
= R_+ \tag{18}
$$
then $X_+[z]$ will converge if
$$
\lim_{n\rightarrow\infty}
\left|
\frac{x[n+1]z^{-n-1}}{x[n]z^{-n}}
\right|
=
\lim_{n\rightarrow\infty}
\left|
\frac{x[n+1]}{x[n]}
\right|
\left|z^{-1}\right|
<1 \tag{19}
$$
This implies that
$$\left|z\right| > \lim_{n\rightarrow\infty}
\left|
\frac{x[n+1]}{x[n]}
\right|=R_+. \tag{20}
$$
That is, the ROC for $X_+(z)$ is
$$|z|>R_+. \tag{21}$$
### Convergence of $X_-(z)$
Assuming that the sequence converges to a non-infinite value $1/R_-$
$$
\lim_{m\rightarrow\infty}
\left|
\frac{x[-m-1]}{x[-m]}
\right|
= \frac{1}{R_-}, \tag{22}
$$
the anticausal components will converge if
$$
\lim_{m\rightarrow\infty}
\left|
\frac{x[-m-1]z^{m+1}}{x[-m]z^{m}}
\right|
=
\lim_{m\rightarrow\infty}
\left|
\frac{x[-m-1]}{x[-m]}
\right|
\left|z\right| = \frac{1}{R_-} \left|z\right|
<1. \tag{23}
$$
Thus, the ROC for $X_-(z)$ is
$$|z|<R_-.\tag{25}$$
### Combining the Results
The ROC for a infinite sequence, $X(z)$ is given by
$$R_+<|z|<R_-. \tag{26}$$
Note that if $R_- < R_+$ then there is **no ROC** and $X(z)$ **does not exist**.
Let's look at this graphically:
<img src="Fig/ROC.png" width="800">
**Figure 1. Illustrating the different regions of convergence for $X_+(z)$, $X_-(z)$ and $X(z)$.**
## Example 2 - Causal geometric sequence
**Q:** Determine the z-transform of $x[n] = a^n u[n]$ where $u[n]$ is the unit step function.
**A:** The input function may be written as
$$X(z) = \sum_{n=-\infty}^{\infty} a^n u[n]z^{-n} = \sum_{n=0}^{\infty} a^n z^{-n}= \sum_{n=0}^{\infty} \left(a z^{-1}\right)^n. \tag{27}$$
According to the above, $X(z)$ will converge if
$$\sum_{n=0}^{\infty} \left|a z^{-1}\right|^n< \infty \tag{28}$$
Applying the **ratio test**
$$\lim_{n\rightarrow\infty}
\left|
\frac{f_{n+1}(z)}{f_n(z)}
\right|
< 1. \tag{29}
$$
we get
$$\lim_{n\rightarrow\infty}
\left|
\frac{a^{n+1}z^{-n-1}}{a^nz^{-n}}
\right|
=
\left|
az^{-1}
\right|
< 1.\tag{30}
$$
Thus, the convergence condition is that $|a|<|z|$. Thus, within this region we may use a geometric series to evaluate this infinite summation in the region where the series converges:
$$
X(z) = \sum_{n=0}^\infty \left(az^{-1}\right)^n
=
\frac{1-\left(az^{-1}\right)^\infty}{1-az^{-1}}
=
\frac{1}{1-az^{-1}}
=
\frac{z}{z-a},
\tag{31}
$$
where the second equality is reached in the ROC because $az^{-1}<1$ which means that $(az^{-1})^\infty=0$; the final step is just multiplying top and bottom by $z$.
Thus, together with the ROC, the z-transform of $x[n]=a^n u[n]$ is:
$$X(z) = \frac{z}{z-a}, \quad |a| < |z|. \tag{32}$$
It is clear that $X(z)$ has a **zero** at $z=0$ and a **pole** at $z=a$.
<img src="Fig/ROC_EX2.png" width="500">
**Figure 2. Plotting the ROC of $|z|>|a|$. Note that if $|a|<1$ then the Discrete Fourier Transform is guaranteed to exist. However, if $|a|>1$ then it is not guaranteed to exist (but it may if the input terms in $u(z)$ fall over faster than $a^{-1}$).**
## Example 3 - Anticausal geometric sequence
**Q:** Determine the z-transform of $x[n]=-b^n u[-n-1]$.
**A:** Let's write
$$X(z) =
-\sum_{n=-\infty}^{\infty}b^n u[-n-1] z^{-n}
=
-\sum_{n=-\infty}^{-1}b^n z^{-n}\tag{33}
$$
Let's now identify $m=-n$ and write
$$X(z) =
-\sum_{m=1}^{\infty}b^{-m} z^{m}
=
-\sum_{m=1}^{\infty}\left(b^{-1} z\right)^{m}. \tag{34}
$$
Thus, like the Example 2, $X(z)$ converges if $\left|b^{-1}z\right|<1$, or $|b|>|z|$. This gives:
$$X(z)=-\sum_{m=1}^{\infty} \left(b^{-1}z\right)^m =
- \frac{b^{-1}z(1-(b^{-1}z)^\infty)}{1-b^{-1}z} =- \frac{b^{-1}z}{1-b^{-1}z} = - \frac{z}{b-z} = \frac{z}{z-b}. \tag{35}$$
Thus, together with the ROC, the z-transform of $x[n]=-b^n u[-n-1]$ is:
$$X(z) = \frac{z}{z-b}, \quad |b|>|z|. \tag{36}$$
Again, it is clear that $X(z)$ has a **zero** at $z=0$ and a **pole** at $z=b$.
<img src="Fig/ROC_EX3.png" width="500">
**Figure 3. Plotting the ROC of $|b|>|z|$. Note that if $|b|>1$ then the Discrete Fourier Transform is guaranteed to exist. However, if $|b|<1$ then it is not guaranteed to exist (but it may if the input terms in $u(z)$ fall over faster than $b^{-1}$).**
## Example 4 - Combining Examples 2 and 3
**Q:** Determine the z-transform of $x[n] = a^n u[n]+b^n u[-n-1]$ where $|a|<|b|$.
**A:** Employing the previous results we have
$$
\begin{eqnarray}
X(z) &=& \frac{z}{z-a}-\frac{z}{z-b} \quad |a|<|z|<|b| \tag{37a} \\
&=&
\frac{(b-a)z}{(z-a)(z-b)}, \quad |a|<|z|<|b| \tag{37b}\\
\end{eqnarray}
$$
Note that there is still one **zero** ($z=0$) but there are now two **poles** ($z=a$ and $z=b$). Note that the ROC is given by Figure 1c where $a=R_+$ and $b=R_-$.
## Example 5 - Unit Impulse
**Q:** What is the Z-transform of $x[n]=\delta[n-p]$.
**A:** We have
$$X(z) = \sum_{n=-\infty}^\infty \delta[n-p]z^{-n} = z^{-p},\quad |z|<\infty, \tag{38}$$
which effectively states that as long as $r^{-p}<\infty$ the Z transform will converge.
## Example 6 - Finite Geometry Series
**Q:** Determine the z-transform of $x[n]$ which has the form
$$x[n] = \left\{
\begin{array}{cc}
a^n & 0\le n\le N-1 \\
0 & \mathrm {otherwise}\\
\end{array}
\right. \tag{39}
$$
**A:** Assuming that $a^N<\infty$, we have by the geometric series
$$X(z) = \sum_{n=0}^{N-1}\left(az^{-1}\right)^n =
\frac{1-\left(az^{-1}\right)^N}{1-az^{-1}}
=
\frac{1}{z^{N-1}}\frac{z^N-a^N}{z-a}, \quad |z|>0. \tag{40}\\
$$
Note that when $a=z$ then the first summation term reduces to a sum of N ones.
## Finite- and Infinite-duration sequences
**Finite-duration sequence**: A sequence where values of $x[n]$ are non-zero only for a finite time interval.
<img src="Fig/finite.png" width="400">
**Figure 4. Illustrating a number of *finite-duration* sequences and their region of convergence.**
Otherwise $x[n]$ is an **infinite-duration sequence**. There are a number of different types of these infinite-duration sequences:
* **Right-sided**: If $x[n]=0$ for $n<N_+<\infty$ where $N_+$ is an integer.
* **Left-sided**: If $x[n]=0$ for $n >N_- >-\infty$ where $N_-$ is an integer.
* **Two-sided**: Neither a right- nor left-sided sequence.
<img src="Fig/infinite.png" width="400">
**Figure 5. Illustrating a number of *infinite-duration* sequences and their region of convergence.**
| github_jupyter |
```
# 安装数据集可视化所需包
!pip install pycocotools
!pip install scikit-image
```
# 1 数据集信息
## 1.1 数据集的准备与介绍
### **数据集介绍**
数据集包含多个损坏零件的汽车图像,来源于AI Studio提供的公共数据集,进一步源自于Kaggle的汽车损坏数据集。该数据集属于交通领域,适合计算机视觉中目标检测或实例分割任务。
数据集共有78张图片,以jpg格式存储,位于img文件夹中。
按数据集提供者的数据集分割,train、val、test各包括59、11和8张图片,每张图片以jpg格式存储。其中,train和val包含COCO格式的注释文件。
数据集提供COCO格式的注释,分为两个类型。一部分是仅描述了损坏发生的位置,即仅有damage一类目标;另一部分则描述了损坏具体发生的位置,共有headlamp、front_bumper、hood、door、rear_bumper五类。
```
# 解压数据集
%cd /home/aistudio/
!unzip -oq /home/aistudio/data/data105047/archive\ \(1\).zip -d data/dataset/
# 查看数据集的目录结构
!tree data/dataset/ -d
# 数据集可视化显示
import json
import os
import cv2
from pycocotools.coco import COCO
from skimage import io
from matplotlib import pyplot as plt
import matplotlib.font_manager # 解决字体问题
train_path = 'data/dataset/train/'
train_json = train_path + 'COCO_train_annos.json'
# 可视化bounding box
def visualization_bbox(num_image, json_path, img_path):
with open(json_path) as annos:
annotation_json = json.load(annos)
# 读取图片名
image_name = annotation_json['images'][num_image - 1]['file_name'] # 读取图片名
# 读取图片id
image_id = annotation_json['images'][num_image - 1]['id'] # 读取图片id
image_path = os.path.join(img_path, str(image_name).zfill(5))
image = cv2.imread(image_path, 1)
for i in range(len(annotation_json['annotations'][::])):
if annotation_json['annotations'][i - 1]['image_id'] == image_id:
x, y, w, h = annotation_json['annotations'][i - 1]['bbox'] # 读取边框
image = cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), (0, 255, 255), 4)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.show()
visualization_bbox(5, train_json, train_path) # 第一个参数表示指定可视化某张图片
# 可视化分割效果
def visualization_seg(num_image, json_path):
coco = COCO(json_path)
catIds = coco.getCatIds(catNms=[""])
imgIds = coco.getImgIds(catIds=catIds)
img = coco.loadImgs(imgIds[num_image - 1])[0]
image = io.imread(train_path + img['file_name'])
annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
anns = coco.loadAnns(annIds)
plt.imshow(image)
coco.showAnns(anns)
plt.show()
visualization_seg(5, train_json)
# 同时可视化分割效果和bounding box
def visualization_both(num_image, json_path, img_path):
coco = COCO(json_path)
catIds = coco.getCatIds(catNms=[""])
list_imgIds = coco.getImgIds(catIds=catIds)
img = coco.loadImgs(list_imgIds[num_image-1])[0]
image = io.imread(img_path + img['file_name'])
img_annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
img_anns = coco.loadAnns(img_annIds)
for i in range(len(img_annIds)):
x, y, w, h = img_anns[i-1]['bbox']
image = cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), (0, 255, 255), 4)
plt.rcParams['figure.figsize'] = (5.0, 5.0)
plt.imshow(image)
coco.showAnns(img_anns)
plt.show()
visualization_both(5, train_json, train_path)
```
## 1.2图像数据统计分析
```
# 计算数据集图像均值和方差
import glob
import numpy as np
import cv2
def get_mean_std(image_path_list):
print('Total images:', len(image_path_list))
max_val, min_val = np.zeros(3), np.ones(3) * 255
mean, std = np.zeros(3), np.zeros(3)
for image_path in image_path_list:
image = cv2.imread(image_path)
for c in range(3):
mean[c] += image[:, :, c].mean()
std[c] += image[:, :, c].std()
max_val[c] = max(max_val[c], image[:, :, c].max())
min_val[c] = min(min_val[c], image[:, :, c].min())
mean /= len(image_path_list)
std /= len(image_path_list)
mean /= max_val - min_val
std /= max_val - min_val
return mean, std
path1 = 'data/dataset/img/'
path2 = 'data/dataset/test/'
img_list = glob.glob(path1 + "*.jpg") + glob.glob(path2 + '*.jpg')
mean, std = get_mean_std(img_list)
print('mean:', mean)
print('std:', std)
```
## 1.3数据集类的定义
这里整体思路是通过COCO格式的annotation文件读取数据集信息。
初始化数据集时,读取annotation文件,而test不含annotation文件。
getitem方法,从annotation中按idx选取图片,以plt的方式读入,并在annotation文件的'annotations'中获取对应idx图片的label信息。这里实现了两个功能,既可以返回用于目标检测的四维bounding box坐标,也可以返回用于实例分割的分割点数据。
len方法,可以直接读取annotation文件中'images'包含的图片数得到,若test则通过glob统计。
```
from paddle.io import Dataset
from matplotlib import pyplot as plt
import json
import glob
DATASET_PATH = 'data/dataset/{}/'
ANNO_FILE = 'COCO_{}_annos.json'
class CustomDataset(Dataset):
def __init__(self, mode='train', application='detection'):
super(CustomDataset, self).__init__()
assert mode.lower() in ['train', 'val', 'test'], \
"mode should be 'train', 'val' or 'test', but got {}".format(mode)
assert application.lower() in ['detection', 'segmentation'], \
"application should be 'detection' or 'segmentation', but got {}".format(application)
self.application = application
self.mode = mode
if self.mode != 'test':
self.annotation = self._load_anno(self.mode)
else:
self.annotation = None
def _load_anno(self, mode):
annotation_path = DATASET_PATH.format(mode) + ANNO_FILE.format(mode)
with open(annotation_path) as annos:
annotation_json = json.load(annos)
return annotation_json
def __getitem__(self, idx):
assert self.mode.lower() in ['train', 'val'], \
"mode should be 'train' or 'val', but got {}".format(self.mode)
# 返回matplotlib打开的图片格式
img_name = self.annotation['images'][idx]['file_name']
img_path = DATASET_PATH.format(self.mode) + img_name
data = plt.imread(img_path)
label = []
if self.application == 'detection':
for i in range(len(self.annotation['annotations'][::])):
if self.annotation['annotations'][i - 1]['image_id'] == idx:
label.append(self.annotation['annotations'][i - 1]['bbox'])
if self.application == 'segmentation':
for i in range(len(self.annotation['annotations'][::])):
if self.annotation['annotations'][i - 1]['image_id'] == idx:
label.append(self.annotation['annotations'][i - 1]['segmentation'][0])
return data, label
def __len__(self):
if self.mode == 'test':
return len(glob.glob(DATASET_PATH.format('test') + '*.jpg'))
return len(self.annotation['images'])
```
## 1.4数据集类的测试
```
# 测试各文件夹中用于目标检测和实例分割的len方法
d1 = CustomDataset(mode='train', application='detection')
d2 = CustomDataset(mode='val', application='detection')
d3 = CustomDataset(mode='test', application='detection')
d4 = CustomDataset(mode='train', application='segmentation')
d5 = CustomDataset(mode='val', application='segmentation')
d6 = CustomDataset(mode='test', application='segmentation')
print('train 文件夹 目标检测 ' + str(len(d1)))
print('val 文件夹 目标检测 ' + str(len(d2)))
print('test 文件夹 目标检测 ' + str(len(d3)))
print('train 文件夹 实例分割 ' + str(len(d4)))
print('val 文件夹 实例分割 ' + str(len(d5)))
print('test 文件夹 实例分割 ' + str(len(d6)))
# 这里就不详细每个都测试了,测试train文件夹下某张图片用于实例分割和目标检测的getitem方法
data, label = d1[4]
print('目标检测')
print(data.shape)
print(label)
print()
data, label = d4[5]
print('实例分割')
print(data.shape)
print(label)
# 使用train_dataloader测试
import paddle
d = CustomDataset(mode='train', application='detection')
train_dataloader = paddle.io.DataLoader(
d,
batch_size=1,
shuffle=True,
drop_last=False)
for step, data in enumerate(train_dataloader):
image, label = data
print(step, image.shape, len(label))
```
# 2 安装PaddleDetection
使用PaddleDetection中的PicoDet模型完成车损检测的任务。
由于PaddleDetection项目较大,因此在外部下载PaddleDetection的压缩包,上传到文件中,然后直接解压使用。
```
# 解压PaddleDetection
%cd work/
!unzip -oq /home/aistudio/work/PaddleDetection.zip
# 移动到根目录下
!mv /home/aistudio/work/PaddleDetection /home/aistudio/
# 每次打开notebook需要重新执行的文件:
# 解压数据集,每次打开notebook重新执行
%cd /home/aistudio/
!unzip -oq /home/aistudio/data/data105047/archive\ \(1\).zip -d data/dataset/
# 安装,每次打开notebook重新执行
%cd PaddleDetection/
!pip install -r requirements.txt
!python setup.py install
%cd /home/aistudio/PaddleDetection/
```
# 3 修改配置文件
picodet模型主要用到六个相关的配置文件,对其内容做更改,用于对车损检测任务训练
## 3.1 coco_detection.yml
该配置文件记录了数据集的路径和内容等信息。
因为进行车损检测的的任务,所检测的目标仅有一种,因此修改num_classes为1。分别修改train、val、test三个数据集的annotation文件位置和数据集的文件位置,以正确读取数据集的相关信息。
```
metric: COCO
num_classes: 1
TrainDataset:
!COCODataSet
image_dir:
anno_path: COCO_train_annos.json
dataset_dir: ../data/dataset/train
data_fields: ['image', 'gt_bbox', 'gt_class']
EvalDataset:
!COCODataSet
image_dir:
anno_path: COCO_val_annos.json
dataset_dir: ../data/dataset/val
TestDataset:
!ImageFolder
image_dir: data/test
anno_path: COCO_val_annos.json
dataset_dir: ../data/dataset/val
```
## 3.2 runtime.yml
该配置文件记录了有关训练的相关信息,包括使用的硬件、记录次数等。
此部分内容暂无需修改。
```
use_gpu: true
use_xpu: false
log_iter: 20
save_dir: output
snapshot_epoch: 1
print_flops: false
```
## 3.3 picodet_esnet.yml
该配置文件记录了有关picodet的backbone所使用的的ESNet的相关参数设置。
为了方便模型的运行,将预训练权重修改为使用相同模型在COCO数据集上的预训练模型进行。
```
architecture: PicoDet
pretrain_weights: weights/picodet_l_640_coco.pdparams
PicoDet:
backbone: ESNet
neck: CSPPAN
head: PicoHead
ESNet:
scale: 1.0
feature_maps: [4, 11, 14]
act: hard_swish
channel_ratio: [0.875, 0.5, 1.0, 0.625, 0.5, 0.75, 0.625, 0.625, 0.5, 0.625, 1.0, 0.625, 0.75]
CSPPAN:
out_channels: 128
use_depthwise: True
num_csp_blocks: 1
num_features: 4
PicoHead:
conv_feat:
name: PicoFeat
feat_in: 128
feat_out: 128
num_convs: 4
num_fpn_stride: 4
norm_type: bn
share_cls_reg: True
fpn_stride: [8, 16, 32, 64]
feat_in_chan: 128
prior_prob: 0.01
reg_max: 7
cell_offset: 0.5
loss_class:
name: VarifocalLoss
use_sigmoid: True
iou_weighted: True
loss_weight: 1.0
loss_dfl:
name: DistributionFocalLoss
loss_weight: 0.25
loss_bbox:
name: GIoULoss
loss_weight: 2.0
assigner:
name: SimOTAAssigner
candidate_topk: 10
iou_weight: 6
nms:
name: MultiClassNMS
nms_top_k: 1000
keep_top_k: 100
score_threshold: 0.025
nms_threshold: 0.6
```
## 3.4 optimizer_300e.yml
该配置文件记录了有关学习率和优化器相关的参数配置。
由于原学习率0.3为在多卡环境下训练的设置,我们仅在单卡训练,且batch尺寸约为默认尺寸的一半,因此设为0.04。
```
epoch: 70
LearningRate:
base_lr: 0.04
schedulers:
- !CosineDecay
max_epochs: 300
- !LinearWarmup
start_factor: 0.1
steps: 300
OptimizerBuilder:
optimizer:
momentum: 0.9
type: Momentum
regularizer:
factor: 0.00004
type: L2
```
## 3.5 picodet_640_reader.yml
该配置文件记录了数据读取相关的参数配置。
根据显卡显存情况,因此可以将batch设置为数据集的一半图片,即30,读取线程(num_workers)设为3。将数据集的均值和方差按此前计算的值进行替换。
```
worker_num: 3
TrainReader:
sample_transforms:
- Decode: {}
- RandomCrop: {}
- RandomFlip: {prob: 0.5}
- RandomDistort: {}
batch_transforms:
- BatchRandomResize: {target_size: [576, 608, 640, 672, 704], random_size: True, random_interp: True, keep_ratio: False}
- NormalizeImage: {is_scale: true, mean: [0.412,0.411,0.414], std: [0.252,0.253,0.251]}
- Permute: {}
batch_size: 30
shuffle: true
drop_last: false
collate_batch: false
EvalReader:
sample_transforms:
- Decode: {}
- Resize: {interp: 2, target_size: [640, 640], keep_ratio: False}
- NormalizeImage: {is_scale: true, mean: [0.412,0.411,0.414], std: [0.252,0.253,0.251]}
- Permute: {}
batch_transforms:
- PadBatch: {pad_to_stride: 32}
batch_size: 11
shuffle: false
TestReader:
inputs_def:
image_shape: [1, 3, 640, 640]
sample_transforms:
- Decode: {}
- Resize: {interp: 2, target_size: [640, 640], keep_ratio: False}
- NormalizeImage: {is_scale: true, mean: [0.412,0.411,0.414], std: [0.252,0.253,0.251]}
- Permute: {}
batch_transforms:
- PadBatch: {pad_to_stride: 32}
batch_size: 1
shuffle: false
```
## 3.6 picodet_l_640_coco.yml
该配置文件为最主要的配置文件,记录了其他几个配置文件的位置,以及相关重要的参数设置,这里的参数其实与记录的几个配置文件相同,但优先按该文件的设置,因此将之前五个文件中的设置在该文件中再次修改或直接删除即可。
```
_BASE_: [
'../datasets/coco_detection.yml',
'../runtime.yml',
'_base_/picodet_esnet.yml',
'_base_/optimizer_300e.yml',
'_base_/picodet_640_reader.yml',
]
weights: output/picodet_l_640_coco/model_final
find_unused_parameters: True
use_ema: true
cycle_epoch: 40
snapshot_epoch: 10
ESNet:
scale: 1.25
feature_maps: [4, 11, 14]
act: hard_swish
channel_ratio: [0.875, 0.5, 1.0, 0.625, 0.5, 0.75, 0.625, 0.625, 0.5, 0.625, 1.0, 0.625, 0.75]
CSPPAN:
out_channels: 160
PicoHead:
conv_feat:
name: PicoFeat
feat_in: 160
feat_out: 160
num_convs: 4
num_fpn_stride: 4
norm_type: bn
share_cls_reg: True
feat_in_chan: 160
```
# 4 模型训练
按上述配置文件进行模型训练,采用边训练边验证的模式,并且记录log文件,可以用于后续的loss和ap曲线的绘制。
```
# 训练
!python tools/train.py -c configs/picodet/picodet_l_640_coco.yml --eval --use_vdl=true --vdl_log_dir=vdl_dir/scalar
```
# 5 模型评估
对训练模型进行评估,mAP约为19.2。
```
# 评估
!python tools/eval.py -c configs/picodet/picodet_l_640_coco.yml -o weights=output/model_final.pdparams
```
# 6 模型导出
为了使用训练好的模型进行推理,将模型进行导出,可以用于进一步部署使用。
```
# 模型导出
!python tools/export_model.py -c configs/picodet/picodet_l_640_coco.yml \
-o weights=output/model_final.pdparams --output_dir=inference_model
```
# 7 模型推理
从测试集中选取某张图片进行推理测试。
```
# 推理
!python tools/infer.py -c configs/picodet/picodet_l_640_coco.yml \
-o weights=output/model_final.pdparams \
--infer_img=/home/aistudio/data/dataset/test/66.jpg --output_dir infer_output/
```
推理的图片保存于PaddleDetection/infer_output/目录下,对该推理图片可视化。
```
import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
img = cv2.imread("infer_output/66.jpg")
plt.imshow(img)
plt.show()
```
可以看到,图片中的车损位置被成功检出,但置信度不高,仅有0.3。
| github_jupyter |
# Pattern Mining - Association Rule Mining
A *frequent pattern* is a substructure that appears frequently in a dataset. Finding the frequent patterns of a dataset is a essential step in data mining tasks such as *feature extraction* and a necessary ingredient of *association rule learning*. This kind of algorithms are extremely useful in the field of *Market Basket Analysis*, which in turn provide retailers with invaluable information about their customer shopping habbits and needs.
Here, I will shortly describe the **GraphLab Create frequent pattern mining toolkit**, the tools it provides and its functionality. Major advantage of this high-level ML toolkit is the ease it provides to train an association rule mining algorithm, as well as the high interpretability of the returned results. Under the hood the GLG frequent pattern mining toolkit runs a [TFP-Growth algorithm](https://www.computer.org/csdl/trans/tk/2005/05/k0652-abs.html), introduced by Wang, Jianyong, et al. in 2005. For a recent review of the various directions in the field consult [Han, Jiawei, et al. "Frequent pattern mining: current status and future directions.", Data Mining and Knowledge Discovery 15.1 (2007): 55-86](http://link.springer.com/article/10.1007%2Fs10618-006-0059-1).
## Load GraphLab Create and Necessary Helper Functions
```
import graphlab as gl
from graphlab import aggregate as agg
from visualization_helper_functions import *
```
## A simple retailer example: Loading Data, Exploratory Data Analysis
Here we discuss a simple example of receipt data from a bakery. The dataset consists of items like `'ApplePie'` and `'GanacheCookie'`. The task is to identify sets of items that are frequently bought together. The dataset consists of *266209 rows* and *6 columns* which look like the following. The dataset was constructed by modifying the [Extended BAKERY dataset](https://wiki.csc.calpoly.edu/datasets/wiki/ExtendedBakery).
```
bakery_sf = gl.SFrame('./bakery_sf')
bakery_sf
```
As we can see below, all the coffee products have similar sale frequencies and there is no some particular subset of products that is more preferred than the remaining ones.
```
%matplotlib inline
item_freq_plot(bakery_sf, 'Item', ndigits=3, topk=30,
seaborn_style='whitegrid', seaborn_palette='deep', color='b')
```
Next, we split the **`bakery_sf`** data set in a **training** and a **test part**.
```
(train, test) = bakery_sf.random_split(0.8, seed=1)
print 'Number of Rows in training set [80pct of Known Examples]: %d' % train.num_rows()
print 'Number of Rows in test set [20pct of Known Examples]: %d' % test.num_rows()
```
In order to run a frequent pattern mining algorithm, we require an **item column**, (the column **`'Item'`** in this example), and a set of **feature columns** that *uniquely identify* a transaction (the columns **`['Receipt', 'StoreNum']`** in this example, since we need to take in account the geophraphical location of each store and the accompanied social-economic criteria that may exist).
In addition we need to specify the 3 basic parameters of the **FP-Growth algorithm** which is called by the high-level GraphLab Create (GLC) function. These are:
* **`min_support`:** The minimum number of times that a pattern must occur in order to be considered a *frequent* one. Here, we choose a threshold of 1‰ of total transactions in record to be the `min_support`.
* **`max_patterns`:** The maximum number of frequent patterns to be mined.
* **`min_length`:** The minimum size (number of elements in the set) of each pattern being mined.
```
min_support = int(train.num_rows()*0.001)
model = gl.frequent_pattern_mining.create(train, 'Item',
features=['Receipt', 'StoreNum'],
min_support=min_support,
max_patterns=500,
min_length=4)
```
Here, we obtain the most frequent feature patterns.
```
print 'The most frequent feature patters are:'
print '-----------------------------------------'
model.frequent_patterns.print_rows(max_column_width=80, max_row_width=90)
```
Note that the **`'pattern'`** column contains the patterns that occur frequently together, whereas the **`'support'`** column contains the number of times these patterns occur together in the entire dataset.
In this example, the pattern:
```
[CoffeeEclair, HotCoffee, ApplePie, AlmondTwist]
```
occurred 877 times in the training data.
**Definition**
> A **frequent pattern** is a *set of items* with a *support greater than* user-specified **minimum support threshold**.
However, there is significant redundancy in mining frequent patterns; every subset of a frequent pattern is also frequent (e.g. `'CoffeeEclair'` must be frequent if `['CoffeeEclair'`, `'HotCoffee']` is frequent). The frequent pattern mining toolkit avoids this redundancy by mining the closed frequent patterns, i.e. *frequent patterns with no superset of the same support*. This is achieved by the very design of the [TFP-Growth Algorithm](https://www.computer.org/csdl/trans/tk/2005/05/k0652-abs.html).
Note, that by relaxing the **`min_length`** requirement, one can obtain more frequent patterns of sold coffe products.
```
min_support = int(train.num_rows()*0.001)
model = gl.frequent_pattern_mining.create(train, 'Item',
features=['Receipt', 'StoreNum'],
min_support=min_support,
max_patterns=500,
min_length=3)
print 'The most frequent feature patters are:'
print '-----------------------------------------'
model.frequent_patterns.print_rows(num_rows=35, max_column_width=80, max_row_width=90)
```
Alternatively, by decreasing the **`min_support`** one can obtain more patterns of sold coffee products which are again assumed frequent but with respect to this new threshold.
```
min_support = int(train.num_rows()*(1e-04))
model = gl.frequent_pattern_mining.create(train, 'Item',
features=['Receipt', 'StoreNum'],
min_support=min_support,
max_patterns=500,
min_length=4)
print 'The most frequent feature patters are:'
print '-----------------------------------------'
model.frequent_patterns.print_rows(num_rows=60, max_row_width=90, max_column_width=80)
```
To see some details of the trained model:
```
print model
```
## Top-k frequent patterns
In practice, we rarely know the appropriate **`min_support`** threshold to use. As an alternative to specifying a minimum support, we can specify a **maximum number of patterns** to mine using the **`max_patterns`** parameter. Instead of mining all patterns above a minimum support threshold, we mine the most frequent patterns until the maximum number of closed patterns are found. For large data sets, this mining process can be time-consuming. We recommend specifying a somehow *large initial minimum support* bound to speed up the mining.
```
min_support = int(train.num_rows()*1e-03)
top5_freq_patterns = gl.frequent_pattern_mining.create(train, 'Item',
features=['Receipt', 'StoreNum'],
min_support=min_support,
max_patterns=5,
min_length=4)
```
The top-5 most frequent patterns are:
```
print top5_freq_patterns
```
We can always save the trained model by calling:
```
top5_freq_patterns.save('./top5_freq_patterns_model')
```
## Business Use Case: Compute Association Rules and Make Predictions
An association rule is an ordered pair of item sets (prefix \\( A \\), prediction \\( B \\)) denoted \\( A\Rightarrow B \\) such that \\( A \\) and \\( B \\) are disjoint whereas \\( A\cup B \\) is frequent. The most popular criteria for scoring association rules is to measure the **confidence of the rule**: the ratio of the support of \\( A\cup B \\) to the support of \\( A \\).
\\[ \textrm{Confidence}(A\Rightarrow B) = \frac{\textrm{Supp}(A\cup B)}{\textrm{Supp}(A)}. \\]
The confidence of the rule \\( A\Rightarrow B \\) is our empirical estimate of the conditional probability for \\( B \\) given \\( A \\).
One can make predictions using the **`predict()`** or **`predict_topk()`** method for single and multiple predictions respectively. The output of both the methods is an **SFrame** with the following columns:
* **prefix**: The antecedent or left-hand side of an association rule. It must be a frequent pattern and a subset of the associated pattern.
* **prediction**: The consequent or right-hand side of the association rule. It must be disjoint of the prefix.
* **confidence**: The confidence of the association rule as defined above.
* **prefix support**: The frequency of the prefix pattern in the training data.
* **joint support**: The frequency of the co-occurrence ( prefix + prediction) in the training data
```
predictions = top5_freq_patterns.predict(test)
predictions.print_rows(max_row_width=100)
```
## Feature Engineering to help other ML Tasks in Pipeline
### The `.extract_feature()` method
Using the set of closed patterns, we can convert pattern data to binary features vectors. These feature vectors can be used for other machine learning tasks, such as **clustering** or **classification**. For each input pattern `x`, the `j-th` extracted feature `f_{x}[j]` is a binary indicator of whether the `j-th` closed pattern is contained in `x`.
First, we train the **`top100_freq_patterns`** model as shown below:
```
top100_freq_patterns = gl.frequent_pattern_mining.\
create(train, 'Item',
features=['Receipt', 'StoreNum'],
# occurs at least once in our data record
min_support=1,
# do not search for more than 100 patterns
max_patterns = 100,
# test data have only one coffee product sold per tid .
# We search for patterns of at least 2 coffee products
min_length=2)
```
Here are the 100 unique closed patterns which are found frequent:
```
top100_freq_patterns.frequent_patterns.\
print_rows(num_rows=100, max_row_width=90, max_column_width=80)
```
Next, we apply the **`extract_features()`** method of this newly trained **`top100_freq_patterns`** model on the **`test`** data set.
```
features = top100_freq_patterns.extract_features(train)
```
Once the features are extracted, we can use them downstream in other applications such as **clustering**, **classification**, **churn prediction**, **recommender systems** etc.
```
features.print_rows(num_rows=10, max_row_width=90, max_column_width=100)
```
### Example: Employee Space Clustering by using occurrences of frequency patterns
First, we provide an aggregated form of our data by selecting one **Selling Employee (`EmpId`)** at random.
```
emps = train.groupby(['Receipt', 'StoreNum'],
{'EmpId': agg.SELECT_ONE('EmpId')})
emps
```
Next, we count the instances that each of the **`top100_freq_patterns`** occurs per **`EmpId`**.
```
emp_space = emps.join(features).\
groupby('EmpId', {'all_features': agg.SUM('extracted_features')})
emp_space
```
Finally, we train a **kmeans** algorithm to produce a **3 centered cluster**.
```
cl_model = gl.kmeans.create(emp_space,
features = ['all_features'],
num_clusters=3)
emp_space['cluster_id'] = cl_model['cluster_id']['cluster_id']
emp_space
```
And we can provide a countplot of the **Number of Stores** per **Cluster Id** as below.
```
%matplotlib inline
segments_countplot(emp_space, x='cluster_id',
figsize_tuple=(12,7), title='Number of Stores per Cluster ID')
```
| github_jupyter |
# Functions and Methods Homework Solutions
____
**Write a function that computes the volume of a sphere given its radius.**
```
def vol(rad):
return (4.0/3)*(3.14)*(rad**3)
```
___
**Write a function that checks whether a number is in a given range (Inclusive of high and low)**
```
def ran_check(num,low,high):
#Check if num is between low and high (including low and high)
if num in range(low,high+1):
print " %s is in the range" %str(num)
else :
print "The number is outside the range."
```
If you only wanted to return a boolean:
```
def ran_bool(num,low,high):
return num in range(low,high+1)
ran_bool(3,1,10)
```
____
**Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters.**
Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'
Expected Output :
No. of Upper case characters : 4
No. of Lower case Characters : 33
If you feel ambitious, explore the Collections module to solve this problem!
```
def up_low(s):
d={"upper":0, "lower":0}
for c in s:
if c.isupper():
d["upper"]+=1
elif c.islower():
d["lower"]+=1
else:
pass
print "Original String : ", s
print "No. of Upper case characters : ", d["upper"]
print "No. of Lower case Characters : ", d["lower"]
s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
up_low(s)
```
____
**Write a Python function that takes a list and returns a new list with unique elements of the first list.**
Sample List : [1,1,1,1,2,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
```
def unique_list(l):
# Also possible to use list(set())
x = []
for a in l:
if a not in x:
x.append(a)
return x
unique_list([1,1,1,1,2,2,3,3,3,3,4,5])
```
____
**Write a Python function to multiply all the numbers in a list.**
Sample List : [1, 2, 3, -4]
Expected Output : -24
```
def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
multiply([1,2,3,-4])
```
____
**Write a Python function that checks whether a passed string is palindrome or not.**
Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
```
def palindrome(s):
s = s.replace(' ','') # This replaces all spaces " " with no space ''. (Fixes issues with strings that have spaces)
return s == s[::-1] # Check through slicing
palindrome('nurses run')
palindrome('abcba')
```
____
**Hard**:
Write a Python function to check whether a string is pangram or not.
Note : Pangrams are words or sentences containing every letter of the alphabet at least once.
For example : "The quick brown fox jumps over the lazy dog"
Hint: Look at the string module
```
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(str1.lower())
ispangram("The quick brown fox jumps over the lazy dog")
string.ascii_lowercase
```
| github_jupyter |
# TD3
### **Note on this tutorials:**
**They mostly contain low level implementations explaining what is going on inside the library.**
**Most of the stuff explained here is already available out of the box for your usage.**
If you do not care about the detailed implementation with code, go to the [Library Basics]/algorithms how to/td3, there is a 20 liner version
```
import numpy as np
import pandas as pd
from tqdm.auto import tqdm
import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
import torch_optimizer as optim
from IPython.display import clear_output
import matplotlib.pyplot as plt
%matplotlib inline
# comment out if you are not using themes
from jupyterthemes import jtplot
jtplot.style(theme='grade3')
# == recnn ==
import sys
sys.path.append("../../")
import recnn
cuda = torch.device('cuda')
# ---
frame_size = 10
batch_size = 25
n_epochs = 100
plot_every = 30
step = 0
# ---
tqdm.pandas()
# embeddgings: https://drive.google.com/open?id=1EQ_zXBR3DKpmJR3jBgLvt-xoOvArGMsL
dirs = recnn.data.env.DataPath(
base="../../data/",
embeddings="embeddings/ml20_pca128.pkl",
ratings="ml-20m/ratings.csv",
cache="cache/frame_env.pkl", # cache will generate after you run
use_cache=True
)
env = recnn.data.env.FrameEnv(dirs, frame_size, batch_size)
def soft_update(net, target_net, soft_tau=1e-2):
for target_param, param in zip(target_net.parameters(), net.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - soft_tau) + param.data * soft_tau
)
def run_tests():
test_batch = next(iter(env.test_dataloader))
losses = td3_update(step, test_batch, params, writer, learn=False)
gen_actions = debug['gen_action']
true_actions = env.base.embeddings.detach().cpu().numpy()
f = plotter.kde_reconstruction_error(ad, gen_actions, true_actions, cuda)
writer.add_figure('rec_error',f, losses['step'])
return losses
def td3_update(step, batch, params, writer, learn=True):
state, action, reward, next_state, done = recnn.data.get_base_batch(batch)
# --------------------------------------------------------#
# Value Learning
reward = reward.unsqueeze(1)
done = done.unsqueeze(1)
next_action = target_policy_net(next_state)
noise = torch.normal(torch.zeros(next_action.size()),
params['noise_std']).to(cuda)
noise = torch.clamp(noise, -params['noise_clip'], params['noise_clip'])
next_action += noise
with torch.no_grad():
target_q_value1 = target_value_net1(next_state, next_action)
target_q_value2 = target_value_net2(next_state, next_action)
target_q_value = torch.min(target_q_value1, target_q_value2)
expected_q_value = reward + (1.0 - done) * params['gamma'] * target_q_value
q_value1 = value_net1(state, action)
q_value2 = value_net2(state, action)
value_loss1 = value_criterion(q_value1, expected_q_value.detach())
value_loss2 = value_criterion(q_value2, expected_q_value.detach())
if learn:
value_optimizer1.zero_grad()
value_loss1.backward()
value_optimizer1.step()
value_optimizer2.zero_grad()
value_loss2.backward()
value_optimizer2.step()
else:
debug['next_action'] = next_action
writer.add_figure('next_action',
recnn.utils.pairwise_distances_fig(next_action[:50]), step)
writer.add_histogram('value1', q_value1, step)
writer.add_histogram('value2', q_value2, step)
writer.add_histogram('target_value', target_q_value, step)
writer.add_histogram('expected_value', expected_q_value, step)
# --------------------------------------------------------#
# Policy learning
gen_action = policy_net(state)
policy_loss = value_net1(state, gen_action)
policy_loss = -policy_loss
if not learn:
debug['gen_action'] = gen_action
writer.add_figure('gen_action',
recnn.utils.pairwise_distances_fig(gen_action[:50]), step)
writer.add_histogram('policy_loss', policy_loss, step)
policy_loss = policy_loss.mean()
# delayed policy update
if step % params['policy_update'] == 0 and learn:
policy_optimizer.zero_grad()
policy_loss.backward()
torch.nn.utils.clip_grad_norm_(policy_net.parameters(), -1, 1)
policy_optimizer.step()
soft_update(value_net1, target_value_net1, soft_tau=params['soft_tau'])
soft_update(value_net2, target_value_net2, soft_tau=params['soft_tau'])
losses = {'value1': value_loss1.item(),
'value2': value_loss2.item(),
'policy': policy_loss.item(),
'step' : step}
recnn.utils.write_losses(writer, losses, kind='train' if learn else 'test')
return losses
# === TD3 settings ===
params = {
'gamma': 0.99,
'noise_std': 0.5,
'noise_clip': 3,
'soft_tau': 0.001,
'policy_update': 10,
'policy_lr': 1e-5,
'value_lr': 1e-5,
'actor_weight_init': 25e-2,
'critic_weight_init': 6e-1,
}
# === end ===
value_net1 = recnn.nn.models.Critic(1290, 128, 256, params['critic_weight_init']).to(cuda)
value_net2 = recnn.nn.models.Critic(1290, 128, 256, params['critic_weight_init']).to(cuda)
policy_net = recnn.nn.models.Actor(1290, 128, 256, params['actor_weight_init']).to(cuda)
target_value_net1 = recnn.nn.models.Critic(1290, 128, 256).to(cuda)
target_value_net2 = recnn.nn.models.Critic(1290, 128, 256).to(cuda)
target_policy_net = recnn.nn.models.Actor(1290, 128, 256).to(cuda)
soft_update(value_net1, target_value_net1, soft_tau=1.0)
soft_update(value_net2, target_value_net2, soft_tau=1.0)
soft_update(policy_net, target_policy_net, soft_tau=1.0)
value_criterion = nn.MSELoss()
value_optimizer1 = optim.Ranger(value_net1.parameters(), lr=params['value_lr'], weight_decay=1e-2)
value_optimizer2 = optim.Ranger(value_net2.parameters(), lr=params['value_lr'], weight_decay=1e-2)
policy_optimizer = optim.Ranger(policy_net.parameters(), lr=params['policy_lr'], weight_decay=1e-5)
ad = recnn.nn.models.AnomalyDetector().to(cuda)
ad.load_state_dict(torch.load('../../models/anomaly.pt'))
ad.eval()
loss = {
'train': {'value1': [], 'value2': [], 'policy': [], 'step': []},
'test': {'value1': [], 'value2': [], 'policy': [], 'step': []}
}
debug = {}
writer = SummaryWriter(log_dir='../../runs')
plotter = recnn.utils.Plotter(loss, [['value1', 'policy']],)
for epoch in range(n_epochs):
for batch in tqdm(env.train_dataloader):
loss = td3_update(step, batch, params, writer)
plotter.log_losses(loss)
step += 1
if step % plot_every == 0:
clear_output(True)
print('step', step)
test_loss = run_tests()
plotter.log_losses(test_loss, test=True)
plotter.plot_loss()
torch.save(value_net1.state_dict(), "../../models/td3_value.pt")
torch.save(policy_net.state_dict(), "../../models/td3_policy.pt")
gen_actions = debug['gen_action']
true_actions = env.base.embeddings.numpy()
ad = recnn.nn.AnomalyDetector().to(cuda)
ad.load_state_dict(torch.load('../../models/anomaly.pt'))
ad.eval()
plotter.plot_kde_reconstruction_error(ad, gen_actions, true_actions, cuda)
```
| github_jupyter |
```
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Install Pipeline SDK - This only needs to be ran once in the enviroment.
!python3 -m pip install 'kfp>=0.1.31' --quiet
!pip3 install tensorflow==1.14 --upgrade
```
## KubeFlow Pipelines Serving Component
In this notebook, we will demo:
* Saving a Keras model in a format compatible with TF Serving
* Creating a pipeline to serve a trained model within a KubeFlow cluster
Reference documentation:
* https://www.tensorflow.org/tfx/serving/architecture
* https://www.tensorflow.org/beta/guide/keras/saving_and_serializing
* https://www.kubeflow.org/docs/components/serving/tfserving_new/
### Setup
```
# Set your output and project. !!!Must Do before you can proceed!!!
project = 'Your-Gcp-Project-ID' #'Your-GCP-Project-ID'
model_name = 'model-name' # Model name matching TF_serve naming requirements
import time
ts = int(time.time())
model_version = str(ts) # Here we use timestamp as version to avoid conflict
output = 'Your-Gcs-Path' # A GCS bucket for asset outputs
KUBEFLOW_DEPLOYER_IMAGE = 'gcr.io/ml-pipeline/ml-pipeline-kubeflow-deployer:a8fcec5f702fc2528c87ed6fd698b9cfca8b509e'
model_path = '%s/%s' % (output,model_name)
model_version_path = '%s/%s/%s' % (output,model_name,model_version)
```
### Load a Keras Model
Loading a pretrained Keras model to use as an example.
```
import tensorflow as tf
model = tf.keras.applications.NASNetMobile(input_shape=None,
include_top=True,
weights='imagenet',
input_tensor=None,
pooling=None,
classes=1000)
```
### Saved the Model for TF-Serve
Save the model using keras export_saved_model function. Note that specifically for TF-Serve the output directory should be structure as model_name/model_version/saved_model.
```
tf.keras.experimental.export_saved_model(model, model_version_path)
```
### Create a pipeline using KFP TF-Serve component
```
def kubeflow_deploy_op():
return dsl.ContainerOp(
name = 'deploy',
image = KUBEFLOW_DEPLOYER_IMAGE,
arguments = [
'--model-export-path', model_path,
'--server-name', model_name,
]
)
import kfp
import kfp.dsl as dsl
# The pipeline definition
@dsl.pipeline(
name='Sample model deployer',
description='Sample for deploying models using KFP model serving component'
)
def model_server():
deploy = kubeflow_deploy_op()
```
Submit pipeline for execution on Kubeflow Pipelines cluster
```
kfp.Client().create_run_from_pipeline_func(model_server, arguments={})
#vvvvvvvvv This link leads to the run information page. (Note: There is a bug in JupyterLab that modifies the URL and makes the link stop working)
```
| github_jupyter |
```
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
import os
#print(os.listdir("../input"))
# Any results you write to the current directory are saved as output.
#Import some packages to use
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
#To see our directory
import os
import random
import gc
train_dir = '../input/thesis/Thesis/70'
test_dir = '../input/thesis/Thesis/20'
train_bas = ['../input/thesis/Thesis/70/{}'.format(i) for i in os.listdir(train_dir) if 'melanoma' in i] #get dog images
train_others = ['../input/thesis/Thesis/70/{}'.format(i) for i in os.listdir(train_dir) if not 'melanoma' in i] #get cat images
test_imgs = ['../input/thesis/Thesis/20/{}'.format(i) for i in os.listdir(test_dir)] #get test images
#train_imgs = train_dogs[:2000] + train_cats[:2000] # slice the dataset and use 2000 in each class
#train_imgs = train_mel[:600] + train_others[:600]
train_imgs = train_bas + train_others
random.shuffle(train_imgs) # shuffle it randomly
#Clear list that are useless
del train_bas
del train_others
gc.collect()
nrows = 150
ncolumns = 150
channels = 1 #change to 1 if you want to use grayscale image
#A function to read and process the images to an acceptable format for our model
def read_and_process_image(list_of_images):
"""
Returns two arrays:
X is an array of resized images
y is an array of labels
"""
X = [] # images
y = [] # labels
for image in list_of_images:
X.append(cv2.resize(cv2.imread(image, cv2.IMREAD_COLOR), (nrows,ncolumns), interpolation=cv2.INTER_CUBIC)) #Read the image
#get the labels
if 'basalcell' in image:
y.append(1)
elif not 'basalcell' in image:
y.append(0)
return X, y
X, y = read_and_process_image(train_imgs)
plt.figure(figsize=(20,10))
columns = 5
for i in range(columns):
plt.subplot(5 / columns + 1, columns, i + 1)
plt.imshow(X[i])
import seaborn as sns
del train_imgs
gc.collect()
#Convert list to numpy array
X = np.array(X)
y = np.array(y)
#Lets plot the label to be sure we just have two class
sns.countplot(y)
plt.title('Labels for basalcell vs not basalcell')
from sklearn.model_selection import train_test_split
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.20, random_state=2)
from keras.utils import to_categorical
#del X
#del y
gc.collect()
#get the length of the train and validation data
ntrain = len(X_train)
nval = len(X_val)
#We will use a batch size of 32. Note: batch size should be a factor of 2.***4,8,16,32,64...***
batch_size = 64
from keras.models import Sequential
from keras import layers
from keras import models
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array, load_img
from keras.layers import Dense, Conv2D, Flatten
model = models.Sequential()
model.add(layers.Conv2D(128, (5, 5), activation='relu',input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((5, 5)))
model.add(layers.Conv2D(64, (4, 4), activation='relu'))
model.add(layers.MaxPooling2D((4, 4)))
model.add(layers.Dropout(0.2))
model.add(layers.Conv2D(32, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((3, 3)))
model.add(layers.Dropout(0.25))
model.add(layers.Flatten())
model.add(layers.Dropout(0.4)) #Dropout for regularization
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.summary()
#model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc'])
from keras import optimizers
model.compile(loss='binary_crossentropy', optimizer=optimizers.Adamax(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0), metrics=['acc'])
train_datagen = ImageDataGenerator(rescale=1./255, #Scale the image between 0 and 1
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,)
val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow(X_train, y_train, batch_size=batch_size)
val_generator = val_datagen.flow(X_val, y_val, batch_size=batch_size)
history = model.fit_generator(train_generator,
steps_per_epoch=ntrain // batch_size,
epochs=70,
validation_data=val_generator,
validation_steps=nval // batch_size)
model.save_weights('model_wieghts.h5')
model.save('model_keras.h5')
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
#Train and validation accuracy
plt.plot(epochs, acc, 'b', label='Training accurarcy')
plt.plot(epochs, val_acc, 'r', label='Validation accurarcy')
plt.title('Training and Validation accurarcy')
plt.legend()
plt.figure()
#Train and validation loss
plt.plot(epochs, loss, 'b', label='Training loss')
plt.plot(epochs, val_loss, 'r', label='Validation loss')
plt.title('Training and Validation loss')
plt.legend()
plt.show()
X_test, y_test = read_and_process_image(test_imgs) #Y_test in this case will be empty.
x = np.array(X_test)
test_datagen = ImageDataGenerator(rescale=1./255)
i = 0
text_labels = []
plt.figure(figsize=(30,20))
for batch in test_datagen.flow(x, batch_size=1):
pred = model.predict(batch)
print(pred)
if pred > 0.5:
text_labels.append(1)
else:
text_labels.append(0)
i += 1
if i==600:
break
print('done')
#text_labels=text_labels[0:200]
from sklearn.metrics import accuracy_score
accuracy_score(y_test, text_labels)
```
| github_jupyter |
Extending SMRT
=============
There are different ways to extend SMRT, here we address the case of ice permittivity.
Open the smrt/permittivity/ice.py file in an editor to see how it looks like: permittivity functions are defined as normal python functions with several arguments. There is some rules or some tricks:
- `frequency` is the first one and MUST be there for any permittivity function.
- the second one is often `temperature`, this is recommended.
- optionaly other arguments depending on the formulation.
How SMRT know what to do with this variable number of arguments ?
We heavily use dynamical nature of python because we really want users to define new arguments at will, without changing the core of the model and keeping the compatibility. Here for the permittivity, the trick is in the declaration `@layer_properties("temperature", "salinity")` put just before the function declaration. This tells SMRT that this function needs to temperature and salinity arguments that are taken from the layer for which we want to compute the permittivity. The important point is that **any new arguments can be defined without changing anything in SMRT core**.
Example:
```
from smrt import make_model, make_snowpack, sensor_list
from smrt.core.layer import layer_properties
# let's defined a new function
@layer_properties("temperature", "potassium_concentration")
def new_ice_permittivity(frequency, temperature, potassium_concentration):
return 3.1884 + 1j * (0.1 + potassium_concentration * 0.001) # this is purely imaginative!!!!!!!!
# let's defined the snowpack
thickness = [10]
density = 350
temperature = 270
radius = 100e-6
sp = make_snowpack(thickness, 'sticky_hard_spheres',
density=density, radius=radius, temperature=temperature,
calcium_concentration=0.1,
ice_permittivity_model=new_ice_permittivity) # here we declare we want the new permittivity
sp.layers[0].calcium_concentration
sensor = sensor_list.amsre()
m = make_model("iba", "dort")
result = m.run(sensor, sp)
# execute this code and see the last line of the error message below
# does it make sense ? The call to the new_ice_permittivity function needs
# potassium_concentration to be provided.
# to fix the problem, just add potassium_concentration=5.0e-3 to the make_snowpack call and reexcute.
# the cells.
# Remember: "potassium_concentration" never appears in SMRT code, it is purely user-defined.
# Any other variables (as long as it does not colleige with internal SMRT naming) is valid.
# "K_conc", "myarg1" are valid though we strongly recommend explicit naming such as potassium_concentration
```
| github_jupyter |
# CDL Quantum Hackathon 2020
----
## PennyLane challenge
>**Challenge description**: PennyLane contains the quantum-aware optimizers Rotosolve, QNG, and Rosalin. Rewrite them as PyTorch or TensorFlow native optimizers and provide a tutorial showing how they can be used to train a quantum model.
### Description of notebook
This notebook demonstrates that two of the specified quantum-aware optimizers; Rotosolve and Quantum Natural Gradient are implemented in a PyTorch generic way. They *do* require pennylane qNode circuits to provide some initial functionality, and they borrow the Fubini metric tensor calculation from PennyLane
```
from quantum_aware_optims import *
import pennylane as qml
from torch.optim import SGD, Adam
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set()
```
### The RotoSolve quantum optimizer
----
The example is from https://pennylane.ai/qml/demos/tutorial_rotoselect.html
```
n_wires = 2
dev = qml.device("default.qubit", analytic=True, wires=2)
def ansatz(params):
qml.RX(params[0], wires=0)
qml.RY(params[1], wires=1)
qml.CNOT(wires=[0, 1])
@qml.qnode(dev)
def circuit(params):
ansatz(params)
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))
@qml.qnode(dev)
def circuit2(params):
ansatz(params)
return qml.expval(qml.PauliX(0))
```
### Hamiltonian definition
We assume that the required expectation values that will be present in the final quantum circuit are evaluated from a list of quantum circuits, and that these are joined together corresponding to some mixing coefficients.
Further, we specify some initial parameters
```
qcircuits = [circuit, circuit2]
proportions = [0.5, 1.2, -0.2]
init_params = torch.tensor([0.1, 0.25])
```
We iterate the rotosolve algorithm 20 times
```
n_steps = 20
optim = RotoSolve(init_params,qcircuits,proportions)
"""RotoSolve inherits from torch.optim.Optimizer, but relies heavily
on native python operations. However, since it's non-gradient optimization
can't flow the gradients into a classical layer anyway"""
for i in range(n_steps):
loss = optim.step()
print(optim.final_params)
# Plotting results
plt.plot(list(range(n_steps+1)),optim.losses, 'o-')
plt.xlabel("Iteration number")
plt.ylabel("Cost")
plt.title("Rotosolve takes one iteration to find the optimal parameters for this Hamiltonian")
plt.show()
%%timeit
optim = RotoSolve(init_params,qcircuits,proportions)
loss = optim.step()
# Let's scale it up to a more complicated Hamiltonian
n_wires = 5
dev = qml.device("default.qubit", analytic=True, wires=n_wires)
def ansatz(params):
qml.RX(params[0], wires=0)
qml.RY(params[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.RX(params[2], wires=0)
qml.RY(params[4], wires=1)
qml.CNOT(wires=[0, 1])
qml.RX(params[2], wires=0)
qml.RY(params[4], wires=1)
@qml.qnode(dev)
def circuit(params):
ansatz(params)
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1)), qml.expval(qml.PauliZ(2)),qml.expval(qml.PauliY(4))
@qml.qnode(dev)
def circuit2(params):
ansatz(params)
return qml.expval(qml.PauliX(0)), qml.expval(qml.PauliX(1)), qml.expval(qml.PauliY(2))
qcircuits = [circuit, circuit2]
proportions = [0.5, 1.2, -0.2, 0.3, -0.8, 0.9, -1.8]
init_params = torch.randn(7)
n_steps = 20
optim = RotoSolve(init_params,qcircuits,proportions)
"""RotoSolve inherits from torch.optim.Optimizer, but relies heavily
on native python operations. However, since it's non-gradient optimization
can't flow the gradients into a classical layer anyway"""
for i in range(n_steps):
loss = optim.step()
print(optim.final_params)
# Plotting results
plt.plot(list(range(n_steps+1)),optim.losses, 'o-')
plt.xlabel("Iteration number")
plt.ylabel("Cost")
plt.title("For more complicated Hamiltonians can take more iterations")
plt.show()
dev = qml.device("default.qubit", wires=3)
@qml.qnode(dev)
def circuit(inputs, params):
# |psi_0>: state preparation
qml.RY(np.pi / 4, wires=0)
qml.RY(np.pi / 3, wires=1)
qml.RY(np.pi / 7, wires=2)
# V0(theta0, theta1): Parametrized layer 0
qml.RZ(params[0], wires=0)
qml.RZ(params[1], wires=1)
# W1: non-parametrized gates
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
# V_1(theta2, theta3): Parametrized layer 1
qml.RY(params[2], wires=1)
qml.RX(params[3], wires=2)
# W2: non-parametrized gates
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
return qml.expval(qml.PauliY(0))
qlayer = qml.qnn.TorchLayer(circuit, {"params": 4})
def loss_func(theta):
loss = qlayer(theta)
return loss
params = np.array([0.5, -0.123, 0.543, 0.233])
qlayer.params.data = torch.tensor(params)
optimQNG = QuantumNaturalGradientOptim([qlayer.params], circuit, lr=0.1)
lossesQNG = []
for i in range(100):
loss = loss_func(qlayer.params)
lossesQNG.append(loss)
loss.backward()
optimQNG.step()
optimQNG.zero_grad()
dev = qml.device("default.qubit", wires=3)
@qml.qnode(dev)
def circuit(inputs, params):
# |psi_0>: state preparation
qml.RY(np.pi / 4, wires=0)
qml.RY(np.pi / 3, wires=1)
qml.RY(np.pi / 7, wires=2)
# V0(theta0, theta1): Parametrized layer 0
qml.RZ(params[0], wires=0)
qml.RZ(params[1], wires=1)
# W1: non-parametrized gates
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
# V_1(theta2, theta3): Parametrized layer 1
qml.RY(params[2], wires=1)
qml.RX(params[3], wires=2)
# W2: non-parametrized gates
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
return qml.expval(qml.PauliY(0))
qlayer = qml.qnn.TorchLayer(circuit, {"params": 4})
def loss_func(theta):
loss = qlayer(theta)
return loss
params = np.array([0.5, -0.123, 0.543, 0.233])
qlayer.params.data = torch.tensor(params)
optim = SGD([qlayer.params], lr=0.1)
losses = []
for i in range(100):
loss = loss_func(qlayer.params)
losses.append(loss)
loss.backward()
optim.step()
optim.zero_grad()
plt.plot(list(range(100)),losses, label='SGD Loss')
plt.plot(list(range(100)),lossesQNG, label='QNG Loss')
plt.legend()
plt.title("The quantum natural gradient converges faster")
plt.show()
```
| github_jupyter |
# **OVERFITTING AND PRUNING**
The first part of the assignment will focus on overfitting and the second part will focus on pruning.
Overfitting is a condition when your model fits your training data too well including the noisy labels. Therefore it fails to generalise and its performance on the test set decreases.
Pruning is one method to overcome overfitting in Decision Trees. We will essentially look at one way of pruning.
## IMPORTING THE PACKAGES
The important packages have been imported for you.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
from sklearn.datasets import load_breast_cancer, load_diabetes
from sklearn.model_selection import train_test_split
import json
ans = [0]*8
```
## LOADING THE DATASET
We will load the dataset into the dataset variable. It is a diabetes dataset, a regression problem.
There are 11 features (numerical). They include measurements like bmi, sugar level etc. The column names have been set as Feature1, Feature2 etc for ease.
The target variable(numerical) is a quantitative measure of how much the disease has progressed.
```
# LOADING THE DATASET USING SKLEARN.
# THE CODE HAS BEEN WRITTEN FOR YOU. DO NOT MAKE ANY CHANGES.
data, label = load_diabetes(return_X_y = True) #loading the dataset
cols = ["Feature"+str(i) for i in range(1, 11)]
dataset = pd.DataFrame(np.concatenate((data, label.reshape(-1, 1)), axis = 1), columns = cols + ["Target"])
print("Shape of Dataset : ", dataset.shape, "\n")
dataset.head()
```
## DIVIDING THE DATASET INTO TRAIN AND TEST SET
You need to divide the dataset into train and test set using sklearn's train_test_split(x, y, random_state = 15, test_size = x) function. x is the fraction of examples to be alloted to the test set.
You need to divide the dataset in 8:2 ratio (train:test size).
**NOTE**: Remember to keep random_state = 15 (produces consistent results for evaluation purposes).
```
# DIVIDE THE DATASET INTO TRAIN AND TEST SET
# START YOUR CODE HERE:
# END YOUR CODE HERE
```
## **QUESTIONS**
## **OVERFITTING**
It is when your model is too complex and fits the noisy parts of your training data. Therefore it fails to generalize and achieves a bad result on the test set.
### **QUESTION 1**: Fit a Decision Tree Classifier with max_depth = 1 on the training dataset. Assign the train set mean squared error to ans[0] and the test set mean squared error to ans[1]. (1 mark)
```
# SOME PART OF THE CODE HAS BEEN WRITTEN FOR YOU
dt1 = DecisionTreeRegressor(max_depth = 1, random_state = 20) # The decision tree model you need to use. Don't change parameters.
# START YOUR CODE HERE:
# END YOUR CODE HERE
# SUBSTITUTE YOUR ANSWER IN PLACE OF None
ans[0] = None
ans[1] = None
```
### **QUESTION 2**: Fit a Decision Tree Classifier with max_depth = 2 on the training dataset. Assign the train set mean squared error to ans[2] and the test set mean squared error to ans[3]. (2 marks)
```
# SOME PART OF THE CODE HAS BEEN WRITTEN FOR YOU
dt4 = DecisionTreeRegressor(max_depth = 2, random_state = 20) # The decision tree model you need to use. Don't change parameters.
# START YOUR CODE HERE:
# END YOUR CODE HERE
# SUBSTITUTE YOUR ANSWER IN PLACE OF None
ans[2] = None
ans[3] = None
```
Did the accuracy for test set go down?
### **QUESTION 3**: Fit a Decision Tree Classifier with max_depth = 5 on the training dataset. Assign the train set accuracy to ans[4] and the test set accuracy to ans[5]. (2 marks)
```
# SOME PART OF THE CODE HAS BEEN WRITTEN FOR YOU
dt5 = DecisionTreeRegressor( max_depth = 5, random_state = 20) # The decision tree that you need to use. Don't change parameters.
# START YOUR CODE HERE:
# END YOUR CODE HERE
# SUBSTITUTE YOUR ANSWER IN PLACE OF None
ans[4] = None
ans[5] = None
```
Did the accuracy of the test set go down again? If not then why? Is overfitting the reason?
### **PLOTTING TRAIN AND TEST ACCURACY VS DEPTH OF TREES**
Let's try to plot the train and test accuracy vs max_depth.
Some part of the code has been written for you.
### **QUESTION 4**: Fit a Decision Tree Classifier with max_depth = d where d varies from 1-6 (both inclusive) on the training dataset. Assign the depth for which the test mean squared error is least, to ans[6]. (2 marks)
```
# SOME OF THE CODE HAS BEEN WRITTEN FOR YOU
depth = [] # List containing depth of decision tree.
train_mse = [] # Train accuracy of corresponding tree.
test_mse = [] # Test accuracy of corresponding tree.
# Dont forget to set random_state = 10 for your decision tree model.
# START YOUR CODE HERE:
# END YOUR CODE HERE
# SUBSTITUTE YOUR ANSWER IN PLACE OF None
ans[6] = None
```
### PLOTTING MEAN SQUARED ERROR VS THE DEPTH OF THE TREE
You can try to plot the train mean squared error and the test mean squared error vs the depth of the tree for gaining a better insight.
Some part of the matplotlib code has been written for you.
```
plt.plot(depth, train_mse, c = "r", label = "Train Mse")
plt.plot(depth, test_mse, c = "g", label = "Test Mse")
plt.legend()
plt.xlim(1)
plt.xticks(ticks = [i for i in range(1, 7)])
plt.title("Mean Squared Error vs Max Depth")
plt.xlabel("Max depth of the Decision Tree")
plt.ylabel("Mean Squared Error")
plt.show()
```
## **PRUNING**
We will look at one way to prune a decision tree.
## USING SKLEARN'S INBUILT PRUNING ALGORITHM
We will use a inbuilt parameter in the sklearn Decision Tree Regressor model called ccp_alpha to prune the Decision Trees formed.
**Minimal Cost Complexity Pruning**: One of the types of pruning in Decision Trees.
It utilises a complexity parameter **alpha** (alpha > 0). It is used to define a cost complexity measure of a tree as:-
$R_{alpha}(T) = R(T) + alpha*|T|$ where |T| are the number of terminal nodes in the tree, R(T) is the misclassification rate of the terminal nodes (a mean squared error type of quantity for regression and accuracy type of quantity for classification).
R(T) as you must have noticed always favours bigger trees as their misclassification rate would be always lower (remember we are talking about training set misclassification rate). So to penalise the bigger ones alpha*|T| term is added as it would favour a smaller tree.
alpha is what we call a hyperparameter. We need to find the best values of alpha to decrease the test set mean squared error.
### **QUESTION 5**: For which values of alpha (a) 10 (b) 50 (c) 100 (d) 200 is the test mean squared error the lowest? (We will use a tree with max_depth = 4). Assign your answer (the value of alpha and not the option) to ans[7]. (3 marks)
```
# SOME OF THE MATPLOTLIB CODE HAS BEEN WRITTEN FOR YOU
train_mse = [] # Train accuracy of corresponding tree.
test_mse = [] # Test accuracy of corresponding tree.
alphas = [10, 50, 100, 200]
# KEEP ALL PARAMETERS OTHER THAN ccp_alpha the same. REPLACE None WITH THE GIVEN VALUES OF ALPHA BEFORE FITTING ON THE TRAIN SET.
dt_temp = DecisionTreeRegressor(max_depth = 4, random_state = 10, ccp_alpha = None)
# START YOUR CODE HERE
# END YOUR CODE HERE
# SUBSTITUTE YOUR ANSWER IN PLACE OF None
ans[7] = None
import json
ans = [str(item) for item in ans]
filename = "group0_Saurav_Joshi_Issues_Classification"
# Eg if your name is Saurav Joshi and group id is 0, filename becomes
# filename = group0_Saurav_Joshi_Issues_Classification
```
## Do not change anything below!!
- Make sure you have changed the above variable "filename" with the correct value. Do not change anything below!!"
```
from importlib import import_module
import os
from pprint import pprint
findScore = import_module('findScore')
response = findScore.main(ans)
response['details'] = filename
with open(f'evaluation_{filename}.json', 'w') as outfile:
json.dump(response, outfile)
pprint(response)
```
| github_jupyter |
You've already seen and used functions such as `print` and `abs`. But Python has many more functions, and defining your own functions is a big part of python programming.
In this lesson, you will learn more about using and defining functions.
# Getting Help
You saw the `abs` function in the previous tutorial, but what if you've forgotten what it does?
The `help()` function is possibly the most important Python function you can learn. If you can remember how to use `help()`, you hold the key to understanding most other functions.
Here is an example:
```
help(round)
```
`help()` displays two things:
1. the header of that function `round(number, ndigits=None)`. In this case, this tells us that `round()` takes an argument we can describe as `number`. Additionally, we can optionally give a separate argument which could be described as `ndigits`.
2. A brief English description of what the function does.
**Common pitfall:** when you're looking up a function, remember to pass in the name of the function itself, and not the result of calling that function.
What happens if we invoke help on a *call* to the function `round()`? Unhide the output of the cell below to see.
```
help(round(-2.01))
```
Python evaluates an expression like this from the inside out. First it calculates the value of `round(-2.01)`, then it provides help on the output of that expression.
<small>(And it turns out to have a lot to say about integers! After we talk later about objects, methods, and attributes in Python, the help output above will make more sense.)</small>
`round` is a very simple function with a short docstring. `help` shines even more when dealing with more complex, configurable functions like `print`. Don't worry if the following output looks inscrutable... for now, just see if you can pick anything new out from this help.
```
help(print)
```
If you were looking for it, you might learn that print can take an argument called `sep`, and that this describes what we put between all the other arguments when we print them.
## Defining functions
Builtin functions are great, but we can only get so far with them before we need to start defining our own functions. Below is a simple example.
```
def least_difference(a, b, c):
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
```
This creates a function called `least_difference`, which takes three arguments, `a`, `b`, and `c`.
Functions start with a header introduced by the `def` keyword. The indented block of code following the `:` is run when the function is called.
`return` is another keyword uniquely associated with functions. When Python encounters a `return` statement, it exits the function immediately, and passes the value on the right hand side to the calling context.
Is it clear what `least_difference()` does from the source code? If we're not sure, we can always try it out on a few examples:
```
print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?
)
```
Or maybe the `help()` function can tell us something about it.
```
help(least_difference)
```
Python isn't smart enough to read my code and turn it into a nice English description. However, when I write a function, I can provide a description in what's called the **docstring**.
### Docstrings
```
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.
>>> least_difference(1, 5, -5)
4
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
```
The docstring is a triple-quoted string (which may span multiple lines) that comes immediately after the header of a function. When we call `help()` on a function, it shows the docstring.
```
help(least_difference)
```
> **Aside:**
> The last two lines of the docstring are an example function call and result. (The `>>>` is a reference to the command prompt used in Python interactive shells.) Python doesn't run the example call - it's just there for the benefit of the reader. The convention of including 1 or more example calls in a function's docstring is far from universally observed, but it can be very effective at helping someone understand your function. For a real-world example, see [this docstring for the numpy function `np.eye`](https://github.com/numpy/numpy/blob/v1.14.2/numpy/lib/twodim_base.py#L140-L194).
Good programmers use docstrings unless they expect to throw away the code soon after it's used (which is rare). So, you should start writing docstrings, too!
## Functions that don't return
What would happen if we didn't include the `return` keyword in our function?
```
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
min(diff1, diff2, diff3)
print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7),
)
```
Python allows us to define such functions. The result of calling them is the special value `None`. (This is similar to the concept of "null" in other languages.)
Without a `return` statement, `least_difference` is completely pointless, but a function with side effects may do something useful without returning anything. We've already seen two examples of this: `print()` and `help()` don't return anything. We only call them for their side effects (putting some text on the screen). Other examples of useful side effects include writing to a file, or modifying an input.
```
mystery = print()
print(mystery)
```
## Default arguments
When we called `help(print)`, we saw that the `print` function has several optional arguments. For example, we can specify a value for `sep` to put some special string in between our printed arguments:
```
print(1, 2, 3, sep=' < ')
```
But if we don't specify a value, `sep` is treated as having a default value of `' '` (a single space).
```
print(1, 2, 3)
```
Adding optional arguments with default values to the functions we define turns out to be pretty easy:
```
def greet(who="Colin"):
print("Hello,", who)
greet()
greet(who="Kaggle")
# (In this case, we don't need to specify the name of the argument, because it's unambiguous.)
greet("world")
```
## Functions Applied to Functions
Here's something that's powerful, though it can feel very abstract at first. You can supply functions as arguments to other functions. Some example may make this clearer:
```
def mult_by_five(x):
return 5 * x
def call(fn, arg):
"""Call fn on arg"""
return fn(arg)
def squared_call(fn, arg):
"""Call fn on the result of calling fn on arg"""
return fn(fn(arg))
print(
call(mult_by_five, 1),
squared_call(mult_by_five, 1),
sep='\n', # '\n' is the newline character - it starts a new line
)
```
Functions that operate on other functions are called "higher-order functions." You probably won't write your own for a little while. But there are higher-order functions built into Python that you might find useful to call.
Here's an interesting example using the `max` function.
By default, `max` returns the largest of its arguments. But if we pass in a function using the optional `key` argument, it returns the argument `x` that maximizes `key(x)` (aka the 'argmax').
```
def mod_5(x):
"""Return the remainder of x after dividing by 5"""
return x % 5
print(
'Which number is biggest?',
max(100, 51, 14),
'Which number is the biggest modulo 5?',
max(100, 51, 14, key=mod_5),
sep='\n',
)
```
| github_jupyter |
```
import re
import numpy as np
import pandas as pd
import collections
from sklearn import metrics
from sklearn.preprocessing import LabelEncoder
import tensorflow as tf
from sklearn.model_selection import train_test_split
from unidecode import unidecode
from nltk.util import ngrams
from tqdm import tqdm
import time
permulaan = [
'bel',
'se',
'ter',
'men',
'meng',
'mem',
'memper',
'di',
'pe',
'me',
'ke',
'ber',
'pen',
'per',
]
hujung = ['kan', 'kah', 'lah', 'tah', 'nya', 'an', 'wan', 'wati', 'ita']
def naive_stemmer(word):
assert isinstance(word, str), 'input must be a string'
hujung_result = re.findall(r'^(.*?)(%s)$' % ('|'.join(hujung)), word)
word = hujung_result[0][0] if len(hujung_result) else word
permulaan_result = re.findall(r'^(.*?)(%s)' % ('|'.join(permulaan[::-1])), word)
permulaan_result.extend(re.findall(r'^(.*?)(%s)' % ('|'.join(permulaan)), word))
mula = permulaan_result if len(permulaan_result) else ''
if len(mula):
mula = mula[1][1] if len(mula[1][1]) > len(mula[0][1]) else mula[0][1]
return word.replace(mula, '')
def build_dataset(words, n_words):
count = [['GO', 0], ['PAD', 1], ['EOS', 2], ['UNK', 3]]
counter = collections.Counter(words).most_common(n_words)
count.extend(counter)
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
index = dictionary.get(word, 3)
if index == 0:
unk_count += 1
data.append(index)
count[0][1] = unk_count
reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reversed_dictionary
def classification_textcleaning(string):
string = re.sub(
'http\S+|www.\S+',
'',
' '.join(
[i for i in string.split() if i.find('#') < 0 and i.find('@') < 0]
),
)
string = unidecode(string).replace('.', ' . ').replace(',', ' , ')
string = re.sub('[^A-Za-z ]+', ' ', string)
string = re.sub(r'[ ]+', ' ', string).strip()
string = ' '.join(
[i for i in re.findall('[\\w\']+|[;:\-\(\)&.,!?"]', string) if len(i)]
)
string = string.lower().split()
string = [(naive_stemmer(word), word) for word in string]
return (
' '.join([word[0] for word in string if len(word[0]) > 1]),
' '.join([word[1] for word in string if len(word[0]) > 1]),
)
def str_idx(corpus, dic, maxlen, UNK = 3):
X = np.zeros((len(corpus), maxlen))
for i in range(len(corpus)):
for no, k in enumerate(corpus[i].split()[:maxlen][::-1]):
X[i, -1 - no] = dic.get(k,UNK)
return X
with open('subjectivity-negative-translated.txt','r') as fopen:
texts = fopen.read().split('\n')
labels = [0] * len(texts)
with open('subjectivity-positive-translated.txt','r') as fopen:
positive_texts = fopen.read().split('\n')
labels += [1] * len(positive_texts)
texts += positive_texts
assert len(labels) == len(texts)
for i in range(len(texts)):
texts[i] = classification_textcleaning(texts[i])[0]
concat = ' '.join(texts).split()
vocabulary_size = len(list(set(concat)))
data, count, dictionary, rev_dictionary = build_dataset(concat, vocabulary_size)
print('vocab from size: %d'%(vocabulary_size))
print('Most common words', count[4:10])
print('Sample data', data[:10], [rev_dictionary[i] for i in data[:10]])
def attention(inputs, attention_size):
hidden_size = inputs.shape[2].value
w_omega = tf.Variable(
tf.random_normal([hidden_size, attention_size], stddev = 0.1)
)
b_omega = tf.Variable(tf.random_normal([attention_size], stddev = 0.1))
u_omega = tf.Variable(tf.random_normal([attention_size], stddev = 0.1))
with tf.name_scope('v'):
v = tf.tanh(tf.tensordot(inputs, w_omega, axes = 1) + b_omega)
vu = tf.tensordot(v, u_omega, axes = 1, name = 'vu')
alphas = tf.nn.softmax(vu, name = 'alphas')
output = tf.reduce_sum(inputs * tf.expand_dims(alphas, -1), 1)
return output, alphas
class Model:
def __init__(
self,
size_layer,
num_layers,
dimension_output,
learning_rate,
dropout,
dict_size,
):
def cells(size, reuse = False):
return tf.contrib.rnn.DropoutWrapper(
tf.nn.rnn_cell.LSTMCell(
size,
initializer = tf.orthogonal_initializer(),
reuse = reuse,
),
state_keep_prob = dropout,
output_keep_prob = dropout,
)
self.X = tf.placeholder(tf.int32, [None, None])
self.Y = tf.placeholder(tf.int32, [None])
encoder_embeddings = tf.Variable(
tf.random_uniform([dict_size, size_layer], -1, 1)
)
encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)
for n in range(num_layers):
(out_fw, out_bw), (
state_fw,
state_bw,
) = tf.nn.bidirectional_dynamic_rnn(
cell_fw = cells(size_layer),
cell_bw = cells(size_layer),
inputs = encoder_embedded,
dtype = tf.float32,
scope = 'bidirectional_rnn_%d' % (n),
)
encoder_embedded = tf.concat((out_fw, out_bw), 2)
self.outputs, self.attention = attention(encoder_embedded, size_layer)
W = tf.get_variable(
'w',
shape = (size_layer * 2, 2),
initializer = tf.orthogonal_initializer(),
)
b = tf.get_variable(
'b', shape = (2), initializer = tf.zeros_initializer()
)
self.logits = tf.add(tf.matmul(self.outputs, W), b, name = 'logits')
self.cost = tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(
logits = self.logits, labels = self.Y
)
)
self.optimizer = tf.train.AdamOptimizer(
learning_rate = learning_rate
).minimize(self.cost)
self.accuracy = tf.reduce_mean(
tf.cast(tf.nn.in_top_k(self.logits, self.Y, 1), tf.float32)
)
size_layer = 256
num_layers = 2
dropout = 0.8
dimension_output = 2
learning_rate = 1e-4
batch_size = 32
maxlen = 80
dropout = 0.8
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = Model(
size_layer,
num_layers,
dimension_output,
learning_rate,
dropout,
len(dictionary),
)
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver(tf.trainable_variables())
saver.save(sess, 'hierarchical/model.ckpt')
strings = ','.join(
[
n.name
for n in tf.get_default_graph().as_graph_def().node
if ('Variable' in n.op
or 'Placeholder' in n.name
or 'logits' in n.name
or 'alphas' in n.name)
and 'Adam' not in n.name
and 'beta' not in n.name
]
)
strings.split(',')
vectors = str_idx(texts, dictionary, maxlen)
train_X, test_X, train_Y, test_Y = train_test_split(
vectors, labels, test_size = 0.2
)
EARLY_STOPPING, CURRENT_CHECKPOINT, CURRENT_ACC, EPOCH = 3, 0, 0, 0
while True:
lasttime = time.time()
if CURRENT_CHECKPOINT == EARLY_STOPPING:
print('break epoch:%d\n' % (EPOCH))
break
train_acc, train_loss, test_acc, test_loss = 0, 0, 0, 0
pbar = tqdm(
range(0, len(train_X), batch_size), desc = 'train minibatch loop'
)
for i in pbar:
batch_x = train_X[i : min(i + batch_size, train_X.shape[0])]
batch_y = train_Y[i : min(i + batch_size, train_X.shape[0])]
batch_x_expand = np.expand_dims(batch_x,axis = 1)
acc, cost, _ = sess.run(
[model.accuracy, model.cost, model.optimizer],
feed_dict = {
model.Y: batch_y,
model.X: batch_x
},
)
assert not np.isnan(cost)
train_loss += cost
train_acc += acc
pbar.set_postfix(cost = cost, accuracy = acc)
pbar = tqdm(range(0, len(test_X), batch_size), desc = 'test minibatch loop')
for i in pbar:
batch_x = test_X[i : min(i + batch_size, test_X.shape[0])]
batch_y = test_Y[i : min(i + batch_size, test_X.shape[0])]
batch_x_expand = np.expand_dims(batch_x,axis = 1)
acc, cost = sess.run(
[model.accuracy, model.cost],
feed_dict = {
model.Y: batch_y,
model.X: batch_x
},
)
test_loss += cost
test_acc += acc
pbar.set_postfix(cost = cost, accuracy = acc)
train_loss /= len(train_X) / batch_size
train_acc /= len(train_X) / batch_size
test_loss /= len(test_X) / batch_size
test_acc /= len(test_X) / batch_size
if test_acc > CURRENT_ACC:
print(
'epoch: %d, pass acc: %f, current acc: %f'
% (EPOCH, CURRENT_ACC, test_acc)
)
CURRENT_ACC = test_acc
CURRENT_CHECKPOINT = 0
else:
CURRENT_CHECKPOINT += 1
print('time taken:', time.time() - lasttime)
print(
'epoch: %d, training loss: %f, training acc: %f, valid loss: %f, valid acc: %f\n'
% (EPOCH, train_loss, train_acc, test_loss, test_acc)
)
EPOCH += 1
real_Y, predict_Y = [], []
pbar = tqdm(
range(0, len(test_X), batch_size), desc = 'validation minibatch loop'
)
for i in pbar:
batch_x = test_X[i : min(i + batch_size, test_X.shape[0])]
batch_y = test_Y[i : min(i + batch_size, test_X.shape[0])]
predict_Y += np.argmax(
sess.run(
model.logits, feed_dict = {model.X: batch_x, model.Y: batch_y}
),
1,
).tolist()
real_Y += batch_y
print(
metrics.classification_report(
real_Y, predict_Y, target_names = ['negative', 'positive']
)
)
text = classification_textcleaning('kerajaan sebenarnya sangat sayangkan rakyatnya, tetapi sebenarnya benci')
new_vector = str_idx([text[0]], dictionary, len(text[0].split()))
sess.run(tf.nn.softmax(model.logits), feed_dict={model.X:new_vector})
import json
with open('hierarchical-subjective.json','w') as fopen:
fopen.write(json.dumps({'dictionary':dictionary,'reverse_dictionary':rev_dictionary}))
saver.save(sess, 'hierarchical/model.ckpt')
def freeze_graph(model_dir, output_node_names):
if not tf.gfile.Exists(model_dir):
raise AssertionError(
"Export directory doesn't exists. Please specify an export "
'directory: %s' % model_dir
)
checkpoint = tf.train.get_checkpoint_state(model_dir)
input_checkpoint = checkpoint.model_checkpoint_path
absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])
output_graph = absolute_model_dir + '/frozen_model.pb'
clear_devices = True
with tf.Session(graph = tf.Graph()) as sess:
saver = tf.train.import_meta_graph(
input_checkpoint + '.meta', clear_devices = clear_devices
)
saver.restore(sess, input_checkpoint)
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess,
tf.get_default_graph().as_graph_def(),
output_node_names.split(','),
)
with tf.gfile.GFile(output_graph, 'wb') as f:
f.write(output_graph_def.SerializeToString())
print('%d ops in the final graph.' % len(output_graph_def.node))
freeze_graph('hierarchical', strings)
def load_graph(frozen_graph_filename):
with tf.gfile.GFile(frozen_graph_filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def)
return graph
g = load_graph('hierarchical/frozen_model.pb')
x = g.get_tensor_by_name('import/Placeholder:0')
logits = g.get_tensor_by_name('import/logits:0')
alphas = g.get_tensor_by_name('import/alphas:0')
test_sess = tf.InteractiveSession(graph = g)
result = test_sess.run([logits, alphas], feed_dict = {x: new_vector})
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
news_string = 'kerajaan sebenarnya sangat bencikan rakyatnya, minyak naik dan segalanya'
text = classification_textcleaning(news_string)
new_vector = str_idx([text[0]], dictionary, len(text[0].split()))
result = test_sess.run([tf.nn.softmax(logits), alphas], feed_dict = {x: new_vector})
plt.figure(figsize = (15, 7))
labels = [word for word in text[1].split()]
val = [val for val in result[1][0]]
plt.bar(np.arange(len(labels)), val)
plt.xticks(np.arange(len(labels)), labels, rotation = 'vertical')
plt.title('negative %f positive %f' % (result[0][0,0], result[0][0,1]))
plt.show()
```
| github_jupyter |
# Chapter 13 While and for Loops
#### Two main looping constructs:
while-----'while' provides a way to code general loops
for------'for' is designed for stepping through the items in a sequence object
'while' and 'for' are the primary syntax for coding repeated actions
#### some statements used within loops:
break
continue
#### some loop generator:
range
zip
map
'range', 'zip' and 'map' are additional looping operations
#### Chapter 14 will talk about Python's iteration protocol and list comprehensions
I don't know what the iteration protocol is
#### Later chapters will explore some generators like filter and reduce.
```
# While loops
# while True:
# print("") # Press 'Ctrl-C to stop this iteration'
i = 123456789
while i%2 == 0:
print("lbwnb")
i
i%2 == 0
# Print the even numbers from 0 to 100:
i = 0
while i <=1000:
if i%2==0:
print(i,end=' ')
i += 1
print('\n')
for i in range(0,1001):
if i%2 ==0:
print(i, end = ' ')
i =0
while i <=100: # A header line with a test expression
if i%2==0: # body, indented statements
print('%d is the even number'%i,end =', ')
i += 1
i = 0
while i <=100:
print(i, end =' ')
i += 1
else: # Optional. Function: else will run statements below it, if and only if the text expression doesn't stand alone
print('i is %d, bigger than 100. Thus, the loop will end here!'%i)
# Examples
1 == True # True is just a custom version of the integer 1 and always stands for a Boolean true value
1 is True
type(1), type (True) # '1' and 'True' are different things.
# infinite loop
# While True:
# print('Type Ctrl-C to stop me')
bool('')
type('')
len('')
x = 'spam'
while x:
print(x,sep=',')
x = x[1:]
x = 'xswl'
print(x[0] +'=>x[0]',x[1] +'=>x[1]',x[2] +'=>x[2]',x[len(x)-1] +'=>x[3]',sep=' ')
x = x[1:]
print(x,x[0] +'=>x[0]',x[1] +'=>x[1]',x[2] +'=>x[2]',x[len(x)-1] +'=>x[2]',sep=' ')
a = 0; b = 10
while a < b:
print(a, end = ' ')
a += 1
```
### Break, continue, pass, and the Loop else
#### break: jumps out of the closet enclosing loop (past the entire loop statement)
#### continue: jumps to the top of the closet enclosing loop (to the loop's header line)
#### pass: do nothing at all; placeholder
#### else: optional; be executed if and only if control exits the loop without hitting the break
```
## General Loop Format
i = 1
while i <=100: # i = 1, pass # i = 2, pass
print(i) # do this statement # execute this statement
if i%2 == 0: # false # True when i = 2
break # Jumps out of the closet enclosing loop; Since it is false when i = 1, this operation will be executed
# The loop will end here when i = 2
if i%3 == 0: # false
continue # Won't be executed when i = 1
i += 1 # i = i + 1, i =2
else:
print("i is %d and the loop will end here!"%i)
print(1%3==0, 2%3==0, 3%3==0)
```
# Pass
```
s = """Simple things first: the pass statement is a no-operation placeholder that is used when
the syntax requires a statement, but you have nothing useful to say. It is often used to
code an empty body for a compound statement. For instance, if you want to code an
infinite loop that does nothing each time through, do it with a pass"""
print(s)
for i in s:
print(i, end = ' ')
I = iter(s)
I.__next__()
I.__next__()
from sympy import *
init_session()
solveset(11*x**2-56*x + 42,x)
while (28/11-sqrt(322)/11) <= 0:
pass
else:
print('(28/11-sqrt(322)/11) is bigger than 0!')
## One of functions 'pass' has is 'to be filled in later'
def To_be_filled_in():
pass
def To_be_filled_in_later():
pass
To_be_filled_in() # Won't give an error
def To_be_filled_in_later():
... # ... is ellipses; Three consecutive dots
To_be_filled_in_later() # won't give an error when this function is called
x = ...
x
```
### x = pass: Wrong, invalid syntax
# Continue
```
x = 1234
while x:
x -=1
if x % 2 !=0: continue # if x%2 !=0 (that is, x is an odd number), skip print
print(x, end = ' ')
x = 10
while x:
x -= 1
if x%2 == 0:
print(x, end=' ')
# Break
while True:
name = input('Enter name:')
if name == 'stop': break
age = input('Enter age: ')
print("Hello", name, '=>', int(age))
while True:
name = input('请输入名字:')
if name == 'Ned Stark':
break
print('Ned Stark is dead after Season 3') # Useless
age = input("请输入年龄:")
print('哈喽,', name, '=>', age)
```
# Loop else
```
import random
def numerate(k):
return random.randint(1,k)
y = numerate(100)
x = y //2
while x > 1:
if y % x == 0:
print(y, 'has factor', x)
# break
x -= 1
else:
print(y, 'is prime')
bool(y%21166==0)
int(42332/21166)
# More on the loop else
# The codes here are just notion
found = False
while x and not found:
if match(x[0]):
print('Ni')
found = True
else:
x = x[1:]
if not found:
print('not found')
x = """Because the loop else clause is unique to Python, it tends to perplex some newcomers.
In general terms, the loop else provides explicit syntax for a common coding scenario—
it is a coding structure that lets us catch the “other” way out of a loop, without setting
and checking flags or conditions."""
L = []
for i in x:
L.append(i)
print(L)
x = L
def match(x):
if x == 't':
return True
else:
return False
# Equivalent code:
while x:
if match(x[0]):
print('Ni')
break
x = x[1:]
else:
print('Not found')
S1 = 'abcdefghijklmnopqrstuvwxyz'
L2 = []
for j in S1:
L2.append(j)
print(L2)
for i in L2:
if i in x:
print(i in x, end = ', ')
else:
print('%s is not in x'%i, end =', ')
def match(x):
if x == 'b':
return True
else:
return False
while x:
if match(x[0]):
print('Ni')
break
x = x[1:]
else:
print('Not found')
def match(x):
if x == 'j':
return True
else:
return False
while x:
if match(x[0]):
print('Ni')
break
x = x[1:]
else:
print('Not found')
def match(x):
if x == 'z':
return True
else:
return False
while x:
if match(x[0]):
print('Ni')
break
x = x[1:]
else:
print('Not found')
next?
print(L)
''.join(L)
iterator1 = iter(L)
next(iterator1)
```
# For loops
```
S = 'The for loop is a generic sequence iterator in Python: it can step through the items in any ordered sequence object. '
S1 = "The for loop is a generic sequence iterator in Python: it can step through the items in any ordered sequence object. "
S2 = """The for loop is a generic sequence iterator in Python: it can step through the items in any ordered sequence object. """
S4 = "The for loop is 'a generic sequence'"
L = [] # empty list
for i in S:
L.append(i)
print(L)
L2 = []
for i in L:
L2.append(L)
''.join(L)
T = ('1','2','3')
type(T)
print(tuple(L))
S
print(list(S))
str(L)
print(tuple(S))
T = tuple(S)
print(list(T))
```
strings => lists => tuples;
lists !=> strings => tuples;
tuples => strings;
```
str(T)
# The other built-in iterables: file
for i in [0,1,2,3,4,5,6,7,8,9,10]:
# i = i + 1
if i >= 6: break
print(i,end=' ')
else:
print("Raise an error!")
i == 6
from sympy import *
init_session()
a, b, c = symbols('a b c')
solveset(a*x**2+ b*x + c, x)
```
# Examples
```
for x in ["spam","eggs","ham"]:
print(x, end = ' ')
L = [1,2,3,4]
sum(L)
sum = 0
for x in [1,2,3,4]:
sum = sum + x
sum
init_session()
del sum
sum(L)
symbols = 0
for i in range(10):
symbols +=i
print(symbols)
type(symbols)
from sympy import *
x, y, z, t = symbols('x y z t')
x, y, z, t
summation = 0
for i in range(101):
summation += i
print(summation)
prod = 1
for item in [1,2,3,4]:
prod *= item
prod
from sympy import *
i = symbols('i')
product(i,(i,1,4))
type((1,2))
type([1,2,3,4,5,6])
```
A list of tuples
```
T = [(1,2),(3,4),(5,6)]
for (a,b) in T:
print(a,b)
zip?
Tu = zip([1,2],[3,4],[5,6])
for i in Tu:
print(i)
map?
D = {'a': 1, 'b': 2, 'c': 3}
for key in D:
print(key, '=>', D[key])
D
list(D)
list(D.items())
D.items()
D['a'] = '1','2'
D['b'] = '3','4'
D['c'] = '5', '6'
for (key,value) in D.items():
print(key, '=>', value)
from turtle import *
# 设置色彩模式是RGB:
colormode(255)
lt(90)
lv = 14
l = 120
s = 45
width(lv)
# 初始化RGB颜色:
r = 0
g = 0
b = 0
pencolor(r, g, b)
penup()
bk(l)
pendown()
fd(l)
def draw_tree(l, level):
global r, g, b
# save the current pen width
w = width()
# narrow the pen width
width(w * 3.0 / 4.0)
# set color:
r = r + 1
g = g + 2
b = b + 3
pencolor(r % 200, g % 200, b % 200)
l = 3.0 / 4.0 * l
lt(s)
fd(l)
if level < lv:
draw_tree(l, level + 1)
bk(l)
rt(2 * s)
fd(l)
if level < lv:
draw_tree(l, level + 1)
bk(l)
lt(s)
# restore the previous pen width
width(w)
speed("fastest")
draw_tree(l, 4)
done()
#KocheDraw1
import turtle
def koch(size,n):
if n==1:
turtle.fd(size)
else:
for i in [0,60,-120,60]:
turtle.left(i)
koch(size/3,n-1)
def main():
turtle.setup(600,600)
turtle.penup()
turtle.speed(10)
turtle.hideturtle()
turtle.pensize(2)
turtle.goto(-200,100)
turtle.pendown()
level=4
koch(400,level)
turtle.right(120)
koch(400, level)
turtle.right(120)
koch(400, level)
turtle.penup()
turtle.done()
main()
import turtle as t
t.speed(10)
t.pensize(8)
t.hideturtle()
t.screensize(500, 500, bg='white')
# 猫脸
t.fillcolor('#00A1E8')
t.begin_fill()
t.circle(120)
t.end_fill()
t.pensize(3)
t.fillcolor('white')
t.begin_fill()
t.circle(100)
t.end_fill()
t.pu()
t.home()
t.goto(0, 134)
t.pd()
t.pensize(4)
t.fillcolor("#EA0014")
t.begin_fill()
t.circle(18)
t.end_fill()
t.pu()
t.goto(7, 155)
t.pensize(2)
t.color('white', 'white')
t.pd()
t.begin_fill()
t.circle(4)
t.end_fill()
t.pu()
t.goto(-30, 160)
t.pensize(4)
t.pd()
t.color('black', 'white')
t.begin_fill()
a = 0.4
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a = a+0.08
t.lt(3) #向左转3度
t.fd(a) #向前走a的步长
else:
a = a-0.08
t.lt(3)
t.fd(a)
t.end_fill()
t.pu()
t.goto(30, 160)
t.pensize(4)
t.pd()
t.color('black', 'white')
t.begin_fill()
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a = a+0.08
t.lt(3) # 向左转3度
t.fd(a) # 向前走a的步长
else:
a = a-0.08
t.lt(3)
t.fd(a)
t.end_fill()
t.pu()
t.goto(-38,190)
t.pensize(8)
t.pd()
t.right(-30)
t.forward(15)
t.right(70)
t.forward(15)
t.pu()
t.goto(15, 185)
t.pensize(4)
t.pd()
t.color('black', 'black')
t.begin_fill()
t.circle(13)
t.end_fill()
t.pu()
t.goto(13, 190)
t.pensize(2)
t.pd()
t.color('white', 'white')
t.begin_fill()
t.circle(5)
t.end_fill()
t.pu()
t.home()
t.goto(0, 134)
t.pensize(4)
t.pencolor('black')
t.pd()
t.right(90)
t.forward(40)
t.pu()
t.home()
t.goto(0, 124)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(10)
t.forward(80)
t.pu()
t.home()
t.goto(0, 114)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(6)
t.forward(80)
t.pu()
t.home()
t.goto(0,104)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(0)
t.forward(80)
# 左边的胡子
t.pu()
t.home()
t.goto(0,124)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(170)
t.forward(80)
t.pu()
t.home()
t.goto(0, 114)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(174)
t.forward(80)
t.pu()
t.home()
t.goto(0, 104)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(180)
t.forward(80)
t.pu()
t.goto(-70, 70)
t.pd()
t.color('black', 'red')
t.pensize(6)
t.seth(-60)
t.begin_fill()
t.circle(80,40)
t.circle(80,80)
t.end_fill()
t.pu()
t.home()
t.goto(-80,70)
t.pd()
t.forward(160)
t.pu()
t.home()
t.goto(-50,50)
t.pd()
t.pensize(1)
t.fillcolor("#eb6e1a")
t.seth(40)
t.begin_fill()
t.circle(-40, 40)
t.circle(-40, 40)
t.seth(40)
t.circle(-40, 40)
t.circle(-40, 40)
t.seth(220)
t.circle(-80, 40)
t.circle(-80, 40)
t.end_fill()
# 领带
t.pu()
t.goto(-70, 12)
t.pensize(14)
t.pencolor('red')
t.pd()
t.seth(-20)
t.circle(200, 30)
t.circle(200, 10)
# 铃铛
t.pu()
t.goto(0, -46)
t.pd()
t.pensize(3)
t.color("black", '#f8d102')
t.begin_fill()
t.circle(25)
t.end_fill()
t.pu()
t.goto(-5, -40)
t.pd()
t.pensize(2)
t.color("black", '#79675d')
t.begin_fill()
t.circle(5)
t.end_fill()
t.pensize(3)
t.right(115)
t.forward(7)
t.mainloop()
# coding: utf-8
import turtle as t
t.pensize(4)
t.hideturtle()
t.colormode(255)
t.setup(840,500)
t.speed(5)
# Nose
t.color((255,155,192),"pink")
t.pencolor(255,155,192)
t.pu()
t.goto(-100,100)
t.pd()
t.seth(-30)
t.begin_fill()
a=0.4
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a = a + 0.08
t.lt(3) # 向左转3度
t.fd(a) # 向前走a的步长
else:
a = a -0.08
t.lt(3)
t.fd(a)
t.end_fill()
t.pu()
t.seth(90)
t.fd(25)
t.seth(10)
t.fd(10)
t.pd()
t.pencolor(255,155,192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160,82,45)
t.end_fill()
t.pu()
t.seth(0)
t.fd(20)
t.pd()
t.pencolor(255,155,192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160,82,45)
t.end_fill()
# 头
t.color((255,155,192),"pink")
t.pu()
t.seth(90)
t.fd(41)
t.seth(0)
t.fd(0)
t.pd()
t.begin_fill()
t.seth(180)
t.circle(300,-30)
t.circle(100,-60)
t.circle(80,-100)
t.circle(150,-20)
t.circle(60,-95)
t.seth(161)
t.circle(-300,15)
t.pu()
t.goto(-100,100)
t.pd()
t.seth(-30)
a = 0.4
for i in range(60):
if 0 <= i < 30 or 60 <= i <90:
a = a + 0.08
t.lt(3) # 向左转3度
t.fd(a) # 向前走a的步长
else:
a = a - 0.08
t.lt(3)
t.fd(a)
t.end_fill()
# 耳朵
t.color((255,155,192),"pink")
t.pu()
t.seth(90)
t.fd(-7)
t.seth(0)
t.fd(70)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50,50)
t.circle(-10,120)
t.circle(-50,54)
t.end_fill()
t.pu()
t.seth(90)
t.fd(-12)
t.seth(0)
t.fd(30)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50,50)
t.circle(-10,120)
t.circle(-50,56)
t.end_fill()
# 眼睛
t.color((255,155,192),"white")
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-95)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
t.color((255,155,192),"white")
t.pu()
t.seth(90)
t.fd(-25)
t.seth(0)
t.fd(40)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
# 腮
t.color((255,155,192))
t.pu()
t.seth(90)
t.fd(-95)
t.seth(0)
t.fd(65)
t.pd()
t.begin_fill()
t.circle(30)
t.end_fill()
# 嘴
t.color(239,69,19)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(-100)
t.pd()
t.seth(-80)
t.circle(30,40)
t.circle(40,80)
#身体
t.color("red",(255,99,71))
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-78)
t.pd()
t.begin_fill()
t.seth(-130)
t.circle(100,10)
t.circle(300,30)
t.seth(0)
t.fd(230)
t.seth(90)
t.circle(300,30)
t.circle(100,3)
t.color((255,155,192),(255,100,100))
t.seth(-135)
t.circle(-80,63)
t.circle(-150,24)
t.end_fill()
# 手
t.color((255,155,192))
t.pu()
t.seth(90)
t.fd(-40)
t.seth(0)
t.fd(-27)
t.pd()
t.seth(-160)
t.circle(300,15)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-10)
t.circle(-20,90)
t.pu()
t.seth(90)
t.fd(30)
t.seth(0)
t.fd(237)
t.pd()
t.seth(-20)
t.circle(-300,15)
t.pu()
t.seth(90)
t.fd(20)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-170)
t.circle(20,90)
# 脚
t.pensize(10)
t.color((240,128,128))
t.pu()
t.seth(90)
t.fd(-75)
t.seth(0)
t.fd(-180)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)
t.pensize(10)
t.color((240,128,128))
t.pu()
t.seth(90)
t.fd(40)
t.seth(0)
t.fd(90)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)
# 尾巴
t.pensize(4)
t.color((255,155,192))
t.pu()
t.seth(90)
t.fd(70)
t.seth(0)
t.fd(95)
t.pd()
t.seth(0)
t.circle(70,20)
t.circle(10,330)
t.circle(70,30)
t.done()
from sympy import *
init_session()
from sympy import tan
A = symbols('A')
a = solve((1 + tan(A))/(1-tan(A))-2005,A)
from sympy import sec
from sympy import substitution
type(a)
a[0]
float(sec(2*a[0]) + tan(2*a[0]))
```
求证:〖sin〗^3 a/3+3*〖sin〗^3 a/3^2 +⋯+3^(n-1)*〖sin〗^3 a/3^n =1/4(3^n*sin a/3^n -sina)
```
from sympy import *
init_session()
a = symbols('a')
from sympy import sin
# 当 n = 1
simplify(Sum(3**(n-1)*(sin(a/(3**n)))**3,(n,1,2)).doit()-1/4*(3**2*sin(a/(3**2))-sin(a)))
# 当 n = 2
simplify(Sum(3**(n-1)*(sin(a/(3**n)))**3,(n,1,2)).doit()-1/4*(3**2*sin(a/(3**2))-sin(a)))
# 当 n = 5
simplify(Sum(3**(n-1)*(sin(a/(3**n)))**3,(n,1,5)).doit()-1/4*(3**5*sin(a/(3**5))-sin(a)))
Sum(3**(n-1)*(sin(a/(3**n)))**3,(n,1,n))
left = Sum(3**(n-1)*(sin(a/(3**n)))**3,(n,1,n))
1/4*(3**n*sin(a/(3**n))-sin(a))
right = 1/4*(3**n*sin(a/(3**n))-sin(a))
from sympy import substitution
from sympy import *
init_session()
i = symbols('i', integer = True)
type(i)
Sum(i,(i,1,100)).doit()
a = symbols('a')
Sum(3**(n-1)*(sin(a/(3**n))**3),(n,1,k))
left = Sum(3**(n-1)*(sin(a/(3**n))**3),(n,1,k))
factor(1/4*(3**n*sin(a/(3**n))-sin(a)))
right = factor(1/4*(3**n*sin(a/(3**n))-sin(a)))
simplify(left - right)
# n = 1
simplify(left.subs(k,1).doit()-right.subs(n,1))
# n = 5
simplify(left.subs(k,5).doit()-right.subs(n,5))
right.subs(n,5)
left.subs(k,5).doit()
# n = 19
simplify(left.subs(k,19).doit()-right.subs(n,19))
a, b = symbols('a b', real=True)
a.is_real and b.is_real
left = sin(2*a+b)/sin(a)-2*cos(a+b)
right = sin(b)/sin(a)
simplify(left - right).doit()
# %load untitled0.py
"""
Created on Sat Feb 15 22:35:00 2020
@author: NickC
"""
from PIL import Image
from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
import numpy as np
import jieba
def GetWordCloud():
path_txt = 'C://Users/NickC/all.txt'
path_img = 'C://Users/NickC/2.jpg'
f = open(path_txt, 'r', encoding='UTF-8').read()
background_image = np.array(Image.open(path_img))
# 结巴分词,生成字符串,如果不通过分词,无法直接生成正确的中文词云,感兴趣的朋友可以去查一下,有多种分词模式
#Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
cut_text = " ".join(jieba.cut(f))
wordcloud = WordCloud(
# 设置字体,不然会出现口字乱码,文字的路径是电脑的字体一般路径,可以换成别的
font_path="C:/Windows/Fonts/simfang.ttf",
background_color="white",
# mask参数=图片背景,必须要写上,另外有mask参数再设定宽高是无效的
mask=background_image).generate(cut_text)
# 生成颜色值
image_colors = ImageColorGenerator(background_image)
# 下面代码表示显示图片
plt.imshow(wordcloud.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis("off")
plt.show()
if __name__ == '__main__':
GetWordCloud()
# coding=utf-8
import turtle
from datetime import *
# 抬起画笔,向前运动一段距离放下
def Skip(step):
turtle.penup()
turtle.forward(step)
turtle.pendown()
def mkHand(name, length):
# 注册Turtle形状,建立表针Turtle
turtle.reset()
Skip(-length * 0.1)
# 开始记录多边形的顶点。当前的乌龟位置是多边形的第一个顶点。
turtle.begin_poly()
turtle.forward(length * 1.1)
# 停止记录多边形的顶点。当前的乌龟位置是多边形的最后一个顶点。将与第一个顶点相连。
turtle.end_poly()
# 返回最后记录的多边形。
handForm = turtle.get_poly()
turtle.register_shape(name, handForm)
def Init():
global secHand, minHand, hurHand, printer
# 重置Turtle指向北
turtle.mode("logo")
# 建立三个表针Turtle并初始化
mkHand("secHand", 135)
mkHand("minHand", 90)
mkHand("hurHand", 45)
secHand = turtle.Turtle()
secHand.shape("secHand")
secHand.color('red')
minHand = turtle.Turtle()
minHand.color('purple')
minHand.shape("minHand")
hurHand = turtle.Turtle()
hurHand.color('yellow')
hurHand.shape("hurHand")
for hand in secHand, minHand, hurHand:
hand.shapesize(1, 1, 3)
hand.speed(0)
# 建立输出文字Turtle
printer = turtle.Turtle()
printer.color('green')
# 隐藏画笔的turtle形状
printer.hideturtle()
printer.penup()
def SetupClock(radius):
# 建立表的外框
turtle.reset()
turtle.bgpic(r'yang.gif')
turtle.color('green')
turtle.pensize(7)
for i in range(60):
Skip(radius)
if i % 5 == 0:
turtle.color('blue')
turtle.forward(20)
Skip(-radius - 20)
Skip(radius + 20)
if i == 0:
turtle.write(int(12), align="center", font=("Courier", 14, "bold"))
elif i == 30:
Skip(25)
turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))
Skip(-25)
elif (i == 25 or i == 35):
Skip(20)
turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))
Skip(-20)
else:
turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))
Skip(-radius - 20)
else:
turtle.dot(5)
Skip(-radius)
turtle.right(6)
def Week(t):
week = ["星期一", "星期二", "星期三",
"星期四", "星期五", "星期六", "星期日"]
return week[t.weekday()]
def Date(t):
y = t.year
m = t.month
d = t.day
return "%s/%d/%d" % (y, m, d)
def Tick():
# 绘制表针的动态显示
t = datetime.today()
second = t.second + t.microsecond * 0.000001
minute = t.minute + second / 60.0
hour = t.hour + minute / 60.0
secHand.setheading(6 * second)
minHand.setheading(6 * minute)
hurHand.setheading(30 * hour)
turtle.tracer(False)
printer.forward(65)
printer.write(Week(t), align="center",
font=("Courier", 14, "bold"))
turtle.color('purple')
printer.back(130)
printer.write(Date(t), align="center",
font=("Courier", 14, "bold"))
printer.back(30)
# printer.write('大古需要光', align='center',font=("Courier",14,"bold"))
printer.home()
turtle.tracer(True)
# 100ms后继续调用tick
turtle.ontimer(Tick, 100)
def main():
# 打开/关闭龟动画,并为更新图纸设置延迟。
turtle.tracer(False)
Init()
SetupClock(160)
turtle.tracer(True)
Tick()
turtle.mainloop()
if __name__ == "__main__":
main()
file = open('woshicik.txt',encoding='utf-8')
file.read?
while True:
char = file.read(1) # Read 1 character by 1 character
if not char: break
print(char, end='')
for char in open('woshicik.txt', encoding = 'utf-8').readline():
print(char, end='')
for i in iter(open('woshicik.txt', encoding = 'utf-8').readline()):
print(i, end= '')
```
# Loop Coding Techniques
```
print(range(5)); print(list(range(5)))
print(range(2,5)); print(list(range(2,5)))
print(range(0,10,2)); print(list(range(0,10,2)))
```
```
print(list(range(-5,5)))
print(list(range(5,-5,-1)))
```
```
for i in range(10):
print(i, file.readline(), end='')
X = 'spam'
for item in X: print(item,end=' ')
i = 0
while i < len(X):
print(X[i],end=' ')
i+=1
```
```
X
len(X)
list(range(len(X)))
for i in range(len(X)): print(X[i], end=' ')
```
# Nonexhaustive Traversals: range and Slices
```
for item in X: print(item,end=' ')
S = """However, the coding pattern used in the prior example does allow us to do more specialized sorts of traversals. For instance, we can skip items as we go:"""
print(S.split(), end = ' ')
for i in range(0, len(S.split()), 1): print(S.split()[i], end =' ')
for c in S.split()[::1]: print(c, end = ' ')
```
# Changing lists: range. The combination of range wiht for loops
```
L = S.split()
for x in L:
x += 'xswl'
print(L, end= '' )
x
```
```
for i in range(len(L)):
L[i] += 'xswl'
print(L, end = '')
S = """印度这次修订可谓大刀阔斧、魄力惊人:制造业月度指数强行绑定于同类商品,比如印度生产了一辆印度国产车,强行与市场上的奥迪车等价。"""
from jieba import *
L = list(cut(S))
for i in range(len(L)):
L[i] += ', xswl'
i = 0
L = list(cut(S))
while i < len(L):
L[i] += ', nb'
i += 1
S = """印度这次修订可谓大刀阔斧、魄力惊人:制造业月度指数强行绑定于同类商品,比如印度生产了一辆印度国产车,强行与市场上的奥迪车等价。"""
```
# Parallel Traversals: zip and map
```
S = """The last example in the prior section works, but it’s not the fastest option. It’s also
more work than we need to do. """
L = S.split()
for i in L:
print(i, end =' ')
for i in range(0, len(L), 4):
print(L[i], end = ' ')
L1 = list(range(1,5,1))
L2 = list(range(5,9,1))
L1, L2
z = list(zip(L1,L2))
for x, y in zip(L1, L2): print(x, y, '--', x+y)
(x, y) == (4,8)
file = open('woshicik.txt',encoding='utf-8')
len(list(enumerate(file.read())))
print(list(zip(list(range(1,4116,1)), file)), end =' ')
L3 = list(range(9,13,1))
print(L1)
print(L2)
print(L3)
list(zip(L1,L2,L3))
S1 = 'abc'
S2 = 'xyz123'
zip(S1, S2)
list(_)
list(map(ord, S1))
res = []
for c in 'spam': res.append(ord(c))
res
```
# Dictionary construction with zip
```
D1 = {'spam':1 , 'eggs': 3, 'toast': 5}
D1
```
```
D1 = {}
D1['spam'] = 1
D1['eggs'] = 3
D1['toast'] = 5
S = """The built-in name dict is really a type name in Python (you’ll learn more about type
names, and subclassing them, in Chapter 31). Calling it achieves something like a listto-dictionary conversion, but it’s really an object construction request. In the next
chapter we’ll explore a related but richer concept, the list comprehension, which builds
lists in a single expression; we’ll also revisit 3.0 dictionary comprehensions an alternative
to the dict cal for zipped key/value pairs."""
L = S.split()
keys = S.split()
vals = list(range(1, len(keys)+1, 1))
D2 = {}
for k, v in zip(keys, vals): D2[k] = v
D3 = dict(zip(keys, vals))
D3 == D2
[i**2 for i in range(10)] # List comprehension
{v: k for v, k in zip(keys, vals)} # dictionary comprehension
```
# Generating Both offsets and items: enumerate
```
file = open('woshicik.txt',encoding='utf-8')
S = 'spam'
offset = 0
for item in S:
print(item, 'appears at offset', offset)
offset +=1
S = 'spam'
for offset, item in enumerate(S):
print(item, 'appears at offset', offset)
type(enumerate(S))
E = enumerate(file)
next(E)
next(enumerate(file)) #为什么
```
| github_jupyter |
# Plotting a Time Series of HMDA Filers by Category
### Scope of Notebook
This notebook will build on the [previous analysis example](https://github.com/cfpb/HMDA_Data_Science_Kit/blob/master/analysis_examples/1.%20Plotting%20a%20Time%20Series%20of%20HMDA%20Filers%20from%202004-2017.ipynb) of counting the number of institutions that have filed HMDA data from 2004-2017, by demonstrating how to filter counts by a particular category. The code below will focus on counts taken from the Transmittal Sheet dataset inside the HMDA collections.
The example will show how to pull Transmittal Sheet data from a local Postgres database, filter by a particular category, write the data to a pipe-delimited text file, and produce a graph in the Jupyter notebook as well as save the graph to a .png file.
Additionally, more advanced methods using functions will be shown as an introduction to a library of functions that can be used to interact with the HMDA data.
While these examples provide some commentary on the use of SQL and Python, they should not be considered a replacement for more full fledged tutorials on how to use these tools.
### Setup Requirements
In order to run this example locally several software packages need to be installed and configured.
Please see [these instructions](https://github.com/Kibrael/HMDA_Data_Science_Kit#creating-postgres-tables-and-loading-data) to get a local Postgres database set up and populated with HMDA data.
Please see [these instructions](https://github.com/Kibrael/HMDA_Data_Science_Kit#requirements) for setting up a Python development environment. Python 3.5 or higher is required as well as several libraries.
### Python Libraries Used
- [Pandas](https://pandas.pydata.org/pandas-docs/stable/): a data manipulation and analysis package.
- [Psycopg2](http://initd.org/psycopg/docs/): a database driver library providing APIs for connecting Python to Postgres.
- [Matplotlib](https://matplotlib.org/): a library to enable inline plotting with Pandas and Jupyter notebooks.
- [Jupyter](http://jupyter.org/documentation): a development tool that supports multiple formats for display such as Markdown and Python. Allows segmentation of code into cells for easy data manipulation trials.
### Approach
This notebook will leverage Postgres SQL as a data store and aggregation tool. Python will be used to interact with the database through the Psycopg2 library. The Pandas library will be used for data handling after pulling from Postgres. This includes cleaning, analysis, and visualization with the Matplotlib library (which integrates with Pandas).
The procss for this analysis will be:
- Establish a connection to the database using psycopg2
- Call a SQL file through Python to pull Transmittal Sheet counts by year
- Filter by a particular category
- Load the data into a Pandas dataframe
- Graph the data in the Jupyter notebook and save the graph to a .PNG file
## Import Python Libraries
```
import psycopg2 #Imports the Psycopg2 library
import pandas as pd #Imports the Pandas library and renames it "pd"
import matplotlib.pyplot as plt #imports the Matplot library and renames it "plt"
```
### Connect to the Database
The connection to the database, which was demonstrated in the [previous example](https://github.com/cfpb/HMDA_Data_Science_Kit/blob/master/analysis_examples/1.%20Plotting%20a%20Time%20Series%20of%20HMDA%20Filers%20from%202004-2017.ipynb), will use a locally hosted database and the hmda database created during initial setup. Please see Analysis Example 1 for further details on connecting using a locally hosted database.
```
#Establish connection parameters
#If you have established a username and password, change user and password below to your own username and password.
connection_params = {"user":"postgres",
"password":"",
"dbname":"hmda",
"host":"localhost"}
def connect(params):
"""
This function accepts a dictionary of connection parameters that must include:
- user: the username to be used for the database session
- password: the user's password
- dbname: the name of the database for connection
- host: the host location of the database
"""
#attempt a connection with the supplied parameters
try:
conn = psycopg2.connect(**params)
print("I'm connected") #print a success message
return conn.cursor() #return a cursor object
except psycopg2.Error as e:
print("I am unable to connect to the database: ", e) #print a fail message and the error, if any
#Test the connection function, if everything is correct, it will print "I'm connected."
cur = connect(params=connection_params)
#Close the cursor. This is important as open cursors can interfere with updates to data tables.
cur.close()
#When using Jupyter, it is best to open and close the cursor in the same code cell.
#If there are coding errors that interrupt the execution, the cursor will need to be reestablished.
```
### Variabalizing a SQL Command String for Filtering
As demonstrated in the previous example, Python strings can contain markers which enable substitution of values. This allows use of the .format() command to change the table reference for the SQL query. The string below selects the activity year and the filer count, variabalizing the year.
```
sql_command = """SELECT
activity_year,
COUNT (*) AS filer_count
FROM
hmda_public.ts_{year}
GROUP BY
activity_year;"""
```
A SQL command string may be modified to select a count of filers by a given category. The command string below not only variabalizes the year of the file to be selected but also creates an extention to the query that may be modified by the user.
```
sql_base = """SELECT
activity_year,
COUNT (*) AS filer_count
FROM
hmda_public.ts_{year}
{extention}
;"""
```
### Selecting the Number of Filers by a Particular State
The code above may be placed in another sql file, which may be called by the the time series function defined in the previous example. The code below may be used to select for the number of filers who have their headquarters in New York. Respondent_state refers to the headquarters location of the institution and does not necessarily reflect lending patterns in that geography.
```
cur = connect(connection_params) #Establishes cursor object and connect to the database
year = 2017 #Provides the year of the file
#Sets the extention variable so that it selects filers in the state of New York
extention = "WHERE respondent_state = 'NY' GROUP BY activity_year, respondent_state"
#Executes the query text against the database, formatting for the year and the extention
cur.execute(sql_base.format(year=year, extention=extention))
results = cur.fetchall() #Returns the query results.
#Converts the results_list into a Pandas dataframe with names pulled from the SQL query.
results_df = pd.DataFrame(results, columns=[desc[0] for desc in cur.description])
cur.close() #Closes the connection and remove the cursor object.
results_df.head() #Shows the top 5 rows of the dataframe
```
### Using A Function to Create a Timeseries of Counts by Category
A function may defined to create a Pandas dataframe of filer counts by a category. The sql command above that variabalizes by category may be placed in file.
The code below demonstrates a function that passes in a sql_command file, a start-year, an end-year, and an extention to the sql_command file. The default for the function produces a time series between years 2004 and 2017 in the form of a Pandas dataframe.
As shown below, the Pandas "loc" function may be used to reorder columns.
```
def time_series_by_category(sql_file=None, cur=None, extention=None, start=2004, end=2017):
"""
This function requires a path to a SQL file and a cursor object.
The default start year is 2004, the default end year is 2017.
This function will call the passed SQL file against each of the years
from start to end.
The results will be returned as a Pandas dataframe.
"""
years = list(range(start, (end+1))) #Convert start and stop points to a list for iteration.
results_list = [] #Create an empty list to hold query results.
for year in years: #Iterate over desired years.
sql_base = "" #Create blank string to modify into SQL query.
with open(sql_file) as in_sql: #Open the SQL file.
for line in in_sql.readlines(): #Read all lines in the SQL file.
sql_base = sql_base + line.strip("\n") #Concatenate lines and remove newline characters.
#Replace the year and extention placeholder and execute the query.
cur.execute(sql_base.format(year=year,extention=extention))
results = cur.fetchall() #Return results from the cursor.
results_list.append(results[0]) #Append results to list.
#Convert results list to a dataframe with column names from the query.
results_df = pd.DataFrame(results_list, columns=[desc[0] for desc in cur.description])
return results_df #return a dataframe of the results
#Using the function to return data.
cur = connect(connection_params) #Create a database connection and cursor object.
#Call the function.
time_series_df = time_series_by_category(sql_file="sql_commands/2_filer_count_by_category.sql",
cur=cur,
extention="WHERE respondent_state = 'NY' GROUP BY activity_year, respondent_state")
time_series_df #Show the dataframe.
```
### Saving a Dataframe to a Pipe-Delimited File
The dataframe created in the previous step can be saved to a file in a single command using the to_csv() command in Pandas.
The first argument passed is the desired path and name of the file.
If the passed directory path does not exist an error will be thrown. For programmatic creation of file paths, see documentation of the OS module.
The delimiter used in file creation can be changed by passing sep="delimiter".
By default, the dataframe index is saved to the file. To change this behavior pass index=False.
```
#Save the dataframe to a file
time_series_df.to_csv("analysis_output/tables/2_filer_count_by_category.txt",
index=False, sep="|")
```
### Visualizing Data From Dataframes
The below example will use Matplotlib (imported as plt) to do some basic visualization.
Drawing from the previous example, a function may be defined to plot using information from a pandas dataframe.
```
def bar_chart(x_data=None, y_data=None, title="Chart Title", x_label=None, y_label=None,
color="blue", figsize=(10,5)):
"""
This function requires two Pandas data series for x and y data.
Optionally: the x label, y label, color, title, and size may be set.
This function returns a bar chart with the specified parameters.
"""
if x_data is None or y_data is None:
print("No data passed.")
return None
if x_label is None:
x_label = x_data.name
if y_label is None:
y_label = y_data.name
fig = plt.figure(figsize=figsize) #Sets size of the bar chart.
plt.bar(x_data, y_data, color=color) #Plots x and y and set the color.
plt.title(title) #Sets title of the chart.
plt.xlabel(x_label) #Sets x-axis label.
plt.ylabel(y_label) #Sets y-axis label.
plt.xticks(x_data, rotation='45') #Setting x-tick labels and rotating 45 degrees.
return plt
#Create a bar chart using the function defined above.
#Save the graph output to a PNG file.
plt = bar_chart(x_data=time_series_df['activity_year'], y_data=time_series_df['filer_count'],
title="Number of HMDA Filers in NY, 2004-2017", figsize=(10,5))
plt.savefig('analysis_output/charts/2_filer_count_by_category.png')
```
| github_jupyter |
## ASSIGNMENT 4
In this assignment we will start combining different aspects (i.e., variables, loops, indexing) of the first three assignments.
### Flipping strings
Remember, you can get individual letters from a string using square brackets, similar to lists and tuples:
```python
my_string = 'banana'
len(my_string) # will give 6
l = 2
my_string[l] # will give 'n'
```
#### Question 1
Use range() to define a sequence that counts down from the length of the string to 0. In the case of our example, where my_string=='banana' , the sequence should be:<br/>
[5, 4, 3, 2, 1, 0]
* At the top of the cell assign 'banana' to the variable my_string
* In python 3 you need list to print the output of range (e.g., list(range(10))
* don't simply assume that myString has length 6, but use a function to get the length of the string
```
#answer question 1
```
#### Question 2
Use your answer to question 1 in a for-loop to print the letters from my_string in reversed order
* In the for loop you don't need the list wrapper anymore
```
#answer question 2
```
#### Question 3
We can use the code above to flip strings, e.g. to turn 'banana' into 'ananab'. To do this, you need to take the following steps:
1. define a new string called rev_string, which starts empty ('')
2. Use range() again to loop over the characters in myString in reverse.
3. Do not print every individual letter, but append every letter to rev_string (remember you can use + for that, just as with lists).
4. print rev_string to see if your script worked!<br/><br/>
perform these steps in python, and flip "I am a reversed string"
```
#answer question 3
```
#### Question 4
If we want to reverse a lot of strings, it is a good idea to write a function that does this. Therefore, write a function called stringReverse(). It takes exactly one argument, which is the string you want to flip. For the rest, it does exactly the same as your code in response to question 3. Test your function using a new string:
```python
string_B = 'murder for a jar of red rum'
stringReverse(string_B) # ' mur der fo raj a rof redrum '
```
```
#answer question 4
```
#### Question 5
Currently, our function flips its input string, then prints it and forgets it. That is a pity if we want to use this flipped string later on. Luckily, as we have seen before, functions can also return values. Write a new function based on stringReverse() called stringReverse2(). This function is identical, except that it does not print the flipped string but returns it.<br/><br/>
To test whether your function works, store the result of your function in a variable, and feed it back into your function to retrieve the original via the foloowing code:
```python
original_string = 'This is the original string'
flipped_string = stringReverse2(original_string)
flipped_back = stringReverse2(flipped_string)
if flipped_back == original_string:
print("Yes.", flipped_back)
else:
print("No.", flipped_back, " is not the same!")
```
```
#answer question 5
```
### Number guessing game
During the second lecture, a number guessing game was given as an example of how to use a while loop. In its current form, the game stops once the number is guessed right. In this exer-cise you are going to change this. Your program will ask the player if he or she wants to play again, and restart the game if he or she answers ‘y’, but exit the program if the answer is ‘n’.
#### Question 6
The cell below contains code that allows you to play a number guessing game. Unfortunatly, the code as specified below still contains a couple of errors. Please adjust the code such that you can play the number guessing game.
```
# answer question 6
to_guess = 6
while True:
# ask player to guess (use int() to change input string to a number)
guess = int(input('Guess the number: \n'))
if guess < :
print ('Your guess is too low, please guess again.')
:
print ('Your guess is too high, please guess again.')
print 'Yes {} was the correct answer. Thank you for playing'.format(guess)
break
```
#### Question 7
In the cell below paste your answer to question 6 inside a while loop, that will repeat if the user an-swers ‘y’ and stop if he answers ‘n’. You can use the function input() to listen for key-board input from the player, as is done when the player is asked to enter a number. The player should only be asked the question to play again after he or she has finished a round (so the game shouldn’t start with the question).
```
#answer question 7
```
#### Question 8
It is likely that you have implemented question 7 in such a way, that the user can also give other responses than “y” or “n”, and that the game will either quit or start over after such an invalid response. Make sure the player can only answer with ‘y’ or ‘n’ to the question of playing again, and print “Please answer with ‘y or ‘n’” if any other input than y or n is given.
Also, make sure you can use lowercase and uppercase ‘y’ and ‘n’
```
#answer question 8
```
#### Question 9
The number to be guessed is fixed at 6 in the example. It would make the game more inter-esting if a random number is picked when a new round starts. Find a function in the random module with which you can generate a random number between 1 and 20 and let the player guess that number.
```
#answer question 8
```
### Bonus questions
As a extra addition to the game, in the cell above change the code such that if the 'player’ input is not an integer then you provide the message “your input is not a number” and the 'player' should be asked to guess the number again.
Finally, keep track of the number of guesses needed to arrive at the correct answer and provide feedback based on the performance.
If only guess was needed print "Lucky bastard, maybe you should go to the casino?"
If more than 6 guesses were needed print "Finally, come on it is not that hard, please try harder"
Otherwise as before simply print 'Yes {} was the correct answer. Thank you for playing'.format(guess))
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pymc3 as pm
import seaborn as sns
from utils import ECDF
from data import load_kruschke
%load_ext autoreload
%autoreload 2
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
```
# Bayesian comparison of two (or more) groups
Comparison of two groups is a ubiquitous inference task. You'll find it in many places:
- Experimental biologists have a control group and some treatment.
- Marketers call this A/B testing.
- In clinical research, we'll have a case and control group, in which the case group receives an intervention.
In this notebook, we will be introducing the use of PyMC3, a probabilistic programming language for Bayesian statistical modelling, and we will show how you can use PyMC3 to perform inference on this common statistical task.
This notebook will be more guided than the latter ones, to help you get familiar with the syntax.
## Problem 1: The Intervention-IQ Problem
### Data Credits
The data for this exercise was obtained from John Kruschke's paper, [Bayesian Estimation supersedes the T-test][best]. The data come from a fictional study of a drug and its effect on IQ, and have been slightly modified for pedagogical reasons.
[best]: http://www.indiana.edu/~kruschke/BEST/BEST.pdf
### Setup
You are consulting for an academic research group, which would like to independently evaluate whether an intervention boosts IQ or not. To investigate this problem, the research group has set up a case-control study, comparing the IQ of students with and without the intervention.
### Step 1: Define Data Generating Process
Without looking at the data, let us first think about the generative model for the data.
Generative models, you might ask?
A generative model is not necessarily a mechanistic model, in which every last detail is captured. Rather, a generative model lets us use probability distributions to express how the data were generated.
One strategy for the data generating process is to go forward from first principles. This tends to be more mechanistic and principled, particularly when we are modelling a physical system or a known process.
The other strategy is to go backwards from what the data might look like. This is useful when we do not have all of the necessary details, and is a flexible way to approximate how our data were generated.
For this particular problem, we will take the latter strategy.
#### Intervention IQ Data Generating Process
The data generating process for this problem may be specified as such:
1. We know that the IQ can be approximately modelled by normal distributions.
1. Because interventions in humans are generally expensive, we typically take few samples. Thus, instead of a normal distribution, which makes strong assumptions about having skinny tails (low probability mass in the extremes), we might want its more flexible cousin, the t-distribution.
1. This forms the **likelihood function** for the data.
1. The t-distribution is parameterized by three parameters:
1. Mean
1. Variance (or standard deviation)
1. Degrees of Freedom (DoF)
1. It is for these data parameters for which we require **priors**.
1. Mean: Assuming no good prior information, it is common to use a relatively wide normal distribution: $\mu \sim N(0, 100)$
1. Variance: Should be positive. Assuming no prior information, use a relatively flat positive distribution: $\sigma \sim HalfCauchy(100)$
1. Degrees of Freedom ($\nu$): Should be positive and not equal to zero. We know some properties of DoF: when degrees of freedom is equal to 1, the t-distribution is equivalent to a Cauchy distribution, and as degrees of freedom go to infinity, the t-distribution becomes more and more like a Normal distribution.
1. This is a nuisance parameter - we need it for modelling with the t-distribution, but we don't really care about it .
1. [Questions have been asked][stats_exchange] regarding what are good priors. Check out [this link][stats_exchange] for more information.
1. Therefore, just as with the other parameters, we can assign a fairly flat degree of freedom parameter, and let the data speak for itself.
[stats_exchange]: https://stats.stackexchange.com/questions/6492/whats-a-good-prior-distribution-for-degrees-of-freedom-in-a-t-distribution
With this setup, we have *explicitly stated our assumptions* about what we believe about the data generating process, prior to having seen any data.
In pictures, that big chunk of bullet points above can be visualized as follows:

### Step 2: Explore the Data
Now that we have a first-pass generative model for the data, let's do some quick sanity checks against the data.
Let's get started by loading the data!
```
df = load_kruschke()
df.sample(5)
```
**Exercise:** Plot the number of samples for drug and for treatment.
```
df.groupby('treatment').size().plot(kind='bar') # blank out "treatment"
```
More important than the number of samples per treatment is the distribution of IQ, which will give us a hint as to whether we can expect a difference in effect.
**Exercise:** Plot the ECDF of the treatments vs. control. If you need to inspect the source code of ECDF, it is available below.
```
ECDF??
placebo_filter = df['treatment'] == 'placebo'
drug_filter = df['treatment'] == 'drug'
fig, ax = plt.subplots(nrows=1, ncols=1)
x_ctrl, y_ctrl = ECDF(df[placebo_filter]['iq'])
x_treat, y_treat = ECDF(df[drug_filter]['iq'])
ax.plot(x_ctrl, y_ctrl, label='placebo')
ax.plot(x_treat, y_treat, label='drug')
ax.set_xlabel('IQ')
ax.set_ylabel('Cumulative Fraction')
ax.legend()
```
**Discuss:** Does it look like the treatment had an effect on the IQ of the participants? What numbers from the chart above can help support your conclusions?
### Step 3: Fit Model
**Exercise:** We will specify the model below. Fill in the distributions as we go along in class. We are proceeding slowly here, simply to give you repetition practice with PyMC3's syntax.
```
with pm.Model() as kruschke_model:
# Prior for drug-treated IQ mean.
mu_drug = pm.Normal('mu_drug', mu=0, sd=100**2)
# Prior for placebo-treated IQ mean.
mu_placebo = pm.Normal('mu_placebo', mu=0, sd=100**2)
# Prior for drug treated IQ standard deviation.
sigma_drug = pm.HalfCauchy('sigma_drug', beta=100)
# Prior for placebo treated IQ standard deviation.
sigma_placebo = pm.HalfCauchy('sigma_placebo', beta=100)
# Prior for nuisance parameter. Adding a small positive number
# guarantees that we never get nu == 0 by accident
# (e.g. through rounding error).
nu = pm.Exponential('nu', lam=1/29) + 1
# Likelihood function for the drug-treated participants' IQ.
drug_like = pm.StudentT('drug', nu=nu, mu=mu_drug,
sd=sigma_drug, observed=df[drug_filter]['iq'])
# Likelihood function for the placebo-treated participants' IQ.
placebo_like = pm.StudentT('placebo', nu=nu, mu=mu_placebo,
sd=sigma_placebo, observed=df[placebo_filter]['iq'])
# Calculate the effect size and its uncertainty.
diff_means = pm.Deterministic('diff_means', mu_drug - mu_placebo)
pooled_sd = pm.Deterministic('pooled_sd',
np.sqrt(
(np.power(sigma_drug, 2) + np.power(sigma_placebo, 2)) / 2
)
)
effect_size = pm.Deterministic('effect_size',
diff_means / pooled_sd)
```
A few pointers to help you read the code.
PyMC3 distributions are implemented using Distribution objects. Their object names match their distribution names. This is a very nice implementation detail of PyMC3! Additionally, [the docs][pymc3] show the parameters that are accepted; occasionally, the default parameterization might differ from what you have seen before, so referring to the docs is very important.
[pymc3]: http://docs.pymc.io
`pm.Deterministic` allows us to compute a deterministic transform on the random variables. Wrapping this in a Deterministic object allows us to hook the result of the transformation into the tools used later for visualizing posterior distributions.
Now, we hit the Inference Button!
```
# Fill in `kruschke_model`
with kruschke_model:
# Fill in `pm.sample(2000)`
trace = pm.sample(2000)
```
Let's visualize the posterior distribution.
```
# Use `pm.plot_posterior()`
pm.plot_posterior(trace, varnames=['mu_drug', 'mu_placebo'])
```
### Step 4: Evaluate Model
We use posterior predictive checks (PPC) as one tool in our toolkit to evaluate and critique the model. The overarching goal of the PPC is to check that the data generating model generates simulated data that matches closely to the actual data. If this is the case, then we have a model that probably describes the data generating process well. If this is not the case, then we have evidence to go guide us towards re-doing the model.
**Exercise:** To do a PPC, PyMC3 provides a `sample_ppc` function, which allows us to draw samples from the posterior distribution as a check. Run the following cell, filling in the appropriate `trace` and `model`.
```
samples = pm.sample_ppc(trace=trace, samples=500, model=kruschke_model)
```
**Exercise:** Let's now plot the ECDF of the sampled data against the original data.
```
samples['drug'].shape
fig, [ax1, ax2] = plt.subplots(nrows=1, ncols=2, sharex=True)
x, y = ECDF(samples['drug']) # Want ECDF of drug-treatment PPC samples
ax1.plot(x, y, label='ppc')
x, y = ECDF(df[drug_filter]['iq']) # Want ECDF of drug-treatment data
ax1.plot(x, y, label='data')
ax1.legend()
ax1.set_title('drug treatment')
ax1.set_xlabel('IQ')
ax1.set_ylabel('Cumulative Fraction')
x, y = ECDF(samples['placebo']) # Want ECDF of placebo-treatment PPC samples
ax2.plot(x, y, label='ppc')
x, y = ECDF(df[placebo_filter]['iq']) # Want ECDF of placebo-treatment data
ax2.plot(x, y, label='data')
ax2.legend()
ax2.set_title('placebo')
ax2.set_xlabel('IQ')
```
It looks like we have a model that, just by eyeballing the charts, models pretty well the distribution of the observed data.
For pedagogical brevity, we did not dive into a case where the model was plausibly but nonetheless incorrectly specified. Under an incorrect model, we would expect the PPC and data distributions to be anywhere from moderately to wildly off. Having detected this from a visual comparison of the PPC samples and data, we would go back and try to see where we went wrong. We might also opt to quantify this difference using the tools provided in PyMC3.
**Exercise:** Now, let us evaluate whether the drug actually did have an effect. Recall that we computed the difference in means, as well as an effect size, both with uncertainty. Using this information, plot the posterior distribution of the difference in means and effect sizes.
```
pm.plot_posterior(trace=trace, varnames=['diff_means', 'effect_size'])
```
Questions:
1. What is the 95% highest posterior density (HPD) interval for the difference of means?
1. What is the 95% HPD interval for the effect size?
**Exercise:** Compute the p-value of the t-test for this dataset.
```
from scipy.stats import ttest_ind
ttest_ind(df[placebo_filter]['iq'], df[drug_filter]['iq'], equal_var=False)
```
**Discuss**:
1. Is there a significant difference between the drug-treated and placebo-treated participants of the intervention? (This question is intentionally vague on the definition of "significant", to encourage discussion of the difference between statistical and practical significance.)
1. Would you recommend the intervention as a method to raise people's IQ? How much money would you be willing to pay for this intervention?
## Further Reading/Watching
- PyMC3's documentation contains an example of how to do [model selection][model_selection], which we did not touch on here.
- John Kruschke's paper on [Bayesian Estimation][bayes_est] is what this notebook's example is based on. There is also a [YouTube video][bayes_yt] available.
[model_selection]: https://docs.pymc.io/notebooks/GLM-model-selection.html
[bayes_est]: http://www.indiana.edu/~kruschke/BEST/BEST.pdf
[bayes_yt]: https://www.youtube.com/watch?v=fhw1j1Ru2i0
## Alternative Syntax
There is an alternative syntax that can be used, one that takes advantage of numpy-like fancy indexing. See it below:
```
with pm.Model() as kruschke_model_alt:
# We have two mus, therefor we have a vector of distributions of shape (2,).
# Likewise for sds.
mus = pm.Normal('mu', mu=0, sd=100**2, shape=(2,))
sds = pm.HalfCauchy('sigma', beta=100, shape=(2,))
# Prior for nuisance parameter. Adding a small positive number
# guarantees that we never get nu == 0 by accident
# (e.g. through rounding error).
nu = pm.Exponential('nu', lam=1/29) + 1
# Likelihood function for the IQ values.
# Fancy indexing allows us
likelihood = pm.StudentT('likelihood', nu=nu, mu=mus[df['treatment_enc']],
sd=sds[df['treatment_enc']], observed=df['iq'])
# Calculate the effect size and its uncertainty.
diff_means = pm.Deterministic('diff_means', mus[0] - mus[1])
pooled_sd = pm.Deterministic('pooled_sd',
np.sqrt(np.power(sds[0], 2) +
np.power(sds[1], 2) / 2))
effect_size = pm.Deterministic('effect_size',
diff_means / pooled_sd)
with kruschke_model_alt:
trace_alt = pm.sample(2000, tuning=1000)
traces = pm.traceplot(trace_alt)
pm.plot_posterior(trace_alt, varnames=['mu', 'effect_size'])
```
# Next Steps
If you are feeling comfortable with PyMC3's syntax, in particular fancy indexing, and would like to move onto trying your hand at solving an inference problem without more guidance, then please proceed to Notebook 5.
If you are feeling the need to get more practice with PyMC3's syntax, then proceed to Notebook 4.
| github_jupyter |
# Discovering structure behind data
Let's understand and model the hidden structure behind data with Decision Trees. In this tutorial, we'll explore and inspect how a model can do its decisions on a car evaluation data set. Decision trees work with simple "if" clauses dichotomically chained together, splitting the data flow recursively on those "if"s until they reach a leaf where we can categorize the data. Such data inspection could be used to reverse engineer the behavior of any function.
Since [decision trees](http://www.r2d3.us/visual-intro-to-machine-learning-part-1/) are good algorithms for discovering the structure hidden behind data, we'll use and model the car evaluation data set, for which the prediction problem is a (deterministic) surjective function. This means that the inputs of the examples in the data set cover all the possibilities, and that for each possible input value, there is only one answer to predict (thus, two examples with the same input values would never have a different expected prediction). On the point of view of Data Science, because of the properties of our dataset, we won't need to use a test set nor to use cross validation. Thus, the error we will obtain below at modelizing our dataset would be equal to the true test error if we had a test set.
The attribute to predict in the data set could have been, for example, created from a programmatic function and we will basically reverse engineer the logic mapping the inputs to the outputs to recreate the function and to be able to explain it visually.
## About the Car Evaluation Data Set
For more information: http://archive.ics.uci.edu/ml/datasets/Car+Evaluation
### Overview
The Car Evaluation Database was derived from a simple hierarchical decision model originally developed for the demonstration of DEX, M. Bohanec, V. Rajkovic: Expert system for decision making. Sistemica 1(1), pp. 145-157, 1990.). The model evaluates cars according to the following concept structure:
- CAR car acceptability:
- PRICE overall price:
- **buying** buying price
- **maint** price of the maintenance
- TECH technical characteristics:
- COMFORT comfort:
- **doors** number of doors
- **persons** capacity in terms of persons to carry
- **lug_boot** the size of luggage boot
- **safety** estimated safety of the car
Input attributes are printed in lowercase. Besides the target concept (CAR), the model includes three intermediate concepts: PRICE, TECH, COMFORT. Every concept is in the original model related to its lower level descendants by a set of examples.
The Car Evaluation Database contains examples with the structural information removed, i.e., directly relates CAR to the six input attributes: buying, maint, doors, persons, lug_boot, safety.
Because of known underlying concept structure, this database may be particularly useful for testing constructive induction and structure discovery methods.
### Attributes, instances, and Class Distribution
Number of Attributes: 6
Missing Attribute Values: none
| Attribute | Values |
|------------|--------|
| buying | v-high, high, med, low |
| maint | v-high, high, med, low |
| doors | 2, 3, 4, 5-more |
| persons | 2, 4, more |
| lug_boot | small, med, big |
| safety | low, med, high |
Number of Instances: 1728 (Instances completely cover the attribute space.)
| class | N | N[%] |
|---|---|---|
| unacc | 1210 | 70.023 % |
| acc | 384 | 22.222 % |
| good | 69 | 3.993 % |
| v-good | 65 | 3.762 % |
## We'll now load the car evaluation data set in Python and then train decision trees with XGBoost
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import xgboost as xgb
from xgboost import plot_tree
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
import os
```
### Define the features and preprocess the car evaluation data set
We'll preprocess the attributes into redundant features, such as using an integer index (linear) to represent a value for an attribute, as well as also using a one-hot encoding for each attribute's possible values as new features. Despite the fact that this is redundant, this will help to make the tree smaller since it has more choice on how to split data on each branch.
```
input_labels = [
["buying", ["vhigh", "high", "med", "low"]],
["maint", ["vhigh", "high", "med", "low"]],
["doors", ["2", "3", "4", "5more"]],
["persons", ["2", "4", "more"]],
["lug_boot", ["small", "med", "big"]],
["safety", ["low", "med", "high"]],
]
output_labels = ["unacc", "acc", "good", "vgood"]
# Load data set
data = np.genfromtxt(os.path.join('data', 'data/car.data'), delimiter=',', dtype="U")
data_inputs = data[:, :-1]
data_outputs = data[:, -1]
def str_data_to_one_hot(data, input_labels):
"""Convert each feature's string to a flattened one-hot array. """
X_int = LabelEncoder().fit_transform(data.ravel()).reshape(*data.shape)
X_bin = OneHotEncoder().fit_transform(X_int).toarray()
attrs_names = []
for a in input_labels:
key = a[0]
for b in a[1]:
value = b
attrs_names.append("{}_is_{}".format(key, value))
return X_bin, attrs_names
def str_data_to_linear(data, input_labels):
"""Convert each feature's string to an integer index"""
X_lin = np.array([[
input_labels[a][1].index(j) for a, j in enumerate(i)
] for i in data])
# Indexes will range from 0 to n-1
attrs_names = [i[0] + "_index" for i in input_labels]
return X_lin, attrs_names
# Take both one-hot and linear versions of input features:
X_one_hot, attrs_names_one_hot = str_data_to_one_hot(data_inputs, input_labels)
X_linear_int, attrs_names_linear_int = str_data_to_linear(data_inputs, input_labels)
# Put that together:
X = np.concatenate([X_one_hot, X_linear_int], axis=-1)
attrs_names = attrs_names_one_hot + attrs_names_linear_int
# Outputs use indexes, this is not one-hot:
integer_y = np.array([output_labels.index(i) for i in data_outputs])
print("Data set's shape,")
print("X.shape, integer_y.shape, len(attrs_names), len(output_labels):")
print(X.shape, integer_y.shape, len(attrs_names), len(output_labels))
# Shaping the data into a single pandas dataframe for naming columns:
pdtrain = pd.DataFrame(X)
pdtrain.columns = attrs_names
dtrain = xgb.DMatrix(pdtrain, integer_y)
```
### Train simple decision trees (here using XGBoost) to fit the data set:
First, let's define some hyperparameters, such as the depth of the tree.
```
num_rounds = 1 # Do not use boosting for now, we want only 1 decision tree per class.
num_classes = len(output_labels)
num_trees = num_rounds * num_classes
# Let's use a max_depth of 4 for the sole goal of simplifying the visual representation produced
# (ideally, a tree would be deeper to classify perfectly on that dataset)
param = {
'max_depth': 4,
'objective': 'multi:softprob',
'num_class': num_classes
}
bst = xgb.train(param, dtrain, num_boost_round=num_rounds)
print("Decision trees trained!")
print("Mean Error Rate:", bst.eval(dtrain))
print("Accuracy:", (bst.predict(dtrain).argmax(axis=-1) == integer_y).mean()*100, "%")
```
### Plot and save the trees (one for each class):
The 4 trees of the classifer (one tree per class) will each output a number that represents how much it is probable that the thing to classify belongs to that class, and it is by comparing the output at the end of all the trees for a given example that we could get the maximal output as associating the example to that class. Indeed, the binary situation where we have only one tree that outputs a positive and else negative number would be simpler to interpret rather than classifying for 4 binary classes at once.
```
def plot_first_trees(bst, output_labels, trees_name):
"""
Plot and save the first trees for multiclass classification
before any boosting was performed.
"""
for tree_idx in range(len(output_labels)):
class_name = output_labels[tree_idx]
graph_save_path = os.path.join(
"exported_xgboost_trees",
"{}_{}_for_{}".format(trees_name, tree_idx, class_name)
)
graph = xgb.to_graphviz(bst, num_trees=tree_idx)
graph.render(graph_save_path)
# from IPython.display import display
# display(graph)
### Inline display in the notebook would be too huge and would require much side scrolling.
### So we rather plot it anew with matplotlib and a fixed size for inline quick view purposes:
fig, ax = plt.subplots(figsize=(16, 16))
plot_tree(bst, num_trees=tree_idx, rankdir='LR', ax=ax)
plt.title("Saved a high-resolution graph for the class '{}' to: {}.pdf".format(class_name, graph_save_path))
plt.show()
# Plot our simple trees:
plot_first_trees(bst, output_labels, trees_name="simple_tree")
```
Note that the above trees can be viewed here online:
https://github.com/Vooban/Decision-Trees-For-Knowledge-Discovery/tree/master/exported_xgboost_trees
### Plot the importance of each input features for those simple decision trees:
Note here that it is the feature importance according to our simple, shallow trees. More complex trees would include more of the features/attributes with different proportions.
```
fig, ax = plt.subplots(figsize=(12, 7))
xgb.plot_importance(bst, ax=ax)
plt.show()
```
### Let's now generate slightly more complex trees to aid inspection
<p align="center">
<a href="http://theinceptionbutton.com/" ><img src="deeper.jpg" /></a>
</p>
Let's [go deeper](http://theinceptionbutton.com/) and build deeper trees. However, those trees are not maximally complex since XGBoost is rather built to boost over forests of small trees than a big one.
```
num_rounds = 1 # Do not use boosting for now, we want only 1 decision tree per class.
num_classes = len(output_labels)
num_trees = num_rounds * num_classes
# Let's use a max_depth of 4 for the sole goal of simplifying the visual representation produced
# (ideally, a tree would be deeper to classify perfectly on that dataset)
param = {
'max_depth': 9,
'objective': 'multi:softprob',
'num_class': num_classes
}
bst = xgb.train(param, dtrain, num_boost_round=num_rounds)
print("Decision trees trained!")
print("Mean Error Rate:", bst.eval(dtrain))
print("Accuracy:", (bst.predict(dtrain).argmax(axis=-1) == integer_y).mean()*100, "%")
# Plot our complex trees:
plot_first_trees(bst, output_labels, trees_name="complex_tree")
# And their feature importance:
print("Now, our feature importance chart considers more features, but it is still not complete.")
fig, ax = plt.subplots(figsize=(12, 7))
xgb.plot_importance(bst, ax=ax)
plt.show()
```
Note that the above trees can be viewed here online:
https://github.com/Vooban/Decision-Trees-For-Knowledge-Discovery/tree/master/exported_xgboost_trees
### Finding a perfect classifier rather than an easily explainable one
We'll now use boosting. The resulting trees can't be explained as easily as the previous ones, since one classifier will now have incrementally many trees for each class to reduce error, each new trees based on the errors of the previous ones. And those trees will each be weighted.
```
num_rounds = 10 # 10 rounds of boosting, thus 10 trees per class.
num_classes = len(output_labels)
num_trees = num_rounds * num_classes
param = {
'max_depth': 20,
'eta': 1.43,
'objective': 'multi:softprob',
'num_class': num_classes,
}
bst = xgb.train(param, dtrain, early_stopping_rounds=1, num_boost_round=num_rounds, evals=[(dtrain, "dtrain")])
print("Boosted decision trees trained!")
print("Mean Error Rate:", bst.eval(dtrain))
print("Accuracy:", (bst.predict(dtrain).argmax(axis=-1) == integer_y).mean()*100, "%")
```
In our case, note that it is possible to have an error of 0 (thus an accuracy of 100%) since we have a dataset that represents a function, which is mathematically deterministic and could be interpreted as programmatically pure in the case it would be implemented. But wait... we just implemented and recreated the function that was used to model the dataset with our trees! We don't need cross validation nor a test set, because our training data already covers the full feature space (attribute space).
### Finally, the full attributes/features importance:
```
# Some plot options from the doc:
# importance_type : str, default "weight"
# How the importance is calculated: either "weight", "gain", or "cover"
# "weight" is the number of times a feature appears in a tree
# "gain" is the average gain of splits which use the feature
# "cover" is the average coverage of splits which use the feature
# where coverage is defined as the number of samples affected by the split
importance_types = ["weight", "gain", "cover"]
for i in importance_types:
print("Importance type:", i)
fig, ax = plt.subplots(figsize=(12, 7))
xgb.plot_importance(bst, importance_type=i, ax=ax)
plt.show()
```
## Conclusion
To sum up, we managed to get a good classification result and to be able to explain those results visually and automatically, but not with full depth here due to XGBoost not being built especially for having complete trees. Also note that it would have been possible to solve a regression problem with the same algorithm, such as predicting a price rather than a category, using a single tree. Note that if you want to have full depth with your trees, we also explored the [decision trees as implemented in scikit-learn](https://github.com/Vooban/Decision-Trees-For-Knowledge-Discovery/blob/master/Decision-Trees-For-Knowledge-Discovery-With-Scikit-Learn.ipynb).
Such techniques using decision trees can be useful in reverse engineering an existing system, such as an old one that has been coded in a peculiar programming language and for which the employees who coded it have left. This technique can also be used for data mining, gaining business intelligence, and insights from data.
Decision trees are good to model data sets and XGBoost has revealed to be a [quite good algorithm for winning Kaggle competitions](http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/). Using XGBoost can lead to great results in plus of being interesting for roughly explaining how classifications are made on data. However, XGBoost is normally used for boosting trees (also called gradient boosting) and the resulting forest is hard to interpret. Each tree is trained on the errors of the previous ones until the error gets at its lowest.
| github_jupyter |
# Multivariate statistics (decoding / MVPA) on MEG/EEG
Authors : Alexandre Gramfort, Richard Höchenberger
See more info on decoding on this page: https://mne.tools/stable/auto_tutorials/machine-learning/plot_sensors_decoding.html
First, load the mne package:
```
import mne
```
We set the log-level to 'WARNING' so the output is less verbose
```
mne.set_log_level('WARNING')
```
## Access the raw data
Now we import the `sample` dataset. It will be downloaded automatically (approx. 2 GB).
```
import os
from mne.datasets import sample
data_path = sample.data_path()
raw_fname = os.path.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif')
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw
```
High-pass filter the data.
```
raw.filter(l_freq=1, h_freq=None, verbose=True)
print(raw.info)
```
## Define epochs
We're only interested in `auditory left` and `auditory right`.
First extract events:
```
events = mne.find_events(raw, stim_channel='STI 014', verbose=True)
```
Look at the design in a graphical way. We're only interested in `auditory left` and `auditory right`.
```
event_id = {'aud_l': 1, 'aud_r': 2} # event trigger and conditions
fig = mne.viz.plot_events(events, sfreq=raw.info['sfreq'],
first_samp=raw.first_samp, event_id=event_id)
```
Define epochs parameters:
```
tmin = -0.1 # start of each epoch (in seconds)
tmax = 0.4 # end of each epoch
baseline = None # no baseline correction, data were high-pass filtered
reject = dict(eeg=80e-6, eog=40e-6)
picks = mne.pick_types(raw.info, eeg=True, meg=True,
eog=True, stim=False, exclude='bads')
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
picks=picks, baseline=baseline,
reject=reject, preload=True) # with preload
print(epochs)
```
Look at the ERF and contrast between left and right stimulation.
```
evoked_left = epochs['aud_l'].average()
evoked_right = epochs['aud_r'].average()
evoked_contrast = mne.combine_evoked([evoked_left, evoked_right],
weights=[1, -1])
fig = evoked_left.plot()
fig = evoked_right.plot()
fig = evoked_contrast.plot()
```
### Plot some topographies
```
vmin, vmax = -4, 4 # Colorbar range
fig = evoked_left.plot_topomap(ch_type='eeg', contours=0, vmin=vmin, vmax=vmax)
fig = evoked_right.plot_topomap(ch_type='eeg', contours=0, vmin=vmin, vmax=vmax)
fig = evoked_contrast.plot_topomap(ch_type='eeg', contours=0, vmin=None, vmax=None)
```
## Now let's see if we can classify single trials.
To keep chance level at 50% accuracy, we first equalize the number of epochs in each condition.
```
epochs.equalize_event_counts(event_id)
print(epochs)
```
A classifier takes as input an `X` and returns `y` (0 or 1). Here `X` will be the data at one time point on all gradiometers (hence the term multivariate). We want to train our model to discriminate between the `auditory left` and the `auditory right` trials.
We work with all sensors jointly and try to find a discriminative pattern between the two conditions to predict the class.
For classification we will use the scikit-learn package (http://scikit-learn.org/) and MNE functions.
Let's first create the response vector, `y`.
```
import numpy as np
y = np.empty(len(epochs.events), dtype=int)
idx_auditory_left = epochs.events[:, 2] == event_id['aud_l']
idx_auditory_right = epochs.events[:, 2] == event_id['aud_r']
y[idx_auditory_left] = 0
y[idx_auditory_right] = 1
y.size
```
Now, the input matrix, `X`.
```
X = epochs.copy().pick_types(meg='grad').get_data()
X.shape
XX = X.reshape(108, -1)
XX.shape
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
logreg = LogisticRegression()
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
clf = make_pipeline(StandardScaler(), logreg)
scores = cross_val_score(clf, XX, y, cv=cv, scoring='roc_auc')
roc_auc_mean = np.mean(scores)
roc_auc_std = np.std(scores)
print(f'CV scores: {scores}')
print(f'Mean ROC AUC = {roc_auc_mean:.3f} (std: {roc_auc_std:.3f})')
```
## We can do this more simply using the `mne.decoding` module! Let's do some spatio-temporal decoding.
```
from sklearn.pipeline import make_pipeline
from mne.decoding import Scaler, Vectorizer, cross_val_multiscore
epochs_decoding = epochs.copy().pick_types(meg='grad')
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
clf = make_pipeline(Scaler(epochs_decoding.info),
Vectorizer(),
logreg)
X = epochs_decoding.get_data()
y = epochs_decoding.events[:, 2]
scores = cross_val_multiscore(clf, X, y, cv=cv, scoring='roc_auc')
roc_auc_mean = np.mean(scores)
roc_auc_std = np.std(scores)
print(f'CV scores: {scores}')
print(f'Mean ROC AUC = {roc_auc_mean:.3f} (std: {roc_auc_std:.3f})')
```
<div class="alert alert-success">
<b>EXERCISES:</b>
<ul>
<li>Why do you get different results from above? what did we change in the model?</li>
<li>How does the choice of cross-validation affect the results? Hint: Change the random_state</li>
<li>Try a different cross-validtion object like scikit-learn StratifiedShuffleSplit</li>
<li>Which sensor types give the best classification scores? EEG, MEG gradiometers, MEG magnetometers?</li>
</ul>
</div>
## Decoding over time: Comparisons at every single time point.
In the previous examples, we have trained a classifier to discriminate between experimentel conditions by using the spatio-temporal patterns of **entire trials**. Consequently, the classifier was (hopefully!) able to predict which activation pattern belonged to which condition.
However, an interesting neuroscientific is: **Exactly *when* do the brain signals for two conditions differ?**
We can try to answer this question by fitting a classifier **at every single time point.** If the classifier can successfully discriminate between the two conditions, we can conclude that the spatial activation patterns measured by the MEG or EEG sensors differed **at this time point**.
```
from sklearn.preprocessing import StandardScaler
from mne.decoding import SlidingEstimator
X = epochs_decoding.get_data()
y = epochs_decoding.events[:, 2]
clf = make_pipeline(StandardScaler(),
logreg)
time_decod = SlidingEstimator(clf, scoring='roc_auc', n_jobs=1, verbose=True)
scores = cross_val_multiscore(time_decod, X, y, cv=5, n_jobs=1)
# Mean scores across cross-validation splits, for each time point.
mean_scores = np.mean(scores, axis=0)
# Mean score across all time points.
mean_across_all_times = np.mean(scores)
print(f'Mean CV score across all time points: {mean_across_all_times:.3f}')
# Plot
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(epochs.times, mean_scores, label='score')
ax.axhline(0.5, color='k', linestyle='--', label='chance')
ax.set_xlabel('Time (s)')
ax.set_ylabel('Mean ROC AUC')
ax.legend()
ax.axvline(0, color='k', linestyle='-')
ax.set_title('Sensor space decoding')
scores.shape
```
For more details see: https://martinos.org/mne/stable/auto_tutorials/plot_sensors_decoding.html
and this book chapter:
Jean-Rémi King, Laura Gwilliams, Chris Holdgraf, Jona Sassenhagen, Alexandre Barachant, Denis Engemann, Eric Larson, Alexandre Gramfort. Encoding and Decoding Neuronal Dynamics: Methodological Framework to Uncover the Algorithms of Cognition. 2018. https://hal.archives-ouvertes.fr/hal-01848442/
<div class="alert alert-success">
<b>EXERCISES:</b>
<ul>
<li>Plot the decoding score over time for the different channel types.</li>
<li>Do a decoding over time on the SPM `face` dataset to see if you can classify `face` vs. `scrambled face`.</li>
<li>Do a generalization over time analysis as explained in the <a href="https://mne.tools/stable/auto_tutorials/machine-learning/plot_sensors_decoding.html#temporal-generalization">documentation on decoding</a>.
</li>
</ul>
</div>
Hints:
- Access the `face` dataset via:
```
from mne.datasets import spm_face
data_path = spm_face.data_path()
raw_fname = os.path.join(data_path, 'MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds')
raw = mne.io.read_raw_ctf(raw_fname, preload=True)
```
- The event IDs are:
```
event_ids = {"faces": 1, "scrambled": 2}
```
See this online example for additional hints: https://mne.tools/dev/auto_examples/datasets/spm_faces_dataset.html
| github_jupyter |
# Getting started
### Get thermodynamic and material properties using Chemical objects
Chemical objects are an extension of the [thermo.Chemical](http://thermo.readthedocs.io/en/latest/thermo.chemical.html) class from the Chemical Engineering Design Library.
Initiallize a Chemical object with an ID:
```
import biosteam as bst
Water = bst.compounds.Chemical('Water')
Water
```
Chemical objects have a temperature `T`, pressure `P`, and `phase`:
```
Water.T, Water.P, Water.phase
```
You can view in different units with `show`:
```
Water.show(T='degC', P='atm')
```
Chemical objects contain thermodynamic properties:
```
Water.rho # (kg/m3)
```
These properties are dependent on temperature (T), pressure (P) and phase:
```
Water.T = 350 # (Kelvin)
Water.rho # (kg/m3)
```
Note how the density changed with temperature.
Many more material properties are available. Please read the [thermo.Chemical](http://thermo.readthedocs.io/en/latest/thermo.chemical.html) documentation to learn more.
### Group Chemical objects with a Species object
Initiallize a [Species](https://biosteam.readthedocs.io/en/latest/Species.html) object with IDs:
```
species = bst.Species('Methanol', 'Glycerol')
species
```
The Chemical objects are stored as attributes:
```
species.Methanol, species.Glycerol
```
Set chemical attributes:
```
species.Water = Water
species
```
### Material flows and mixture properties with Stream objects
First set the working species of all [Stream](https://biosteam.readthedocs.io/en/latest/Stream.html) objects:
```
bst.Stream.species = species # From before
```
A Stream is initialized with an ID, specie-flow rate pairs, temperature, pressure and phase:
```
feed = bst.Stream(ID='feed', Methanol=1, Glycerol=2, Water=3)
feed
```
Alternatively, flow rates can be given as an iterable:
```
feed = bst.Stream(ID='feed', flow=(1,2,3), T=300, P=101325)
feed
```
View with different units using the `show` method:
```
feed.show(flow='kg/hr', T='degC', P='atm')
```
Flow rates can be conviniently get and set:
```
feed.setflow(Water=50, units='kg/hr')
feed.getflow('Methanol', 'Water', units='kg/hr')
```
Stream objects contain T, P, and phase dependent properties:
```
feed.H # kJ/hr with reference at STP
feed.T = 350
feed.H
```
Vapor liquid equilibrium is just a line away:
```
# Set pressure and duty
feed.VLE(P=101325, Q=0)
feed
# Set vapor fraction and pressure
feed.VLE(V=0.5, P=101325)
feed
```
The stream is cast to a [MixedStream](https://biosteam.readthedocs.io/en/latest/MixedStream.html) object. Mixed streams contain multiple phases:
```
feed.phase
```
Please refer to the [MixedStream objects and thermodynamic equilibrium example](https://biosteam.readthedocs.io/en/latest/MixedStream objects and thermodynamic equilibrium.html) for more details.
### Process settings
**Process settings include price of feeds and products, conditions of utilities, and the chemical engineering plant cost index. These should be set before simulating a system.**
Set the chemical engineering plant cost index:
```
bst.CE # Default year is 2017
bst.CE = 603.1 # To year 2018
```
Set price of streams:
```
feed.price # Default price is zero
feed.price = 0.50
```
Set [PowerUtility](https://biosteam.readthedocs.io/en/latest/PowerUtility.html) options:
```
bst.PowerUtility.price # Default price
bst.PowerUtility.price = 0.065 # Adjust price
```
Set [HeatUtility](https://biosteam.readthedocs.io/en/latest/HeatUtility.html) options:
```
bst.HeatUtility.cooling_agents # Dictionary of available cooling agents
cw = bst.HeatUtility.cooling_agents['Cooling water']
cw # A UtilityAgent
# Data is stored as attributes
(cw.species, cw.molfrac, cw.T, cw.P, cw.phase, cw.T_limit, cw.price_kJ, cw.price_kmol, cw.efficiency)
cw.T = 302 # Change temperature (K)
bst.HeatUtility.heating_agents # Dictionary of available heating agents
bst.HeatUtility.heating_agents['Low pressure steam'] # A UtilityAgent
bst.HeatUtility.heating_agents['Low pressure steam'].price_kmol = 0.20 # Change price (USD/kmol)
```
### Find design requirements and cost with Unit objects
[Creating a Unit](https://biosteam.readthedocs.io/en/latest/Creating a Unit.html) can be flexible. But in summary, a [Unit](https://biosteam.readthedocs.io/en/latest/Unit.html) object is initialized with an ID, and unit specific arguments:
```
# Specify vapor fraction and isobaric conditions
F1 = bst.units.Flash('F1', V=0.5, P=101325)
F1
```
Note that, by default, Missing Stream objects are given to inputs, `ins`, and empty streams to outputs, `outs`:
```
F1.ins
F1.outs
```
You can connect streams by setting the `ins` and `outs`:
```
F1.ins[0] = bst.Stream(Water=220, Glycerol=180)
F1
```
To simulate the flash, use the `simulate` method:
```
F1.simulate()
F1.show()
```
The `results` method returns simulation results:
```
F1.results() # Default returns DataFrame object with units
F1.results(with_units=False) # Returns Series object without units
```
### Solve recycle loops and process specifications with System objects
**Designing a chemical process is no easy task. A simple recycle process consisting of a flash with a partial liquid recycle is presented here.**
Create a [Mixer](https://biosteam.readthedocs.io/en/latest/Mixer.html) object and a [Splitter](https://biosteam.readthedocs.io/en/latest/Splitter.html) object:
```
M1 = bst.units.Mixer('M1')
S1 = bst.units.Splitter('S1', split=0.5) # Split to 0th output stream
F1.outs[0].ID = 'product'
```
You can [find unit operations and manage flowsheets](https://biosteam.readthedocs.io/en/master/tutorial/Managing%20flowsheets.html) with `find`:
```
bst.find.diagram()
```
Connect streams and make a recycle loop using [-pipe- notation](https://biosteam.readthedocs.io/en/latest/Using -pipe- notation.html):
```
feed = bst.Stream('feed', Glycerol=100, Water=450)
# Broken down -pipe- notation
[S1-0, feed]-M1 # M1.ins[:] = [S1.outs[0], feed]
M1-F1 # F1.ins[:] = M1.outs
F1-1-S1 # S1.ins[:] = [F1.outs[1]]
# All together
[S1-0, feed]-M1-F1-1-S1;
```
Create [System](https://biosteam.readthedocs.io/en/latest/System.html) object by specifying an ID, a `recycle` stream and a `network` of units:
```
sys1 = bst.System('sys1', network=(M1, F1, S1), recycle=S1-0) # recycle=S1.outs[0]
sys1
```
View the System object as a Graphviz diagram:
```
sys1.diagram()
```
Simulate the System object:
```
sys1.simulate()
sys1.show()
F1.show()
F1.results()
```
Save a system report:
```
sys1.save_report('Example.xlsx') # Try this on your computer and open excel
```
Once process settings are set and the system is simulated, it is possible to perform [techno-economic analysis of a biorefinery](https://biosteam.readthedocs.io/en/latest/Techno-economic analysis of a biorefinery.html). If a [TEA](https://biosteam.readthedocs.io/en/latest/TEA.html) object of the system was initialized, TEA results would also appear in the report.
### Join the community!
BioSTEAM will become more relevant with communitity involvement. It is strongly encouraged to share designs and new [Unit subclasses](https://biosteam.readthedocs.io/en/latest/Inheriting from Unit.html), no matter how preliminary or rigorous they are.
| github_jupyter |
```
# Import the necessary libraries
import tensorflow as tf
import tensorflow.keras as keras
# This loads the EfficientNetB7 model from the Keras library
# Input Shape is the shape of the image that is input to the first layer. For example, consider an image with shape (width, height , number of channels)
# 'include_top' is set to 'False' to load the model with out the classification or dense layers. Top layers are not required as this is a segmentation problem.
# 'weights' is set to imagenet, that is, it uses the weight it learnt while training on the imagenet dataset. You can set it to None or your custom_weights.
# IMAGE_WIDTH, IMAGE_HEIGHT and CHANNELS values provided for visualization. Please change to suit your dataset.
IMAGE_WIDTH = 512
IMAGE_HEIGHT = 512
CHANNELS = 3
model = tf.keras.applications.EfficientNetB7(input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS),
include_top=False, weights="imagenet")
#To see the list of layers and parameters
# For EfficientNetB7, you should see
'''Total params: 64,097,687
Trainable params: 63,786,960
Non-trainable params: 310,727'''
model.summary()
# Importing the layers to create the decoder and complete the network
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Lambda
from tensorflow.keras.layers import Conv2D, Conv2DTranspose
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Concatenate
from tensorflow.keras import optimizers
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.metrics import MeanIoU
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau
from tensorflow.keras.metrics import MeanIoU, Recall, Precision
import tensorflow_addons as tfa
# Defining the Convolution Block
def conv_block(input, num_filters):
x = Conv2D(num_filters, 3, padding="same", kernel_initializer="he_normal")(input)
x = BatchNormalization()(x)
#Used the Mish activation function as it performs better than ReLU (but is computionally expensive)
x = tfa.activations.mish(x)
#Comment the previous line and uncomment the next line if you limited compute resource
#x = Activation("relu")(x)
x = Conv2D(num_filters, 3, padding="same", kernel_initializer="he_normal")(x)
x = BatchNormalization()(x)
x = tfa.activations.mish(x)
#x = x*tf.math.tanh(tf.softplus(x)) #Mish activation in a mathematical form
#x = Activation("relu")(x)
return x
#Defining the Transpose Convolution Block
def decoder_block(input, skip_features, num_filters):
x = Conv2DTranspose(num_filters, (2, 2), strides=2, padding="same")(input)
x = Concatenate()([x, skip_features])
#Use dropout only if the model is overfitting
#x = Dropout(0.05)(x)
x = conv_block(x, num_filters)
return x
#Building the EfficientNetB7_UNet
def build_efficientNetB7_unet(input_shape):
""" Input """
inputs = Input(shape=input_shape, name='input_image')
""" Pre-trained EfficientNetB7 Model """
effNetB7 = tf.keras.applications.EfficientNetB7(input_tensor=inputs, include_top=False,
weights="imagenet")
# This Section will let you freeze and unfreeze layers. Here I have frozen all layer except
# the last convolution block layers starting after layer 61
for layer in effNetB7.layers[:-61]:
layer.trainable = False
for l in effNetB7.layers:
print(l.name, l.trainable)
""" Encoder """
s1 = effNetB7.get_layer("input_image").output ## (512 x 512)
s2 = effNetB7.get_layer("block1a_activation").output ## (256 x 256)
s3 = effNetB7.get_layer("block2a_activation").output ## (128 x 128)
s4 = effNetB7.get_layer("block3a_activation").output ## (64 x 64)
s5 = effNetB7.get_layer("block4a_activation").output ## (32 x 32)
""" Bridge """
b1 = effNetB7.get_layer("block7a_activation").output ## (16 x 16)
""" Decoder """
d1 = decoder_block(b1, s5, 512) ## (32 x 32)
d2 = decoder_block(d1, s4, 256) ## (64 x 64)
d3 = decoder_block(d2, s3, 128) ## (128 x 128)
d4 = decoder_block(d3, s2, 64) ## (256 x 256)
d5 = decoder_block(d4, s1, 32) ## (512 x 512)
""" Output """
outputs = Conv2D(1, 1, padding="same", activation="sigmoid")(d5)
model = Model(inputs, outputs, name="EfficientNetB7_U-Net")
return model
if __name__ == "__main__":
input_shape = (IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)
model = build_efficientNetB7_unet(input_shape)
#Shows the entire EfficientNetB7_UNet Model
model.summary()
#Adding Model Checkpoints, Early Stopping based on Validation Loss and LR Reducer
model_path = "path/Model_Name.h5"
checkpointer = ModelCheckpoint(model_path,
monitor="val_loss",
mode="min",
save_best_only = True,
verbose=1)
earlystopper = EarlyStopping(monitor = 'val_loss',
min_delta = 0,
patience = 30,
verbose = 1,
restore_best_weights = True)
lr_reducer = ReduceLROnPlateau(monitor='val_loss',
factor=0.6,
patience=6,
verbose=1,
min_lr=0.0001
#min_delta=5e-5
)
lr_schedule = keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate=1e-3,
decay_steps=6000,
decay_rate=0.9)
optimizer = keras.optimizers.Adam(learning_rate=lr_schedule)
from tensorflow.keras import backend as K
# To calculate Intersection over Union between Predicted Mask and Ground Truth
def iou_coef(y_true, y_pred, smooth=1):
intersection = K.sum(K.abs(y_true * y_pred), axis=[1,2,3])
union = K.sum(y_true,[1,2,3])+K.sum(y_pred,[1,2,3])-intersection
iou = K.mean((intersection + smooth) / (union + smooth), axis=0)
return iou
smooth = 1e-5
# F1 score or Dice Coefficient
def f1_score(y_true, y_pred, smooth = 1):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
# Soft Dice Loss
def soft_dice_loss(y_true, y_pred):
return 1-dice_coef(y_true, y_pred)
#Compiling the model with Adam Optimizer and Metrics related to segmentation
model.compile(optimizer=optimizer,
loss=soft_dice_loss,
metrics=[iou_coef, Recall(), Precision(), MeanIoU(num_classes=2), f1_score])
# Initiate Model Training
history = model.fit(train_images,
train_masks/255,
validation_split=0.10,
epochs=EPOCHS,
batch_size = BATCH_SIZE,
callbacks = [checkpointer, earlystopper, lr_reducer])
```
| github_jupyter |
Starting with our mystery fasta file containing an unknown, interesting sequences we found in our studies, let's use Biopython's http BLAST methods to retrieve a BLAST query result. We can save the result to an XML file the default output method of the BLAST search.
```
from Bio.Blast import NCBIWWW
fasta_string = open("testFile.fasta").read()
result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)
with open("blast_output.xml", "w") as output_xml:
output_xml.write(result_handle.read())
result_handle.close()
```
Now that the result is saved to file, we do not need to re-run this cell, and thus avoid having to re-run the BLAST query. With the query result saved to file, we can load the result into a BLAST record object (a type of [python class](https://docs.python.org/3/tutorial/classes.html)) and use Biopython's NCBIXML to return the BLAST record object. The BLAST record object essentially contains all the information you might need in a BLAST record. You can view the raw [BLAST record code](http://biopython.org/DIST/docs/api/Bio.Blast.Record-module.html) to see what data are stored in the object. We can view the alignments, alignment scores, expectation values, and other parameters that are stored in the hsps objects within the BLAST record class. Because there are typically many alignments for each hit from BLAST, we will just examine the alignments from our top hit.
```
result_handle = open("blast_output.xml")
from Bio.Blast import NCBIXML
blast_records = NCBIXML.read(result_handle)
for alignment in blast_records.alignments:
for hsp in alignment.hsps:
print(hsp)
```
Let's now look at what the top 10 hits we get from NCBI's Nucleotide (nt) database. We will view the decriptions.
```
result_handle = open("blast_output.xml")
blast_records = NCBIXML.read(result_handle)
counter = 0
for description in blast_records.descriptions:
print(description)
counter += 1
if counter == 10:
break
```
Our top hit is a mRNA transcript record from an organism named Drosophila yakuba. While outside the scope of this tutorial, one could get more information on this record is by using efetch from the nucleotide database of NCBI via Biopython's Entrez module, as shown below. [EFetch](https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EFetch) is part of [NCBI's E-Utilities Suite](https://www.ncbi.nlm.nih.gov/books/NBK25497/), which provides programmatic access to records and information from NCBI's Entrez databases.
```
from Bio import Entrez
Entrez.email = "anon@example.com" # Always tell NCBI who you are
top_hit_record = Entrez.efetch(db="nucleotide", id="969472224", rettype="gb", retmode="text")
print(top_hit_record.read())
```
Returning to our BLAST query, let's explore a little further different parameters for BLAST. We can first print out the parameters for the qblast function using inspect.signature(function_name). One could also print the more verbose help(function_name).
```
import inspect
print(inspect.signature(NCBIWWW.qblast))
```
There are many parameters for this function. Many of them need not be adjusted in most cases. For simplicity, let's focus on the four parameters below. First, we create a python dictionary for a few different parameters we would like to adjust to ultimately compare outputs. We can start by adjusting the program we want to query against. The allowed values are blastn, blastp, blastx, tblastn, or tblastx. We will store the output of each blast XML separately should we choose to access the data at a later point. As we loop through each blast query for the different programs, we will store the number of hits we get from each query via the parameter object of the BLAST record class.
```
blast_params = {'program': 'blastn', 'database': 'nt', 'sequence': fasta_string, 'expect': 10.0}
blast_params['database'] = ['refseq_representative_genomes', 'RefSeq_Gene']
number_hits = []
databases = []
for database in blast_params['database']:
result = NCBIWWW.qblast(blast_params['program'], database, blast_params['sequence'], expect=blast_params['expect'])
file_name = "blast_output_" + database + ".xml"
with open(file_name, "w") as output_xml:
output_xml.write(result.read())
result.close()
result_input = open(file_name)
blast_record = NCBIXML.read(result_input)
counter = 0
for description in blast_record.descriptions:
print('From the ' + database + ' database, the top hit is:\n')
print(description)
counter += 1
if counter == 1:
break
databases.append(database)
print(number_hits)
```
We can use the values we stored from the above searches to plot a very simple barchart of the number of hits from each database, using a common plotting tool in python, [matplotlib](https://matplotlib.org/)
```
import matplotlib.pyplot as plt
plt.rcdefaults()
import matplotlib.pyplot as plt
plt.rcdefaults()
fig, ax = plt.subplots()
number_hits = [5, 10, 15]
# Example data
y_pos = [0, 1, 2]
ax.barh(y_pos, number_hits, align='center', color='blue')
ax.set_yticks(y_pos)
ax.set_yticklabels(databases)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('# BLAST Hits')
ax.set_title('BLAST database vs # Hits')
plt.show()
# here conclude that the top chromosomal hit is AExxxxx, and this is necessary because you don't know how many genes are available
# in notebook 2, we will explore how to dive deeper into the genes that might be present in our unknown sequence based on
result_handle = open("blast_output.xml")
blast_records = NCBIXML.read(result_handle)
start_stops = []
for description in blast_records.descriptions:
if description.title.find('AEsssss'):
for alignment in blast_records.alignments:
for hsp in alignment.hsps:
start_stops.append((hsp.sbjct_start, hsp.sbjct_stop))
```
| github_jupyter |
# Document retrieval from wikipedia data
## Fire up GraphLab Create
(See [Getting Started with SFrames](../Week%201/Getting%20Started%20with%20SFrames.ipynb) for setup instructions)
```
import graphlab
# Limit number of worker processes. This preserves system memory, which prevents hosted notebooks from crashing.
graphlab.set_runtime_config('GRAPHLAB_DEFAULT_NUM_PYLAMBDA_WORKERS', 4)
```
# Load some text data - from wikipedia, pages on people
```
people = graphlab.SFrame('people_wiki.gl/')
```
Data contains: link to wikipedia article, name of person, text of article.
```
people.head()
len(people)
```
# Explore the dataset and checkout the text it contains
## Exploring the entry for president Obama
```
obama = people[people['name'] == 'Barack Obama']
obama
obama['text']
```
## Exploring the entry for actor George Clooney
```
clooney = people[people['name'] == 'George Clooney']
clooney['text']
```
# Get the word counts for Obama article
```
obama['word_count'] = graphlab.text_analytics.count_words(obama['text'])
print obama['word_count']
```
## Sort the word counts for the Obama article
### Turning dictonary of word counts into a table
```
obama_word_count_table = obama[['word_count']].stack('word_count', new_column_name = ['word','count'])
```
### Sorting the word counts to show most common words at the top
```
obama_word_count_table.head()
obama_word_count_table.sort('count',ascending=False)
```
Most common words include uninformative words like "the", "in", "and",...
# Compute TF-IDF for the corpus
To give more weight to informative words, we weigh them by their TF-IDF scores.
```
people['word_count'] = graphlab.text_analytics.count_words(people['text'])
people.head()
tfidf = graphlab.text_analytics.tf_idf(people['word_count'])
# Earlier versions of GraphLab Create returned an SFrame rather than a single SArray
# This notebook was created using Graphlab Create version 1.7.1
if graphlab.version <= '1.6.1':
tfidf = tfidf['docs']
people['tfidf'] = tfidf
```
## Examine the TF-IDF for the Obama article
```
obama = people[people['name'] == 'Barack Obama']
obama[['tfidf']].stack('tfidf',new_column_name=['word','tfidf']).sort('tfidf',ascending=False)
```
Words with highest TF-IDF are much more informative.
# Manually compute distances between a few people
Let's manually compare the distances between the articles for a few famous people.
```
clinton = people[people['name'] == 'Bill Clinton']
beckham = people[people['name'] == 'David Beckham']
```
## Is Obama closer to Clinton than to Beckham?
We will use cosine distance, which is given by
(1-cosine_similarity)
and find that the article about president Obama is closer to the one about former president Clinton than that of footballer David Beckham.
```
graphlab.distances.cosine(obama['tfidf'][0],clinton['tfidf'][0])
graphlab.distances.cosine(obama['tfidf'][0],beckham['tfidf'][0])
```
# Build a nearest neighbor model for document retrieval
We now create a nearest-neighbors model and apply it to document retrieval.
```
knn_model = graphlab.nearest_neighbors.create(people,features=['tfidf'],label='name')
```
# Applying the nearest-neighbors model for retrieval
## Who is closest to Obama?
```
knn_model.query(obama)
```
As we can see, president Obama's article is closest to the one about his vice-president Biden, and those of other politicians.
## Other examples of document retrieval
```
swift = people[people['name'] == 'Taylor Swift']
knn_model.query(swift)
jolie = people[people['name'] == 'Angelina Jolie']
knn_model.query(jolie)
arnold = people[people['name'] == 'Arnold Schwarzenegger']
knn_model.query(arnold)
```
## Quizzes
```
people = graphlab.SFrame('people_wiki.gl/')
```
### 1. Top word count words for Elton John
```
elton_john = people[people['name'] == 'Elton John']
elton_john.head()
elton_john['word_count'] = graphlab.text_analytics.count_words(elton_john['text'])
elton_john.head()
elton_john_word_count_table = elton_john[['word_count']].stack('word_count', new_column_name = ['word','count'])
elton_john_word_count_table.head()
elton_john_word_count_table = elton_john_word_count_table.sort('count',ascending=False)
elton_john_word_count_table
elton_john_word_count_table[0:3]
```
### 2.Top TF-IDF words for Elton John
```
people['word_count'] = graphlab.text_analytics.count_words(people['text'])
tfidf = graphlab.text_analytics.tf_idf(people['word_count'])
# Earlier versions of GraphLab Create returned an SFrame rather than a single SArray
# This notebook was created using Graphlab Create version 1.7.1
if graphlab.version <= '1.6.1':
tfidf = tfidf['docs']
people['tfidf'] = tfidf
elton_john = people[people['name'] == 'Elton John']
results = elton_john[['tfidf']].stack('tfidf',new_column_name=['word', 'tfidf']).sort('tfidf',ascending=False)
results
results[0:3]
```
### 3. The cosine distance between 'Elton John's and 'Victoria Beckham's articles (represented with TF-IDF) falls within which range?
```
elton_john = people[people['name'] == 'Elton John']
vic_beck = people[people['name'] == 'Victoria Beckham']
graphlab.distances.cosine(elton_john['tfidf'][0], vic_beck['tfidf'][0])
```
### 4. The cosine distance between 'Elton John's and 'Paul McCartney's articles (represented with TF-IDF) falls within which range?
```
elton_john = people[people['name'] == 'Elton John']
paul_mc_cartney = people[people['name'] == 'Paul McCartney']
graphlab.distances.cosine(elton_john['tfidf'][0], paul_mc_cartney['tfidf'][0])
```
### 5. Who is closer to 'Elton John', 'Victoria Beckham' or 'Paul McCartney'?
- Paul McCartney
- similarity = 1 - cosine distance
### 6. Who is the nearest neighbor to 'Elton John' using raw word counts?
```
people = people['name', 'word_count', 'tfidf']
people.head()
knn_model_wc = graphlab.nearest_neighbors.create(
people,
features=['word_count'],
label='name',
distance='cosine')
elton_john = people[people['name'] == 'Elton John']
knn_model_wc.query(elton_john)
```
### 7. Who is the nearest neighbor to 'Elton John' using TF-IDF?
```
elton_john = people[people['name'] == 'Elton John']
knn_model_tf_idf = graphlab.nearest_neighbors.create(
people,
features=['tfidf'],
label='name',
distance='cosine')
knn_model_tf_idf.query(elton_john)
```
### 8. Who is the nearest neighbor to 'Victoria Beckham' using raw word counts?
```
vic_beck = people[people['name'] == 'Victoria Beckham']
knn_model_wc.query(vic_beck)
```
### 9. Who is the nearest neighbor to 'Victoria Beckham' using TF-IDF?
```
vic_beck = people[people['name'] == 'Victoria Beckham']
knn_model_tf_idf.query(vic_beck)
```
| github_jupyter |
# Pipeline
This notebook is from the official Quantopian Guide on Pipelines. Make sure to visit their documentation for many more great resources!
Many trading algorithms have the following structure:
1. For each asset in a known (large) set, compute N scalar values for the asset based on a trailing window of data.
2. Select a smaller tradeable set of assets based on the values computed in (1).
3. Calculate desired portfolio weights on the set of assets selected in (2).
4. Place orders to move the algorithm’s current portfolio allocations to the desired weights computed in (3).
There are several technical challenges with doing this robustly. These include:
* efficiently querying large sets of assets
* performing computations on large sets of assets
* handling adjustments (splits and dividends)
* asset delistings
Pipeline exists to solve these challenges by providing a uniform API for expressing computations on a diverse collection of datasets.
## Factors
A factor is a function from an asset and a moment in time to a numerical value.
A simple example of a factor is the most recent price of a security. Given a security and a specific point in time, the most recent price is a number. Another example is the 10-day average trading volume of a security. Factors are most commonly used to assign values to securities which can then be used in a number of ways. A factor can be used in each of the following procedures:
* computing target weights
* generating alpha signal
* constructing other, more complex factors
* constructing filters
## Filters
A filter is a function from an asset and a moment in time to a boolean.
An example of a filter is a function indicating whether a security's price is below $10. Given a security and a point in time, this evaluates to either True or False. Filters are most commonly used for describing sets of assets to include or exclude for some particular purpose.
## Classifiers
A classifier is a function from an asset and a moment in time to a categorical output.
More specifically, a classifier produces a string or an int that doesn't represent a numerical value (e.g. an integer label such as a sector code). Classifiers are most commonly used for grouping assets for complex transformations on Factor outputs. An example of a classifier is the exchange on which an asset is currently being traded.
```
from quantopian.pipeline import Pipeline
def make_pipeline():
return Pipeline()
pipe = make_pipeline()
from quantopian.research import run_pipeline
result = run_pipeline(pipe, '2017-01-01', '2017-01-01')
result.head(10)
result.info()
```
# Data
```
from quantopian.pipeline.data.builtin import USEquityPricing
```
## Factors
Remember, Factors take in an asset and a timestamp and return some numerical value.
```
from quantopian.pipeline.factors import BollingerBands,SimpleMovingAverage,EWMA
SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30)
def make_pipeline():
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30)
return Pipeline(columns = {
'30 Day Mean Close':mean_close_30
})
results = run_pipeline(make_pipeline(),
'2017-01-01',
'2017-01-01')
results.head(20)
def make_pipeline():
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30)
latest_close = USEquityPricing.close.latest
return Pipeline(columns = {
'30 Day Mean Close':mean_close_30,
'Latest Close':latest_close
})
results = run_pipeline(make_pipeline(),
'2017-01-01',
'2017-01-01')
results.head(10)
```
## Combining Factors
```
def make_pipeline():
mean_close_10 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 10)
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30)
latest_close = USEquityPricing.close.latest
percent_difference = (mean_close_10-mean_close_30) / mean_close_30
return Pipeline(columns = {
'Percent Difference':percent_difference,
'30 Day Mean Close':mean_close_30,
'Latest Close':latest_close
})
results = run_pipeline(make_pipeline(),
'2017-01-01',
'2017-01-01')
results.head()
```
# Filters and Screens
Filters take in an asset and a timestamp and return a boolean
```
last_close_price = USEquityPricing.close.latest
close_price_filter = last_close_price > 20
close_price_filter
def make_pipeline():
mean_close_10 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 10)
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30)
latest_close = USEquityPricing.close.latest
percent_difference = (mean_close_10-mean_close_30) / mean_close_30
perc_diff_check = percent_difference > 0
return Pipeline(columns = {
'Percent Difference':percent_difference,
'30 Day Mean Close':mean_close_30,
'Latest Close':latest_close,
'Positive Percent Diff': perc_diff_check
})
results = run_pipeline(make_pipeline(),
'2017-01-01',
'2017-01-01')
results.head()
```
## Screens
```
def make_pipeline():
mean_close_10 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 10)
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30)
latest_close = USEquityPricing.close.latest
percent_difference = (mean_close_10-mean_close_30) / mean_close_30
perc_diff_check = percent_difference > 0
return Pipeline(columns = {
'Percent Difference':percent_difference,
'30 Day Mean Close':mean_close_30,
'Latest Close':latest_close,
'Positive Percent Diff': perc_diff_check},
screen=perc_diff_check)
results = run_pipeline(make_pipeline(),
'2017-01-01',
'2017-01-01')
results.head()
```
### Reverse a screen
```
def make_pipeline():
mean_close_10 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 10)
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30)
latest_close = USEquityPricing.close.latest
percent_difference = (mean_close_10-mean_close_30) / mean_close_30
perc_diff_check = percent_difference > 0
return Pipeline(columns = {
'Percent Difference':percent_difference,
'30 Day Mean Close':mean_close_30,
'Latest Close':latest_close,
'Positive Percent Diff': perc_diff_check},
screen = ~perc_diff_check)
results = run_pipeline(make_pipeline(),
'2017-01-01',
'2017-01-01')
results.head()
```
## Combine Filters
```
def make_pipeline():
mean_close_10 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 10)
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30)
latest_close = USEquityPricing.close.latest
percent_difference = (mean_close_10-mean_close_30) / mean_close_30
perc_diff_check = percent_difference > 0
small_price = latest_close < 5
final_filter = perc_diff_check & small_price
return Pipeline(columns = {
'Percent Difference':percent_difference,
'30 Day Mean Close':mean_close_30,
'Latest Close':latest_close,
'Positive Percent Diff': perc_diff_check},
screen = final_filter)
results = run_pipeline(make_pipeline(),
'2017-01-01',
'2017-01-01')
results.head()
```
# Masking
Sometimes we want to ignore certain assets when computing pipeline expresssions. There are two common cases where ignoring assets is useful:
* We want to compute an expression that's computationally expensive, and we know we only care about results for certain assets.
* We want to compute an expression that performs comparisons between assets, but we only want those comparisons to be performed against a subset of all assets.
```
def make_pipeline():
# Create Filters for Masks First
latest_close = USEquityPricing.close.latest
small_price = latest_close < 5
# Pass in the mask
mean_close_10 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 10,
mask = small_price)
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30,
mask = small_price)
percent_difference = (mean_close_10-mean_close_30) / mean_close_30
perc_diff_check = percent_difference > 0
final_filter = perc_diff_check
return Pipeline(columns = {
'Percent Difference':percent_difference,
'30 Day Mean Close':mean_close_30,
'Latest Close':latest_close,
'Positive Percent Diff': perc_diff_check},
screen = final_filter)
results = run_pipeline(make_pipeline(),
'2017-01-01',
'2017-01-01')
results.head()
len(results)
```
# Classifiers
A classifier is a function from an asset and a moment in time to a categorical output such as a string or integer label.
```
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.classifiers.morningstar import Sector
morningstar_sector = Sector()
exchange = morningstar.share_class_reference.exchange_id.latest
exchange
```
### Classifier Methods
* eq (equals)
* isnull
* startswith
```
nyse_filter = exchange.eq('NYS')
def make_pipeline():
# Create Filters for Masks First
latest_close = USEquityPricing.close.latest
small_price = latest_close < 5
# Classifier
nyse_filter = exchange.eq('NYS')
# Pass in the mask
mean_close_10 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 10,
mask = small_price)
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],
window_length = 30,
mask = small_price)
percent_difference = (mean_close_10-mean_close_30) / mean_close_30
perc_diff_check = percent_difference > 0
final_filter = perc_diff_check & nyse_filter
return Pipeline(columns = {
'Percent Difference':percent_difference,
'30 Day Mean Close':mean_close_30,
'Latest Close':latest_close,
'Positive Percent Diff': perc_diff_check},
screen=final_filter)
results = run_pipeline(make_pipeline(),
'2017-01-01',
'2017-01-01')
results.head()
len(results)
```
# Pipelines in Quantopian IDE
```
from quantopian.pipeline import Pipeline
from quantopian.algorithm import attach_pipeline, pipeline_output
def initialize(context):
my_pipe = make_pipeline()
attach_pipeline(my_pipe, 'my_pipeline')
def make_pipeline():
return Pipeline()
def before_trading_start(context, data):
# Store our pipeline output DataFrame in context.
context.output = pipeline_output('my_pipeline')
```
| github_jupyter |
```
NAME = "Robina Shaheen"
DATE = "06172020"
COLLABORATORS = ""
```
# Scikit-learn
Scikit-learn is a simple and efficient tools for predictive data analysis.
It is designed for machine learning in python and built on NumPy, SciPy, and matplotlib.
In this notebook I have employed Scikkit-learn to understand relationship between ozone and its precursors.
Ozone formation depends on the presence of oxide of nitrogen, carbon monoxide and volatile organic compounds.
However, VOC's are not measured at all the stations and few stations have values measured for half of the year.
These msissing values cannot be predicted or filled due to spatial variability of its sources.
```
# Import packages/ modules
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import earthpy as et
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
import seaborn as sns
import datetime
from textwrap import wrap
from statsmodels.formula.api import ols
# Handle date time conversions between pandas and matplotlib
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
# Scikit learn to train model and make predictions.
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
# Use white grid plot background from seaborn
sns.set(font_scale=1.5, style="whitegrid")
%matplotlib inline
# Conditional statement to check and set working directory.
ea_path = os.path.join(et.io.HOME, 'earth-analytics')
if os.path.exists(ea_path):
os.chdir(ea_path)
print("working directory is set to earth-analytics")
else:
print("This path does not exist")
# Set base path to download data
base_path = os.path.join(ea_path, "data")
base_path
file_path21 = os.path.join(base_path,"output_figures","sandiego_2014_fires", "air_quality_csv",
"sd_chemical_composition_2014_mean_v02.csv")
# To check if path is created
os.path.exists(file_path21)
sd_atm_df = pd.read_csv(file_path21, parse_dates=['Date Local'],
index_col=['Date Local'])
sd_atm_df.head(2)
sd_atm_df.columns
sd_atm_df.shape
sd_atm_df.describe()
sd_atm_df.plot(x='NO2 (ppb)', y='CO (ppb)', style='o', c='b')
plt.title('Figure 1. NO2 vs CO')
plt.xlabel('NO2 (ppb)')
plt.ylabel('CO (ppb)')
plt.show()
plt.figure(figsize=(4,4))
sns.distplot(sd_atm_df['NO2 (ppb)'], color = 'b')
plt.title('Figure 2. Distribution pattern of NO2')
plt.show()
# plt.tight_layout()
plt.figure(figsize=(4,4))
sns.distplot(sd_atm_df['CO (ppb)'], color = 'red')
plt.title('Figure 3. Distribution pattern of CO')
plt.tight_layout()
```
Our next step is to divide the data into “attributes” and “labels”.
Attributes are the independent variables while labels are dependent variables whose values are to be predicted. In our dataset, we only have two columns. We want to predict the MaxTemp depending upon the MinTemp recorded. Therefore our attribute set will consist of the “MinTemp” column which is stored in the X variable, and the label will be the “MaxTemp” column which is stored in y variable.
```
X = sd_atm_df['NO2 (ppb)'].values.reshape(-1,1)
y = sd_atm_df['CO_ppm'].values.reshape(-1,1)
```
Next, we split 80% of the data to the training set while 20% of the data to test set using below code.
The test_size variable is where we actually specify the proportion of the test set.
```
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
After splitting the data into training and testing sets, finally, the time is to train our algorithm.
For that, we need to import LinearRegression class, instantiate it,
and call the fit() method along with our training data.
As we have discussed that the linear regression model basically finds the best value for the intercept and slope, which results in a line that best fits the data. To see the value of the intercept and slope calculated by the linear regression algorithm for our dataset, execute the following code.
```
regressor = LinearRegression()
regressor.fit(X_train, y_train) #training the algorithm
#To retrieve the intercept:
print(regressor.intercept_)
#For retrieving the slope:
print(regressor.coef_)
```
This means that for every one unit of change in NO2_mean, the change in the CO is about 0.029%.
Now that we have trained our algorithm, it’s time to make some predictions. To do so, we will use our test data and see how accurately our algorithm predicts the percentage score. To make predictions on the test data, execute the following script:
```
y_pred = regressor.predict(X_test)
```
Now compare the actual output values for X_test with the predicted values, execute the following script:
```
# Taking 20% data for CO and NO2 only
df = pd.DataFrame({'Actual': y_test.flatten(), 'Predicted': y_pred.flatten()})
df.head()
```
We can also visualize comparison result as a bar graph using the below script :
Note: As the number of records is huge, for representation purpose I’m taking just 15 records.
```
df1 = df.head(15)
df1.plot(kind='bar',figsize=(8,5))
plt.grid(which='major', linestyle='-', linewidth='0.5', color='green')
# plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.title('Figure 4. Predicted and actual values of CO')
plt.show()
```
This model seems to work well as the predicted percentages are within the error limits for the actual ones.
The overall variation was not high as all 10 monitoring station were averaged.
The O3 formation and dissociation is complex process and depends on many parameters and hence changes in these variables will also affect ozone concentration at photochemical equilibrium.
```
# plotting straight line with the test data.
plt.scatter(X_test, y_test, color='gray')
plt.plot(X_test, y_pred, color='red', linewidth=2)
plt.title('Figure 5. linear fit between actual and predicted values of CO')
plt.show()
```
# Statistical Analysis (One Variable)
The straight line in the above graph shows our algorithm is correct.
The final step is to evaluate the performance of the algorithm.
This step is particularly important to compare how well different algorithms perform on a particular dataset. For regression algorithms, three evaluation metrics are commonly used:
1. Mean Absolute Error (MAE) is the mean of the absolute value of the errors. It is calculated as:

2. Mean Squared Error (MSE) is the mean of the squared errors and is calculated as:

3. Root Mean Squared Error (RMSE) is the square root of the mean of the squared errors:

Luckily, we don’t have to perform these calculations manually. The Scikit-Learn library comes with pre-built functions that can be used to find out these values for us.
Let’s find the values for these metrics using our test data.
```
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))
print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred))
print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
```
## Conclusion for Single Variable Analysis
All these values are excellent, indicative of an excellent fit of model.
```
# To check empty columns, False means no empty colums
sd_atm_df.isnull().any()
```
Once the above code is executed, all the columns should give False,
In case for any column you find True result, then remove all the null values from that column using below code.
```
sd_atm_df = sd_atm_df.fillna(method='ffill')
```
Our next step is to divide the data into “attributes” and “labels”.
X variable contains all the attributes/features and y variable contains labels.
```
X = sd_atm_df[[ 'NO2 (ppb)','CO_ppm', 'PM2.5 (ug/m3)']].values
y = sd_atm_df['O3 (ppb)'].values
plt.figure(figsize=(4,4))
plt.title('Figure 5. Distribution pattern of O3')
sns.distplot(sd_atm_df['O3 (ppb)'])
plt.tight_layout()
```
```
sd_atm_df.plot(x='NO2 (ppb)', y='O3 (ppb)', style='o', c='r')
plt.title('Figure 6. O3 vs NO2')
plt.xlabel('NO2 (ppb)')
plt.ylabel('O3 (ppb)')
plt.show()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Training Algorithm
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#To retrieve the intercept:
print(regressor.intercept_)
#For retrieving the slope:
print(regressor.coef_)
y_pred = regressor.predict(X_test)
# print(y_pred)
df2 = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df2.head()
# printing only 20% values
df2 = df2.head(20)
df2.plot(kind='bar',figsize=(10,6))
plt.grid(which='major', linestyle='-', linewidth='0.5', color='green')
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.title('Figure 7. Comparison of actual and predicted values of ozone')
plt.show()
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))
print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred))
print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
```
Mean O3 (ppb) = 30.693
RMSE = 6.51
# Conclusion:
The ozone prediction from model = (6.51/30.69)*100 ~ 20% less than actual value. still reasonable model fit.
Taking wildfire days out will improve the relationship between normal parameters and hence MLR coefficents.
If we separate inland vs coastal, RMSE will reduce significantly.
the O3 fromation depends on temp, pressure and destruction with OH radical, photolysis and collisons with air moleucles. The data for one of the important source of ozone formation VOC is incomplete and it can signficntly brings predicted values in alignment with the observed one.
| github_jupyter |
# MEGI001-2101033 Introduction to Earth System Data
## Task 2.1 - Data Portals Inspection
Created on: Jan 22, 2019 by Ralph Florent <r.florent@jacobs-university.de>
## T2.1
Please inspect some web services listed in the `resource.md` file. Document with screenshot and short description (1 sentence) of how the interface looks like. Please document your impression on the ease of use.
### Web services
Data access can be povided via services that are either used via web interface. Some of them are:
* NASA Giovanni - https://giovanni.gsfc.nasa.gov/giovanni/
* EO Data Service - eodataservice.org
* [NASA ocean motion viewer](http://oceanmotion.org/html/resources/oscar.htm)
* [UNAVCO GPS velocity viewer](https://www.unavco.org/software/visualization/GPS-Velocity-Viewer/GPS-Velocity-Viewer.html)
* [NOAA Climate Indices: Monthly Atmospheric and Ocean Time Series](https://www.esrl.noaa.gov/psd/data/climateindices/)
* [ESA global current portal](https://globcurrent.oceandatalab.com/?date=735652800000×pan=3m%3B6m&products=3857_GlobCurrent_L4_geostrophic_streamline%2C3857_GlobCurrent_L4_geostrophic_nrt_vectorfield%2C3857_GlobCurrent_drogue_15m%2C3857_ODYSSEA_SAF_SST%2C3857_ODYSSEA_MED_SST%2C3857_ODYSSEA_NWE_SST%2C3857_ODYSSEA_SST&extent=-2951577.706399%2C6082935.2252079%2C179282.971726%2C7658149.5038895&opacity=100%2C100%2C100%2C100%2C100%2C100%2C100&stackLevel=120%2C120.01%2C140%2C50%2C50.01%2C50.02%2C10)
* [Copernicus Global Flood Awareness System](http://globalfloods.jrc.ec.europa.eu/)
* [USGS Spectral Library viewer](https://crustal.usgs.gov/speclab/QueryAll07a.php)
* [CU Grace data portal](http://geoid.colorado.edu/grace/dataportal.html)
### NASA Giovanni
The image below shows how to filter/search the data that needs to be accessed. In our case, we search using these criteria:
* Surface Temperature (Nighttime/Descending)
* From 2015-07-31 to 2016-09-22
* Country: Haiti
* Displine: Atmospheric Dynamics
<img src="../assets/img/giovanni-nasa.1@task2.1.png" width=900 align="center">
The results of the filtering allows the plotting of the selected dataset. See image below.
<img src="../assets/img/giovanni-nasa.2@task2.1.png" width=900 align="center">
NOTE: This Data as a Service (DaaS) web service lacks of user support due to lapse in Federal funding. The user interface is not attractive at all, but it contains a lot of options in terms of searching and filtering.
### EO Data Service
The content of the UI consists of a landing page listing the following options: Concept, Applications, Get the Data, Access the Service|Jupyter
<img src="../assets/img/eo-data-svc.1@task2.1.png" width=900 align="center">
Access to Jupyter Hub as authenticated user (rflorent)
<img src="../assets/img/eo-data-svc.3@task2.1.png" width=900 align="center">
### NASA EarthData OpenSearch
The content of the UI guides new user on a tour to facilate nagivation and use of the toolbar.
<img src="../assets/img/nasa-ed-os.1@task2.1.png" width=900 align="center">
Preview of Map of Haiti using the following search:
* Country: Haiti
* DISC: AIRS/Aqua L1B Infrared (IR) geolocated and calibrated radiances V005 (AIRIBRAD) at GES DISC
* Temporal Extent: 2002-08-30 ongoing
* GIBS Imagery Projection Availability: Geographic
See picture below.
<img src="../assets/img/nasa-ed-os.2@task2.1.png" width=900 align="center">
### EU environmental agency data
Accessing the data is quite easy. Once the map selected, we only need to locate the `Download data` section (usually right after the map), then choose the desired file format. Example of file formats are:
* HTML
* CSV
* TSV
* JSON (with/without exhibit)
* XML (with/without schema)
<img src="../assets/img/eu-env-ad.2@task2.1.png" width=900 align="center">
| github_jupyter |
```
# matplotlib plots within notebook
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
from tqdm import tqdm
import os, sys, shutil
import pickle
from l5kit.configs import load_config_data
from l5kit.data import ChunkedDataset, LocalDataManager
from l5kit.dataset import EgoDataset, AgentDataset
from l5kit.rasterization import build_rasterizer
from l5kit.visualization import draw_trajectory, TARGET_POINTS_COLOR, PREDICTED_POINTS_COLOR, REFERENCE_TRAJ_COLOR
from l5kit.geometry import transform_points
import l5kit
print('Using l5kit version: '+l5kit.__version__)
# Custom libs
sys.path.insert(0, './LyftAgent_lib')
from LyftAgent_lib import train_support as lyl_ts
from LyftAgent_lib import topologies as lyl_nn
# Print Code Version
import git
def print_git_info(path, nombre):
repo = git.Repo(path)
print('Using: %s \t branch %s \t commit hash %s'%(nombre, repo.active_branch.name, repo.head.object.hexsha))
changed = [ item.a_path for item in repo.index.diff(None) ]
if len(changed)>0:
print('\t\t WARNING -- modified files:')
print(changed)
print_git_info('.', 'LyftAgent_lib')
import platform
print("python: "+platform.python_version())
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.backend as K
print('Using TensorFlow version: '+tf.__version__)
print('Using Keras version: '+keras.__version__)
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
```
# Training and Model Config
```
# set env variable for data
os.environ["L5KIT_DATA_FOLDER"] = ""
# get config
cfg = load_config_data("./AgentPrediction_config.yaml")
# Fill defaul classes
cfg = lyl_ts.fill_defaults(cfg)
# Epoch to restart training (0 means start over)
restart_epoch = 0
# Set loss functions and coupling list
# During training these are summed and wheighted like: loss_function[0]*loss_couplings[0] + ... + loss_function[n]*loss_couplings[n]
loss_function = [lyl_ts.L_loss_single2mult, lyl_ts.L2_loss]
loss_couplings = [1.0, 1.0]
```
### Process config parameters
```
# Get parameters
model_map_input_shape = (cfg["raster_params"]["raster_size"][0],
cfg["raster_params"]["raster_size"][1])
base_image_arch = cfg["model_params"]["base_image_model"]
base_image_preprocess = cfg["model_params"]["base_image_preprocess"]
num_future_frames = cfg["model_params"]["future_num_frames"]
num_hist_frames = cfg["model_params"]["history_num_frames"]
histEnc_recurrent_unit = cfg["model_params"]["history_encoder_recurrent_unit"]
histEnc_recurrent_unit_num = cfg["model_params"]["history_encoder_recurrent_units_number"]
pathDec_recurrent_unit = cfg["model_params"]["path_generation_decoder_recurrent_unit"]
pathDec_recurrent_unit_num = cfg["model_params"]["path_generation_decoder_recurrent_units_number"]
gen_batch_size = cfg["train_data_loader"]["batch_size"]
gen_lr_list = cfg["training_params"]["gen_lr_list"]
gen_lr_lims = cfg["training_params"]["gen_lr_lims"]
number_of_scenes = cfg["training_params"]["number_of_scenes"]
frames_per_scene = cfg["training_params"]["frames_per_scene"]
randomize_frames = cfg["training_params"]["randomize_frames"]
randomize_scenes = cfg["training_params"]["randomize_scenes"]
epochs_train = cfg["training_params"]["epochs_train"]
teacher_force_list = cfg["training_params"]["teacher_force_list"]
teacher_force_lims = cfg["training_params"]["teacher_force_lims"]
use_teacher_force = cfg["training_params"]["use_teacher_force"]
init_decoder_on_history = cfg["training_params"]["init_decoder_on_history"]
retrain_inputs_image_model = cfg["training_params"]["retrain_inputs_image_model"]
retrain_all_image_model = cfg["training_params"]["retrain_all_image_model"]
future_steps_train_list = cfg["training_params"]["future_steps_train_list"]
future_steps_train_lims = cfg["training_params"]["future_steps_train_lims"]
use_modulate_future_steps = cfg["training_params"]["use_modulate_future_steps"]
model_version = cfg["model_params"]["version"]
use_fading = cfg["model_params"]["use_fading"]
use_angle = cfg["model_params"]["use_angle"]
increment_net = cfg["model_params"]["increment_net"]
mruv_guiding = cfg["model_params"]["mruv_guiding"]
mruv_model_trainable = cfg["model_params"]["mruv_model_trainable"]
# Append flags to output name
loss_names = ['Likelihood', 'MSE']
if mruv_model_trainable:
loss_names.append('mruv_V_Loss')
loss_names.append('mruv_A_Loss')
loss_names.append('mruv_Conf_Loss')
# Set mru_model trainable flag
train_imgModel = retrain_inputs_image_model or retrain_all_image_model
# Checl model version and set forward pass
isBaseModel = False
if model_version == 'Base':
isBaseModel = True
forward_pass_use = lyl_nn.modelBaseline_forward_pass
save_path = './output_Baseline'
elif model_version == 'V1':
forward_pass_use = lyl_nn.modelV1_forward_pass
save_path = './output_V1_likelihood'
elif model_version == 'V2':
forward_pass_use = lyl_nn.modelV2_forward_pass
save_path = './output_V2_noAttn_big_multiLoss_imgRetrain'
if mruv_guiding:
save_path += '_mruvGuided'
if mruv_model_trainable:
save_path += '_mruvModel'
cfg["model_params"]["history_encoder_recurrent_units_number"] = cfg["model_params"]["path_generation_decoder_recurrent_units_number"]
# Get image preprocessing function (depends on image encoding base architecture)
if base_image_preprocess == None:
base_image_preprocess_fcn = lambda x: x
else:
try:
base_image_preprocess_fcn = getattr(keras.applications, base_image_preprocess.split('.')[0])
base_image_preprocess_fcn = getattr(base_image_preprocess_fcn, base_image_preprocess.split('.')[1])
except:
raise Exception('Base image pre-processing not found. Requested function: %s'%base_image_preprocess)
```
# Dataset Loader
### Train Set
```
dm = LocalDataManager()
dataset_path = dm.require(cfg["train_data_loader"]["key"])
zarr_dataset = ChunkedDataset(dataset_path)
zarr_dataset.open(cached=False)
print(zarr_dataset)
rast = build_rasterizer(cfg, dm)
train_dataset = AgentDataset(cfg, zarr_dataset, rast, min_frame_future = 10)
number_of_scenes = len(train_dataset.dataset.scenes)
tf_train_dataset = lyl_ts.get_tf_dataset(train_dataset,
num_hist_frames,
model_map_input_shape,
num_future_frames,
randomize_frame=randomize_frames,
randomize_scene=randomize_scenes,
num_scenes=number_of_scenes,
frames_per_scene = frames_per_scene)
# Map sample pre-processing function
tf_train_dataset = tf_train_dataset.map(lambda x: lyl_ts.tf_get_input_sample(x,
image_preprocess_fcn=base_image_preprocess_fcn,
use_fading = use_fading,
use_angle = use_angle))
# Set batch size
tf_train_dataset = tf_train_dataset.batch(batch_size=gen_batch_size)
```
### Validation Set
```
dm_val = LocalDataManager()
dataset_path_val = dm_val.require(cfg["val_data_loader"]["key"])
zarr_dataset_val = ChunkedDataset(dataset_path_val)
zarr_dataset_val.open(cached=False)
print(zarr_dataset_val)
rast_val = build_rasterizer(cfg, dm_val)
validation_dataset = AgentDataset(cfg, zarr_dataset_val, rast_val, min_frame_future = 10)
number_of_scenes_val = len(validation_dataset.dataset.scenes)
tf_validation_dataset = lyl_ts.get_tf_dataset(validation_dataset,
num_hist_frames,
model_map_input_shape,
num_future_frames,
randomize_frame=True,
randomize_scene=True,
num_scenes=number_of_scenes_val,
frames_per_scene = frames_per_scene)
# Map sample pre-processing function
tf_validation_dataset = tf_validation_dataset.map(lambda x: lyl_ts.tf_get_input_sample(x, image_preprocess_fcn=base_image_preprocess_fcn,
use_fading = use_fading,
use_angle = use_angle))
# Set batch size
tf_validation_dataset = tf_validation_dataset.batch(batch_size=gen_batch_size)
```
# Build Models
```
if restart_epoch>0:
# Pick up from previous step
model_list = lyl_ts.load_models(save_path, 'epoch_%d'%(restart_epoch),
load_img_model = (retrain_inputs_image_model or retrain_all_image_model),
isBaseModel = isBaseModel,
mruv_guiding = mruv_guiding,
mruv_model_trainable = mruv_model_trainable)
ImageEncModel = model_list[0]
HistEncModel = model_list[1]
PathDecModel = model_list[2]
mruv_model = model_list[3]
else:
# ---------------------- IMAGE ENCODER --------------------------
# Load pretrained image processing model
try:
base_model_builder = getattr(keras.applications, base_image_arch)
except:
raise Exception('Base image processing model not found. Reuquested model: %s'%base_image_arch)
base_img_model = base_model_builder(include_top=False, weights='imagenet')
ImageEncModel = lyl_nn.imageEncodingModel(base_img_model, cfg)
# ---------------------- PATH HISTORY ENCODER ------------------
if not isBaseModel:
HistEncModel = lyl_nn.pathEncodingModel(cfg)
else:
HistEncModel = None
if mruv_guiding:
if mruv_model_trainable:
mruv_model = lyl_nn.mruvModel(cfg, ImageEncModel)
else:
mruv_model = lyl_ts.get_velocity_and_acceleration
else:
mruv_model = None
# ---------------------- PATH DECODER --------------------------
if model_version == 'Base':
PathDecModel = lyl_nn.pathDecoderModel_Baseline(cfg, ImageEncModel)
elif model_version == 'V1':
PathDecModel = lyl_nn.pathDecoderModel_V1(cfg, ImageEncModel, HistEncModel)
elif model_version == 'V2':
PathDecModel = lyl_nn.pathDecoderModel_V2(cfg, ImageEncModel, HistEncModel)
```
### Show model information
```
ImageEncModel.summary()
tf.keras.utils.plot_model(ImageEncModel, show_shapes=True, show_layer_names=True,
to_file=os.path.join(save_path,'ImageEncModel.png'))
if not isBaseModel:
HistEncModel.summary()
tf.keras.utils.plot_model(HistEncModel, show_shapes=True, show_layer_names=True,
to_file=os.path.join(save_path,'HistEncModel.png'))
if mruv_guiding and mruv_model_trainable:
mruv_model.summary()
tf.keras.utils.plot_model(mruv_model, show_shapes=True, show_layer_names=True,
to_file=os.path.join(save_path,'mruv_model.png'))
PathDecModel.summary()
tf.keras.utils.plot_model(PathDecModel, show_shapes=True, show_layer_names=True,
to_file=os.path.join(save_path,'PathDecModel.png'))
```
# Training
### Setup TensorBoard
```
# Set up TensorBoard
logdir = os.path.join(save_path,'TensorBoard_outs')
if os.path.exists(logdir) and restart_epoch==0:
shutil.rmtree(logdir)
tb_writer = tf.summary.create_file_writer(os.path.join(logdir,'train'), name = 'train')
tb_writer_val = tf.summary.create_file_writer(os.path.join(logdir,'validation'), name = 'validation')
# Its really ugly... but you can get it if you want it...
get_graph = False
```
### Setup optimizer
```
optimizer_gen = keras.optimizers.Adam(lr=1.0, beta_1=0.9, beta_2=0.99, epsilon=1.0e-8)
train_genL2_loss = keras.metrics.Mean(name='train_gen_L2_loss')
# Load optimizer state
if restart_epoch>0:
if os.path.exists(os.path.join(os.path.join(save_path,'OptimizerStates'), 'epoch_%d.npy'%(restart_epoch))):
# Get list of trainable variables
train_vars = ImageEncModel.trainable_variables
if not isBaseModel:
train_vars += HistEncModel.trainable_variables
train_vars += PathDecModel.trainable_variables
if mruv_model_trainable:
train_vars += mruv_model.trainable_variables
lyl_ts.load_optimizer_state(os.path.join(save_path,'OptimizerStates'), 'epoch_%d'%(restart_epoch), optimizer_gen, train_vars)
else:
print('Warning - Optimizer state not loaded, using blank optimizer.')
```
### Train!
```
# ----------------------------- Set initial parameters -------------------------------
teacher_force_base = 1.0
teacher_force = teacher_force_base
if restart_epoch > 0:
epoch_ini = restart_epoch+1
else:
epoch_ini = 1
futureSteps_infer = num_future_frames
h_idx_all = list()
# ------------------------------------------------------------------------------------
# Run for the given number of epochs
for epoch in range(epoch_ini, epochs_train+1):
# Using the "train" TensorBoard file
with tb_writer.as_default():
# Step index for this epoch
idx_gen_train = 0
# Number of steps per epoch to run
steps_per_epoch = int(np.floor(number_of_scenes*frames_per_scene/gen_batch_size))
# Global step index (grows indefinitelly with the epochs)
this_step_num = idx_gen_train+(steps_per_epoch*(epoch-1))
# ----------------------------- Set future steos to train on -------------------------
if use_modulate_future_steps:
# Modulate number of future steps to train on
futureSteps_infer = lyl_ts.get_future_steps_train(future_steps_train_list,
future_steps_train_lims,
epoch,
futureSteps_infer)
with tf.name_scope("Train_params"):
tf.summary.scalar('obj_steps', futureSteps_infer, step=this_step_num)
# ------------------------------------------------------------------------------------
# ----------------------------- Set teacher force value ------------------------------
if not isBaseModel:
if use_teacher_force:
# Modulate teacher force
teacher_force = lyl_ts.get_teacher_force_weight(teacher_force_list,
teacher_force_lims,
epoch,
teacher_force,
linearize=True)
if teacher_force<=0.0:
use_teacher_force = False
print('Teacher force deactivated.')
with tf.name_scope("Train_params"):
tf.summary.scalar('teacher_force', teacher_force, step=this_step_num)
# ------------------------------------------------------------------------------------
# ----------------------------- Set learning rate value ------------------------------
# Update learning rate
this_lr = lyl_ts.update_lr(gen_lr_list, gen_lr_lims, epoch, optimizer_gen)
with tf.name_scope("Train_params"):
tf.summary.scalar('learning_rate', this_lr, step=this_step_num)
# ------------------------------------------------------------------------------------
# Flush stdout to avoid tqdm overlap
sys.stdout.flush()
train_genL2_loss_aux = 0
# List of hard examples
# This is a list ot those examples where the error was 5x larger than mean
h_example_idxs = list()
h_example_loss = list()
h_example_mean = list()
example_log = list()
# Set tqdm progress bar
train_dataset_prog_bar = tqdm(tf_train_dataset, total=steps_per_epoch)
# Iterate over the training dataset once
# (Each complete iteration will shield a different, random, frame set)
for (thisSampleMapComp, thisSampeHistPath, thisSampeTargetPath,
thisHistAvail, thisTargetAvail,
thisTimeStamp, thisTrackID, thisRasterFromAgent, thisWorldFromAgent, thisCentroid,
thisSampleIdx) in train_dataset_prog_bar:
# Update step num
this_step_num = idx_gen_train+(steps_per_epoch*(epoch-1))
# If the batch size of this mini-batch is not the same as the
# expected by the net, the training loop is finished (we loose only a few random frames)
if thisSampleMapComp.shape[0] < gen_batch_size:
break
# If the graph is being recorded, start the tracing
if get_graph:
tf.summary.trace_on(graph=True, profiler=True)
# Run the correct train step depending on the model
if isBaseModel:
step_losses, gradients_out = lyl_ts.generator_train_step_Base(thisSampleMapComp,
thisSampeTargetPath,
thisTargetAvail,
ImageEncModel,
PathDecModel,
optimizer_gen,
train_genL2_loss,
forward_pass_use,
loss_use = loss_function,
gradient_clip_value = 10.0)
else:
PathDecModel.reset_states()
HistEncModel.reset_states()
step_losses, gradients_out = lyl_ts.generator_train_step(thisSampleMapComp,
thisSampeHistPath,
thisSampeTargetPath,
thisHistAvail,
thisTargetAvail,
ImageEncModel,
HistEncModel,
PathDecModel,
optimizer_gen,
train_genL2_loss,
tf.constant(tf.zeros(PathDecModel.inputs[-1].shape)),
forward_pass_use,
loss_use = loss_function,
loss_couplings = loss_couplings,
stepsInfer = futureSteps_infer,
use_teacher_force=use_teacher_force,
teacher_force_weight = tf.constant(teacher_force,
dtype=tf.float32),
gradient_clip_value = 10.0,
stop_gradient_on_prediction = False,
increment_net = increment_net,
mruv_guiding = mruv_guiding,
mruv_model = mruv_model,
mruv_model_trainable = mruv_model_trainable)
# If the graph was recorded, save it and stop the tracing
if get_graph:
tf.summary.trace_export(
name="train_step_trace",
step=0,
profiler_outdir=logdir)
tf.summary.trace_off()
get_graph = False
# Analyze train step output
thisL2 = train_genL2_loss.result()
if np.isnan(thisL2):
raise Exception('Bad potato... step %d'%idx_gen_train)
# -------------------------- Update progress bar --------------------------------------
# Get step compound loss
train_genL2_loss_aux += thisL2
train_genL2_loss.reset_states()
print_gen_L2 = train_genL2_loss_aux/(idx_gen_train+1)
# Update progress bar
msg_string = '(Epoch %d/%d) Gen. Loss: %.2f (last %.2f) '%(epoch,
epochs_train,
print_gen_L2,
thisL2)
if use_teacher_force and not isBaseModel:
msg_string += '(t.f. = %.2f)'%teacher_force
train_dataset_prog_bar.set_description(msg_string)
# ------------------------------------------------------------------------------------
# ------------------------------- Log the hard examples data -------------------------
comp_loss = 0
for step_loss, k in zip(step_losses, loss_couplings):
comp_loss += k*step_loss.numpy()
for thisLoss, thisIDX in zip(comp_loss, thisSampleIdx):
example_log.append(thisIDX)
if (thisLoss > 10.0*print_gen_L2):
h_example_idxs.append(thisIDX)
h_example_loss.append(thisLoss)
h_example_mean.append(print_gen_L2)
# ------------------------------------------------------------------------------------
# ------------------------------ Save info to tensorboard ----------------------------
with tf.name_scope("Loss_metrics"):
for this_name, this_loss in zip(loss_names, step_losses):
tf.summary.scalar(this_name, np.mean(this_loss.numpy()), step=this_step_num)
grad_out_count = 0
if train_imgModel:
with tf.name_scope("Gradient_ImgEncModel"):
for grad, var in zip(gradients_out[grad_out_count], ImageEncModel.trainable_variables):
tf.summary.scalar(var.name+'_norm', np.linalg.norm(var.numpy()), step=this_step_num)
grad_out_count += 1
if not isBaseModel:
with tf.name_scope("Gradient_HistEncModel"):
for grad, var in zip(gradients_out[grad_out_count], HistEncModel.trainable_variables):
tf.summary.scalar(var.name+'_norm', np.linalg.norm(var.numpy()), step=this_step_num)
grad_out_count += 1
with tf.name_scope("Gradient_PathDecModel"):
for grad, var in zip(gradients_out[grad_out_count], PathDecModel.trainable_variables):
tf.summary.scalar(var.name+'_norm', np.linalg.norm(var.numpy()), step=this_step_num)
grad_out_count += 1
if mruv_model_trainable:
with tf.name_scope("Gradient_mruvModel"):
for grad, var in zip(gradients_out[grad_out_count], mruv_model.trainable_variables):
tf.summary.scalar(var.name+'_norm', np.linalg.norm(var.numpy()), step=this_step_num)
grad_out_count += 1
if this_step_num % 100 == 0:
if train_imgModel:
with tf.name_scope("ImageEncodingModel"):
for weights, layer in zip(ImageEncModel.get_weights(), ImageEncModel.trainable_variables):
tf.summary.histogram(layer.name, weights, step=this_step_num)
if not isBaseModel:
with tf.name_scope("HistoryEncodingModel"):
for weights, layer in zip(HistEncModel.get_weights(), HistEncModel.trainable_variables):
tf.summary.histogram(layer.name, weights, step=this_step_num)
with tf.name_scope("PathDecoderModel"):
for weights, layer in zip(PathDecModel.get_weights(), PathDecModel.trainable_variables):
tf.summary.histogram(layer.name, weights, step=this_step_num)
if mruv_model_trainable:
with tf.name_scope("Gradient_mruvModel"):
for weights, layer in zip(mruv_model.get_weights(), mruv_model.trainable_variables):
tf.summary.histogram(layer.name, weights, step=this_step_num)
tb_writer.flush()
# ------------------------------------------------------------------------------------
# Update this epoch train step
idx_gen_train += 1
# --------------------------- Save Models -------------------------------------------
if retrain_inputs_image_model or retrain_all_image_model:
lyl_ts.save_model(ImageEncModel, os.path.join(save_path,'ImageEncModel'), 'epoch_%d'%epoch, use_keras=True)
elif epoch == 1:
lyl_ts.save_model(ImageEncModel, os.path.join(save_path,'ImageEncModel'), 'all_epochs', use_keras=True)
if not isBaseModel:
lyl_ts.save_model(HistEncModel, os.path.join(save_path,'HistEncModel'), 'epoch_%d'%epoch, use_keras=True)
lyl_ts.save_model(PathDecModel, os.path.join(save_path,'PathDecModel'), 'epoch_%d'%epoch, use_keras=True)
if mruv_model_trainable:
lyl_ts.save_model(mruv_model, os.path.join(save_path,'mruvModel'), 'epoch_%d'%epoch, use_keras=True)
lyl_ts.save_optimizer_state(optimizer_gen, os.path.join(save_path,'OptimizerStates'), 'epoch_%d'%epoch)
# ------------------------------------------------------------------------------------
# -------------------------- Save list of hard samples -------------------------------
h_example_idxs = np.array(h_example_idxs)
h_example_loss = np.array(h_example_loss)
h_example_mean = np.array(h_example_mean)
file_out = open(os.path.join(save_path,'epoch_%d_h_idx.txt'%epoch),"w")
for idx, loss, media in zip(h_example_idxs, h_example_loss, h_example_mean):
file_out.write('%d : \t %g (%g)\n'%(idx, loss, media))
file_out.close()
file_out = open(os.path.join(save_path,'epoch_%d_sample_log_idx.txt'%epoch),"w")
for idx in example_log:
file_out.write('%d, '%idx)
file_out.close()
# ------------------------------------------------------------------------------------
# Perform validation using the "validation" TensorBoard file
with tb_writer_val.as_default():
# Validate
if (epoch%10 == 0):
# Once every ten, a full validation step
# (it is not really a complete run, because the dataset is built with a given "frames_per_scene")
out_metrics = lyl_ts.validate_model(tf_validation_dataset,
ImageEncModel, HistEncModel, PathDecModel, forward_pass_use,
increment_net = increment_net,
mruv_guiding = mruv_guiding,
mruv_model = mruv_model,
mruv_model_trainable = mruv_model_trainable,
all_metrics = True, base_model = isBaseModel)
else:
out_metrics = lyl_ts.validate_model(tf_validation_dataset,
ImageEncModel, HistEncModel, PathDecModel, forward_pass_use,
increment_net = increment_net,
mruv_guiding = mruv_guiding,
mruv_model = mruv_model,
mruv_model_trainable = mruv_model_trainable,
all_metrics = True,
steps_validate = 100, stepsInfer = futureSteps_infer, base_model = isBaseModel)
with tf.name_scope("Loss_metrics"):
tf.summary.scalar('MSE', out_metrics[0], step=this_step_num)
tf.summary.scalar('Likelihood', out_metrics[1], step=this_step_num)
tf.summary.scalar('TD(0)', out_metrics[2][0], step=this_step_num)
tf.summary.scalar('TD(10)', out_metrics[2][10], step=this_step_num)
tf.summary.scalar('TD(25)', out_metrics[2][25], step=this_step_num)
tf.summary.scalar('TD(T)', out_metrics[2][-1], step=this_step_num)
tf.summary.scalar('TD(mean)', np.mean(out_metrics[2]), step=this_step_num)
tb_writer_val.flush()
print('')
h_idx_all.append(np.unique(h_example_idxs))
print(np.unique(h_example_idxs).shape[0])
```
# Single sample tests
### Process a validation sample
```
# Take a sample batch
for (valSampleMapComp, valSampeHistPath, valSampeTargetPath,
valHistAvail, valTargetAvail,
valTimeStamp, valTrackID, valRasterFromAgent, valWorldFromAgent, valCentroid, valSampleIdx) in tf_validation_dataset:
break
# Process it
PathDecModel.reset_states()
HistEncModel.reset_states()
valPredPath = forward_pass_use(valSampleMapComp,
valSampeHistPath,
valHistAvail,
50,
ImageEncModel, HistEncModel, PathDecModel,
use_teacher_force=False, target_path=valSampeTargetPath, increment_net = increment_net,
mruv_guiding = mruv_guiding,
mruv_model = mruv_model,
mruv_model_trainable = mruv_model_trainable)
valPredPath = valPredPath.numpy()
valLoss = lyl_ts.L_loss_single2mult(valPredPath, valSampeTargetPath, valTargetAvail)
valLoss = valLoss.numpy()
print('Mean likelihood ot this batch: %0.2f'%np.mean(valLoss))
```
### Plot input, predicted and expected path
```
idx_sample = np.random.randint(gen_batch_size)
num_targets = np.sum(valTargetAvail.numpy(), axis=1)[idx_sample].astype(np.int32)
print('Sample num.: %d (%d target points)'%(valSampleIdx[idx_sample], num_targets))
print('Timestamp: %d \t TrackID %d'%(valTimeStamp[idx_sample], valTrackID[idx_sample]))
HISTORY_TRAJ_COLOR = (0, 255, 0)
plt.figure(dpi=300)
plt.subplot(1,3,1)
img_aux = (np.copy(valSampleMapComp[idx_sample,:,:,:3].numpy()))
img_aux = (((img_aux-np.min(img_aux))/(np.max(img_aux)-np.min(img_aux)))*255.0).astype(np.int32)
draw_trajectory(img_aux,
transform_points(valSampeTargetPath[idx_sample,:num_targets,:2].numpy(),
valRasterFromAgent[idx_sample,:num_targets,:].numpy()),
TARGET_POINTS_COLOR)
draw_trajectory(img_aux,
transform_points(valPredPath[idx_sample,:num_targets,:2],
valRasterFromAgent[idx_sample,:num_targets,:].numpy()),
PREDICTED_POINTS_COLOR)
draw_trajectory(img_aux,
transform_points(valSampeHistPath[idx_sample,:,:2].numpy(),
valRasterFromAgent[idx_sample,:,:].numpy()),
HISTORY_TRAJ_COLOR)
plt.imshow(img_aux, origin='botom')
plt.axis('off')
plt.subplot(1,3,2)
plt.imshow(valSampleMapComp[idx_sample,:,:,3].numpy().astype(np.int32), origin='botom')
plt.axis('off')
plt.subplot(1,3,3)
plt.imshow(valSampleMapComp[idx_sample,:,:,4].numpy().astype(np.int32), origin='botom')
plt.axis('off')
plt.tight_layout()
plt.show()
```
### Error plots
```
plt.figure(dpi = 150)
plt.subplot(1,2,1)
plt.plot(valPredPath[idx_sample,:num_targets,0])
plt.plot(valSampeTargetPath.numpy()[idx_sample,:num_targets,0])
plt.ylabel('X position')
plt.xlabel('steps')
plt.legend(['predicted','ground truth'])
plt.subplot(1,2,2)
plt.plot(valPredPath[idx_sample,:num_targets,1])
plt.plot(valSampeTargetPath.numpy()[idx_sample,:num_targets,1])
plt.ylabel('Y position')
plt.xlabel('steps')
plt.legend(['predicted','ground truth'])
plt.tight_layout()
plt.show()
plt.figure(dpi = 150)
plt.subplot(1,2,1)
plt.plot(valSampeTargetPath.numpy()[idx_sample,:num_targets,0], valPredPath[idx_sample,:num_targets,0], '*-')
plt.plot(valSampeTargetPath[idx_sample,:num_targets,0], valSampeTargetPath[idx_sample,:num_targets,0], '-.')
plt.ylabel('X position predicted')
plt.xlabel('X position ground truth')
plt.subplot(1,2,2)
plt.plot(valSampeTargetPath.numpy()[idx_sample,:num_targets,1], valPredPath[idx_sample,:num_targets,1], '*-')
plt.plot(valSampeTargetPath[idx_sample,:num_targets,1], valSampeTargetPath[idx_sample,:num_targets,1], '-.')
plt.ylabel('Y position predicted')
plt.xlabel('Y position ground truth')
plt.tight_layout()
plt.show()
from importlib import reload
reload(lyl_ts)
reload(lyl_nn)
```
| github_jupyter |
# TASK 1 - LFSR Generator
```
from operator import xor
from functools import reduce
from itertools import islice
def lfsr_generator(poly, state=None):
"""
LFSR Generator. Given a polynomial and an initial state, it generates an infinite stream
of bits.
Args:
poly (List): List of integers representing a polynomial. x^3 + x + 1 = 101
state (List, optional): List of binominals representning the state. Defaults to None.
Returns:
b (List): List of bits (formated as an integer)
"""
# Feedback Polynomial -->
feedbackPolynomial = [i in poly for i in range(max(poly)+1)] # True for values in poly, else False
feedbackPolynomial.reverse()
feedbackPolynomial.pop()
# LFSR State -->
if state is None:
stateList = [True for i in range(max(poly))]
else:
stateList = [i == 1 for i in state] # True for 1s, else False
# AND and XOR operations -->
while True:
b = stateList[0]
andedValues = [stateList[i] and feedbackPolynomial[i] for i in range(len(feedbackPolynomial))]
fb = reduce(xor, andedValues)
stateList.pop(0)
stateList.append(fb)
yield b
lfsr = lfsr_generator([3,1])
# The first 16 digits printed as numbers instead of booleans
for b in islice(lfsr, 16):
print(f'{b:d}', end="")
```
# TASK 2 - LFSR Iterator
```
class LFSR(object):
from operator import xor
from functools import reduce
from itertools import islice
"""
[summary]
"""
def __init__(self, poly, state=None):
"""
[summary]
"""
self.poly = [i in poly for i in range(max(poly) + 1)]
self.poly.reverse()
self.poly.pop()
self.length = max(poly)
if state is None:
self.state = [True for i in range(max(poly))]
else:
self.state = [i == 1 for i in state]
self.output = None # Hmm?
self.feedback = None # Hmm?
def __iter__(self):
return self
def __next__(self):
"""
[summary]
"""
self.output = self.state[0]
andedValues = [self.poly[i] and self.state[i] for i in range(len(self.poly))]
self.feedback = reduce(xor, andedValues)
self.state.pop(0)
self.state.append(self.feedback)
return self.output
def run_steps(self, N=1):
"""
[summary]
Args:
N (int, optional): [description]. Defaults to 1.
"""
list_of_bool = [self.__next__() for i in range(N)]
return list_of_bool
def cycle(self, state=None):
"""
[summary]
Args:
state ([type], optional): [description]. Defaults to None.
"""
oneCycle = (2**self.length)-1
list_of_bool = (self.run_steps(oneCycle))
return list_of_bool
def __str__(self):
return "LFSR:\nPoly: " + str(self.poly) + "\nOne cycle: " + str(self.cycle())
def main():
lfsr = LFSR([3,1])
print(lfsr.__str__())
if __name__ == "__main__":
main()
```
| github_jupyter |
# QC Analysis of CTD Oxygen Data
- from CTD Bottle samples and Winkler Titrations
- Seabird Documentation [weblink](http://www.seabird.com/document/an64-2-sbe-43-dissolved-oxygen-sensor-calibration-and-data-corrections)
## Data Sources
- Seabird .btl files
- Oxy titration values from C.Mordy / E.Weisgarver
- Field notes and metadata
- oxy unit conversions: https://ocean.ices.dk/Tools/UnitConversion.aspx
### Before importing here you must
- build the excel file
(currently these are all combined in an excel file - **TODO**: work from the orignal files)
#### Current Active Cruise - DY1904
**Notes:** No Deep Casts (ignore pressure response)
```
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
source_file = '/Users/bell/ecoraid/2019/CTDcasts/dy1904/working/dy1904.report_btl.xlsx'
dateparser = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_excel(source_file,sheet_name='Comparison',parse_dates=['date_time'],index_col='date_time')
try:
df.dropna(subset=['cast','O2, uM/kg00','O2, uM/kg01','Sbeox0Mm/Kg','Sbeox1Mm/Kg'],inplace=True)
except:
df.dropna(subset=['cast','O2, uM/kg00','O2, uM/kg01','Sbox0Mm/Kg','Sbox1Mm/Kg'],inplace=True)
df.describe()
df = df[df['cast']!='HLY1901_082']
#multiple acceptable column names for oxygen so rename if Sbox is found
if 'Sbox0Mm/Kg' in list(df.columns):
df['Sbeox0Mm/Kg'] = df['Sbox0Mm/Kg']
if 'Sbox1Mm/Kg' in list(df.columns):
df['Sbeox1Mm/Kg'] = df['Sbox1Mm/Kg']
```
## Field Calibration Methods
### Bulk slope offset
Seabird suggests not to evaluate the offset but to evaluate the slope as the drift is in the slope. See below for Seabird Method.
FOCI has historically calculated the bulk offset correction (while not forcing through zero... which we probably should). The bulk method treats low and high concentrations equally, but this is not necessarily the case and SBE suggests not doing an offset for values less than **???**
### Bulk Offset: Bottle-Winkler(Flask) Oxygen
(offset below is SBE Bottle Value - Flask)
```
#Plot Basic Offset for Evaluation
fig, ax = plt.subplots(2,2,'none',figsize=(12, 12))
plt.subplot(221)
plt.plot(df.index,(df['Sbeox0Mm/Kg']-df['O2, uM/kg00']),'b.')
plt.plot(df.index,(df['Sbeox1Mm/Kg']-df['O2, uM/kg01']),'c.')
ax = plt.gca()
xfmt = mdates.DateFormatter('%b\n%d')
ax.xaxis.set_major_formatter(xfmt)
plt.ylabel('offset')
plt.xlabel('Date/Time')
plt.subplot(222)
plt.plot(df['Sal00'],(df['Sbeox0Mm/Kg']-df['O2, uM/kg00']),'b.')
plt.plot(df['Sal11'],(df['Sbeox1Mm/Kg']-df['O2, uM/kg01']),'c.')
plt.ylabel('offset')
plt.xlabel('Salinity')
plt.subplot(223)
plt.plot(df['PrDM'],(df['Sbeox0Mm/Kg']-df['O2, uM/kg00']),'b.')
plt.plot(df['PrDM'],(df['Sbeox1Mm/Kg']-df['O2, uM/kg01']),'c.')
plt.ylabel('offset')
plt.xlabel('Pressure')
plt.subplot(224)
plt.plot(df['T090C'],(df['Sbeox0Mm/Kg']-df['O2, uM/kg00']),'b.')
plt.plot(df['T190C'],(df['Sbeox1Mm/Kg']-df['O2, uM/kg01']),'c.')
plt.ylabel('offset')
plt.xlabel('Temperature')
#offsets as time of day (to evaluate if measurements are biased by obtainer)
fig, ax = plt.subplots(figsize=(9, 4.5))
plt.plot(df.index.hour,(df['Sbeox0Mm/Kg']-df['O2, uM/kg00']),'b.')
plt.plot(df.index.hour,(df['Sbeox1Mm/Kg']-df['O2, uM/kg01']),'c.')
plt.xticks(np.arange(24))
z1 = np.polyfit(x=df['Sbeox0Mm/Kg'].values, y=df['O2, uM/kg00'].values, deg=1)
z2 = np.polyfit(x=df['Sbeox1Mm/Kg'].values, y=df['O2, uM/kg01'].values, deg=1)
p1 = np.poly1d(z1)
p2 = np.poly1d(z2)
df['trendline1'] = p1(df['Sbeox0Mm/Kg'].values)
df['trendline2'] = p2(df['Sbeox1Mm/Kg'].values)
fig, ax = plt.subplots(figsize=(9, 9))
plt.plot(df['Sbeox0Mm/Kg'],df['O2, uM/kg00'],'b.')
plt.plot(df['Sbeox1Mm/Kg'],df['O2, uM/kg01'],'c.')
plt.plot(df['Sbeox0Mm/Kg'],df['trendline1'],'b--',linewidth=0.25)
plt.plot(df['Sbeox1Mm/Kg'],df['trendline2'],'c--',linewidth=0.25)
plt.ylabel('Titrated Oxygens uM/kg')
plt.xlabel('SBE CTD Oxygens uM/kg')
print('Primary: y={0:.3f} x + {1:.2f}'.format(z1[0],z1[1]))
print('Secondary: y={0:.3f} x + {1:.2f}'.format(z2[0],z2[1]))
```
#### Correct for linear fit
```
df['Primary'] = 0.924 * df['Sbeox0Mm/Kg']
df['Secondary'] = 0.975 * df['Sbeox1Mm/Kg']
fig, ax = plt.subplots(2,2,'none',figsize=(12, 12))
plt.subplot(221)
plt.plot(df.index,(df['Primary']-df['O2, uM/kg00']),'b.')
plt.plot(df.index,(df['Secondary']-df['O2, uM/kg01']),'c.')
ax = plt.gca()
xfmt = mdates.DateFormatter('%b\n%d')
ax.xaxis.set_major_formatter(xfmt)
plt.ylabel('offset')
plt.xlabel('Date/Time')
plt.subplot(222)
plt.plot(df['Sal00'],(df['Primary']-df['O2, uM/kg00']),'b.')
plt.plot(df['Sal11'],(df['Secondary']-df['O2, uM/kg01']),'c.')
plt.ylabel('offset')
plt.xlabel('Salinity')
plt.subplot(223)
plt.plot(df['PrDM'],(df['Primary']-df['O2, uM/kg00']),'b.')
plt.plot(df['PrDM'],(df['Secondary']-df['O2, uM/kg01']),'c.')
plt.ylabel('offset')
plt.xlabel('Pressure')
plt.xlim([-10,500])
plt.subplot(224)
plt.plot(df['T090C'],(df['Primary']-df['O2, uM/kg00']),'b.')
plt.plot(df['T190C'],(df['Secondary']-df['O2, uM/kg01']),'c.')
plt.ylabel('offset')
plt.xlabel('Temperature')
```
### Alternatively, Fit through zero
```
x1=df['Sbeox0Mm/Kg'].values
x1=x1[:,np.newaxis]
x2=df['Sbeox1Mm/Kg'].values
x2=x2[:,np.newaxis]
z1 = np.linalg.lstsq(x1, df['O2, uM/kg00'].values)
z2 = np.linalg.lstsq(x2, df['O2, uM/kg01'].values)
df['trendline1'] = z1[0]*(x1)
df['trendline2'] = z2[0]*(x2)
fig, ax = plt.subplots(figsize=(9, 9))
plt.plot(df['Sbeox0Mm/Kg'],df['O2, uM/kg00'],'b.')
plt.plot(df['Sbeox1Mm/Kg'],df['O2, uM/kg01'],'c.')
plt.plot(df['Sbeox0Mm/Kg'],df['trendline1'],'b--',linewidth=0.25)
plt.plot(df['Sbeox1Mm/Kg'],df['trendline2'],'c--',linewidth=0.25)
plt.ylabel('Titrated Oxygens uM/kg')
plt.xlabel('SBE CTD Oxygens uM/kg')
print('Primary: y={0:.3f} x '.format(z1[0][0]))
print('Secondary: y={0:.3f} x '.format(z2[0][0]))
```
**TODO:** Validate Seabird suggested methodology with our original methodology and generate a report like this one for every cruise from hereon
### SBE Offset Slope Correction Method
Found in [Application Note 64-2](https://www.seabird.com/asset-get.download.jsa?code=251034) (2012)
Calculate the ratio between the the Winkler Value and SBE43 Bottle Value (Winkler/SBE43) (making sure units are concistent). This is the slope correction value which can be applied over the cruise in varying ways.
Method 1: Take average of all corrections and apply a bulk correction (this should be similar to the forced zero offset above)
Method 2: Apply linear fit to all corrections over time (for time dependent corrections - eg fouling over time)
Method 3: Apply correction on each cast based on winkler for each cast
Limitations exist for values 2-3ml/L or lower, a Winkler sample may have large variablility (hard to get a good one), correction factors greater than 1.2 may indicate that the sensor needs to be calibrated
```
#Plot Basic Ratio for Evaluation
fig, ax = plt.subplots(2,1,'none',figsize=(12, 12))
plt.subplot(211)
plt.plot(df.index,(df['O2, uM/kg00']/df['Sbeox0Mm/Kg']),'b.')
plt.plot(df.index,(df['O2, uM/kg01']/df['Sbeox1Mm/Kg']),'c.')
ax = plt.gca()
xfmt = mdates.DateFormatter('%b\n%d')
ax.xaxis.set_major_formatter(xfmt)
plt.ylabel('slope-correction')
plt.xlabel('Date/Time')
plt.subplot(212)
plt.plot(df.index,(df['O2, uM/kg00']/df['Sbeox0Mm/Kg']),'b.')
plt.plot(df.index,(df['O2, uM/kg01']/df['Sbeox1Mm/Kg']),'c.')
plt.plot(df.index,np.ones(len(df))*(df['O2, uM/kg00']/df['Sbeox0Mm/Kg']).median(),'b--',linewidth=0.25)
plt.plot(df.index,np.ones(len(df))*(df['O2, uM/kg01']/df['Sbeox1Mm/Kg']).median(),'c--',linewidth=0.25)
ax = plt.gca()
ax.set_ylim([.8,1.3])
xfmt = mdates.DateFormatter('%b\n%d')
ax.xaxis.set_major_formatter(xfmt)
plt.ylabel('slope-correction')
plt.xlabel('Date/Time')
print('Primary Corr Ratio: median:{0:.3f} mean:{1:.3f} '.format((df['O2, uM/kg00']/df['Sbeox0Mm/Kg']).median(), (df['O2, uM/kg00']/df['Sbeox0Mm/Kg']).mean()))
print('Secondary Corr Ratio: median:{0:.3f} mean:{1:.3f} '.format((df['O2, uM/kg01']/df['Sbeox1Mm/Kg']).median(), (df['O2, uM/kg01']/df['Sbeox1Mm/Kg']).mean()))
# or for chosen subperiod and values greater than 500
sub_time=['2017-08-15','2019-11-15']
df_sub = df[df.PrDM < 500]
print('Primary Corr Ratio: median:{0:.3f} mean:{1:.3f} '.format(
(df_sub['O2, uM/kg00'][sub_time[0]:sub_time[1]]/df_sub['Sbeox0Mm/Kg'][sub_time[0]:sub_time[1]]).median(),
(df_sub['O2, uM/kg00'][sub_time[0]:sub_time[1]]/df_sub['Sbeox0Mm/Kg'][sub_time[0]:sub_time[1]]).mean()))
print('Secondary Corr Ratio: median:{0:.3f} mean:{1:.3f} '.format(
(df_sub['O2, uM/kg01'][sub_time[0]:sub_time[1]]/df_sub['Sbeox1Mm/Kg'][sub_time[0]:sub_time[1]]).median(),
(df_sub['O2, uM/kg01'][sub_time[0]:sub_time[1]]/df_sub['Sbeox1Mm/Kg'][sub_time[0]:sub_time[1]]).mean()))
```
### Apply Chosen SBE correction method
Using median ratio for bulk entire period
```
ratio_cor1 = 0.975
ratio_cor2 = 1.025
#Plot Offset Corrected Difference for Evaluation
fig, ax = plt.subplots(2,2,'none',figsize=(12, 12))
plt.subplot(221)
plt.plot(df.index,(df['Sbeox0Mm/Kg']*ratio_cor1-df['O2, uM/kg00']),'b.')
plt.plot(df.index,(df['Sbeox1Mm/Kg']*ratio_cor2-df['O2, uM/kg01']),'c.')
ax = plt.gca()
xfmt = mdates.DateFormatter('%b\n%d')
ax.xaxis.set_major_formatter(xfmt)
plt.ylabel('offset')
plt.xlabel('Date/Time')
plt.subplot(222)
plt.plot(df['Sal00'],(df['Sbeox0Mm/Kg']*ratio_cor1-df['O2, uM/kg00']),'b.')
plt.plot(df['Sal11'],(df['Sbeox1Mm/Kg']*ratio_cor2-df['O2, uM/kg01']),'c.')
plt.ylabel('offset')
plt.xlabel('Salinity')
plt.subplot(223)
plt.plot(df['PrDM'],(df['Sbeox0Mm/Kg']*ratio_cor1-df['O2, uM/kg00']),'b.')
plt.plot(df['PrDM'],(df['Sbeox1Mm/Kg']*ratio_cor2-df['O2, uM/kg01']),'c.')
plt.ylabel('offset')
plt.xlabel('Pressure')
plt.xlim([-10,500])
plt.subplot(224)
plt.plot(df['T090C'],(df['Sbeox0Mm/Kg']*ratio_cor1-df['O2, uM/kg00']),'b.')
plt.plot(df['T190C'],(df['Sbeox1Mm/Kg']*ratio_cor2-df['O2, uM/kg01']),'c.')
plt.ylabel('offset')
plt.xlabel('Temperature')
```
### For deep casts or full profile bottle samples, slope correction should be a function of depth
Using median ratio for bulk entire period
```
df[df['cast']=='ctd052']
cast = 'ctd052'
fig, ax = plt.subplots(1,1,'none',figsize=(6, 12))
plt.subplot(111)
plt.plot((df[df['cast']==cast]['O2, uM/kg00']/df[df['cast']==cast]['Sbeox0Mm/Kg']),df[df['cast']==cast]['PrDM'],'b.')
plt.plot((df[df['cast']==cast]['O2, uM/kg01']/df[df['cast']==cast]['Sbeox1Mm/Kg']),df[df['cast']==cast]['PrDM'],'c.')
ax = plt.gca()
plt.xlabel('slope-correction')
ax.set_xlim([0.95,1.07])
ax.invert_yaxis()
print('Primary Corr Ratio: median:{0:.3f} mean:{1:.3f} '.format(
(df[df['cast']==cast]['O2, uM/kg00']/df[df['cast']==cast]['Sbeox0Mm/Kg']).median(),
(df[df['cast']==cast]['O2, uM/kg00']/df[df['cast']==cast]['Sbeox0Mm/Kg']).mean()))
print('Secondary Corr Ratio: median:{0:.3f} mean:{1:.3f} '.format(
(df[df['cast']==cast]['O2, uM/kg01']/df[df['cast']==cast]['Sbeox1Mm/Kg']).median(),
(df[df['cast']==cast]['O2, uM/kg01']/df[df['cast']==cast]['Sbeox1Mm/Kg']).mean()))
```
| github_jupyter |
# Cleaning and Analysing a Dataset of Used Cars from eBay
In this project, we'll work with a modified dataset of used cars from *eBay Kleinanzeigen*, a classifieds section of the German eBay website.
The dataset was originally scraped and uploaded to [Kaggle](https://www.kaggle.com/orgesleka/used-cars-database/data). A few modifications were made from the original dataset that was uploaded to Kaggle in order to fulfill this project's learning purposes.
In this dataset we'll find the following columns:
* dateCrawled - When this ad was first crawled. All field-values are taken from this date.
* name - Name of the car.
* seller - Whether the seller is private or a dealer.
* offerType - The type of listing
* price - The price on the ad to sell the car.
* abtest - Whether the listing is included in an A/B test.
* vehicleType - The vehicle Type.
* yearOfRegistration - The year in which the car was first registered.
* gearbox - The transmission type.
* powerPS - The power of the car in PS.
* model - The car model name.
* kilometer - How many kilometers the car has driven.
* monthOfRegistration - The month in which the car was first registered.
* fuelType - What type of fuel the car uses.
* brand - The brand of the car.
* notRepairedDamage - If the car has a damage which is not yet repaired.
* dateCreated - The date on which the eBay listing was created.
* nrOfPictures - The number of pictures in the ad.
* postalCode - The postal code for the location of the vehicle.
* lastSeenOnline - When the crawler saw this ad last online.
The goal os this project is to clean the data and then perforn somes analysis using the Pandas, numPy and matplotlib libraries.
**Disclaimer: This is guided project from the DataQuest's "Pandas and NumPy Fundamentals" course developed by learning purposes. Although it may look like other projects made for the same reason, this project has some features of its own that were implemented by me, such as the use of charts, for example. Every line in this project was though of and typed by me.**
Let's begin by importing the libraries we'll use.
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
And then we'll take advantage of the `pandas.read_csv` function to read the `.csv` file into a DataFrame.
```
autos = pd.read_csv('autos.csv', encoding='Latin-1')
```
We'll now do some quick exploring through the dataset.
```
autos.info()
autos.head()
```
As we can see, only five columns have null data, which is good. Also, five columns have the data stored as integers:
* yearOfRegistration;
* powerPS;
* monthOfRegistration;
* nrOfPictures;
* postalCode
We can also notice that some columns contain german words, which is normal since this dataset is from a german website. We'll fix that later in this project.
We'll now change the name of the columns. The column names use [camelcase](https://en.wikipedia.org/wiki/Camel_case) instead of Python's preferred [snakecase](https://en.wikipedia.org/wiki/Snake_case). For that we will use the `DataFrame.columns` attribute.
```
autos.columns
autos.columns = ['date_crawled', 'name', 'seller', 'offer_type', 'price', 'ab_test',
'vehicle_type', 'registration_year', 'gearbox', 'power_ps', 'model',
'odometer', 'registration_month', 'fuel_type', 'brand',
'unrepaired_damage', 'ad_created', 'num_photos', 'postal_code',
'last_seen']
print(autos.columns)
autos.head()
```
As you can see, the columns were renamed. Let's keep exploring the dataset.
```
autos.describe(include='all')
```
Notice that the 'seller', 'offer_type' and 'num_photos' columns have basically one value each. As it does not make sense to have columns like this in the dataset, we'll start the cleaning process by droping those columns.
## Cleaning the data
Before dropping the columns, let's take a closer look into them.
```
print(autos['seller'].value_counts())
print('\n')
print(autos['offer_type'].value_counts())
print('\n')
print(autos["num_photos"].value_counts())
```
Now we can easily see that the 'num_photos' column only has one value and that the 'seller' and 'offer_type' columns only have one row with a differente value from the others.
We'll now drop those columns and use `DataFrame.shape` to check if the columns were actually deleted.
```
print(autos.shape)
autos = autos.drop(['seller', 'offer_type', 'num_photos'], axis=1)
print(autos.shape)
```
Columns deleted.
We'll now fix the problem of the columns with german words stored. First, let's take a look in the distinct values in each one of those columns so we know what words we'll need to translate.
```
print(autos['gearbox'].unique())
print('\n')
print(autos['fuel_type'].unique())
print('\n')
print(autos['unrepaired_damage'].unique())
```
Now that we know all the german words in those columns, we'll create a dictionary for each of the columns containing the german word as key and the corresponding english word as value. Then, we'll use the `pandas.Series.map
` to replace the german words for the english words in the whole dataset.
```
# dictionaries
mapping_dict_gearbox = {
'manuell' : 'manually',
'automatik' : 'automatic'}
mapping_dict_fuel = {
'lpg' : 'lpg',
'benzin' : 'gasoline',
'diesel' : 'diesel',
'cng' : 'cng',
'hybrid' : 'hybrid',
'elektro' : 'elektro',
'andere' : 'other'}
mapping_dict_damage = {
'nein' : 'no',
'ja' : 'yes'
}
# translating
autos['gearbox'] = autos['gearbox'].map(mapping_dict_gearbox)
autos['fuel_type'] = autos['fuel_type'].map(mapping_dict_fuel)
autos['unrepaired_damage'] = autos['unrepaired_damage'].map(mapping_dict_damage)
```
Let's check the result.
```
autos.head()
```
The data was successfully translated, but looking at the 'model' column we can see that its first value is the german word 'andere'. We know from the translating we just did that 'andere' means 'other'. Let's fix this.
As we're now dealing with the 'model' column, we'll assume the 'andere' is the only german word in the column and that the other values are the actual names of the models. Therefore, as we are only translating one word in the entire column, it's easier to use a boolean filtering to update the data than to create a dictionary and then use `pandas.Series.map` again. Let's do it
```
autos.loc[autos['model'] == 'andere', 'model'] = 'other'
autos.head()
```
Moving on, we can see that the 'price' and 'odometer' columns contain numeric data. However, this data is stored as string because of characters such as ',', '$' and 'km'. We'll clean these two columns removing those characters and then transforming the values to integer.
We'll also rename the 'odometer' column to 'odometer_km' so it is clear what the column's values are about.
```
# cleaning 'price' column
autos['price'] = autos['price'].str.replace(',', '')
autos['price'] = autos['price'].str.replace('$', '')
autos['price'] = autos['price'].astype(int)
# cleaning 'odometer' column
autos['odometer'] = autos['odometer'].str.replace(',', '')
autos['odometer'] = autos['odometer'].str.replace('km', '')
autos['odometer'] = autos['odometer'].astype(int)
# renaming the column
autos.rename({'odometer' : 'odometer_km'}, axis=1, inplace=True)
autos.head()
```
Now let's take a closer look in these two colmns, starting with 'odometer_km'.
```
print(autos['odometer_km'].describe())
print(autos['odometer_km'].sort_values(ascending=False).unique())
```
The values in this column seem to have been rounded. The highest value is 150,000 and the lowest is 5,000. All of this seems plausible.
Let's look the 'price' column.
```
print(autos['price'].describe())
```
For the 'price', the lowest value is 0 and highest value is so high that it does not even makes sense.
Let's look for the top 20 highest values and the top 20 lowest values for the column and see if we can come up with something.
```
print(autos['price'].value_counts().sort_index(ascending=False).head(20))
print('\n')
print(autos['price'].value_counts().sort_index(ascending=True).head(20))
```
We now can see the data more clearly. There are values over the dozens of millions and values lower than fifty bucks.
In order to work with more realistic data, we'll exclude rows where the 'price' column is above one million or below one hundred. We'll use `Series.between` for this job.
```
autos = autos[autos['price'].between(100, 1000000)]
autos['price'].describe()
```
Now we have more reasonable values.
We'll now work with dates. There are 5 columns that should represent date values:
* date_crawled
* ad_created
* last_seen
* registration_year
* registration_month
The last two are already stored as integer once they represent only years and months. The first three, however, are stored as string. We'll use the `Pandas.to_datetime` attribute to convert them into datetime objects.
```
autos['date_crawled'] = pd.to_datetime(autos['date_crawled'], format='%Y-%m-%d %H:%M:%S')
autos['ad_created'] = pd.to_datetime(autos['ad_created'], format='%Y-%m-%d %H:%M:%S')
autos['last_seen'] = pd.to_datetime(autos['last_seen'], format='%Y-%m-%d %H:%M:%S')
```
Now we are going to take a closer look in the 'registration_year' column.
```
autos['registration_year'].describe()
```
The minimum value is 1000 and the maximum value is 9999. That does not make sense. Let's look for the top 10 highest and lowest values in this column.
```
print(autos['registration_year'].value_counts().sort_index(ascending=False).head(10))
print('\n')
print(autos['registration_year'].value_counts().sort_index(ascending=True).head(10))
```
There are values representing years long before cars were even invented and values representing years way ahead in the future.
Considering that [cars were invented in the eighteen hundreds](https://en.wikipedia.org/wiki/Car), we'll delete rows where the 'resgistration_year' column represents a year before 1900 or after 2020. We'll again use `Series.between`.
```
autos = autos[autos['registration_year'].between(1900,2020)]
autos['registration_year'].describe()
```
# Analysing the Data
We'll now perform some quick analysis in this dataset.
To start we'll keep working with the 'registration year' column. Let's see the 15 most and least common years in which the cars were registered.
```
print(autos['registration_year'].value_counts(normalize=True).head(15))
print('\n')
print(autos['registration_year'].value_counts(normalize=True).tail(15))
```
The most common years are the late 1900s and early 2000s. Over 12% of these cars were registered either in 2000 or in 2005.
The first half of the 19th Century contains the years with least registrations. This makes perfect sense.
Now let's look at the average price by brand so we can see what are the most expensive and cheapest ones. We'll use `DataFrame.groupby` for this job.
```
autos.groupby('brand').price.mean().sort_values(ascending=False)
```
Porsche is by far the most expensive brand, followed by Land Rover. These two are way ahead of the others.
Daewoo appears as the cheapest brand.
Let's now plot this information in a bar chart so we can visualize the average price difference more easily.
```
autos.groupby('brand').price.mean().plot.bar()
```
We'll now check on the most common brands and the chart will be ploted already.
```
print(autos['brand'].value_counts(normalize=True))
autos['brand'].value_counts(normalize=True).plot.bar()
```
Volkswagen is by far the most common brand in this dataset with more than twice as much cars than the second most common brand, BMW. From the second most common on, the decay is slower.
It is also interesting to notice that the five most common brand are german brands, which makes perfect sense since this dataset comes from a german website.
We'll now find the average price for the most common brands. For that, we will first create a new series containing only the brands that represent more than 5% of total of cars.
```
brand_count = autos['brand'].value_counts(normalize=True)
popular_brands = brand_count[brand_count > 0.05].index
print(popular_brands)
```
Now we'll loop through the most common brands and store the average price for each one in a dicionary. The dictionary's keys are the names of the brands and its values are the average price for that brand.
Then we will use the `display_table()` function to display the dictionary in a more readable way.
```
pop_brand_mean_prices = {}
def display_table(table):
table_display = []
for key in table:
key_tuple = (table[key], key)
table_display.append(key_tuple)
table_sorted = sorted(table_display, reverse=True)
for tuple in table_sorted:
print(tuple[1], ':', tuple[0])
for brands in popular_brands:
brand = autos[autos['brand'] == brands]
mean_price = brand['price'].mean()
pop_brand_mean_prices[brands] = round(mean_price, 2)
display_table(pop_brand_mean_prices)
```
We can see that among the most common brands Audi is the most expensive one and Opel is the least expensive one.
We'll repeat the process to check on the average mileage for the most common brands. We'll again use the `display_table()` function.
```
pop_brand_mean_mileage = {}
for brands in popular_brands:
brand = autos[autos['brand'] == brands]
mean_mileage = brand['odometer_km'].mean()
pop_brand_mean_mileage[brands] = round(mean_mileage, 2)
display_table(pop_brand_mean_mileage)
```
BMW has the highest mileage average while Ford has the lowest.
Now let's aggregate these informations into a new DataFrame so it is easier to visualize and compare the brands.
First we use the Series constructor to convert the dictionaries into Series.
```
s_price = pd.Series(pop_brand_mean_prices)
s_mileage = pd.Series(pop_brand_mean_mileage)
```
Now we'll convert the first serie into a DataFrame and the add the second serie as a column to this new Dataframe that will then be displayed.
```
price_mileage = pd.DataFrame(s_price, columns=['mean_price'])
price_mileage['mean_mileage'] = s_mileage
price_mileage
```
Let's now do some data visualization and plot this DataFrame.
```
price_mileage.plot.bar(subplots=True);
```
We can see that although there is a great variation in the average price between the most common brands, the average mileage is pretty much the same.
We'll now analyse the impact of the mileage in the average price. First, let's see the distinct mileage values once more.
Note that we are using the whole dataset again.
```
autos['odometer_km'].sort_values(ascending=False).unique()
```
As the mileage values are rounded and there are only 13 values, we can use them as the references without the need to split the values into intervals.
We're going to plot a chart with average price per mileage.
```
autos.groupby('odometer_km').price.mean().plot.bar()
```
For some reason the cars with the lowest mileage values are ones with the lowest average price, which is odd.
But aside from that, the lowest the mileage, the highest the average price, which makes perfect sense.
As we approach the end of this project, we will see how much the 'unrepaired_damage' and 'gearbox' columns affect the average price. We'll again use `DataFrame.groupby`.
```
print(round(autos.groupby('unrepaired_damage').price.mean(),2))
autos.groupby('unrepaired_damage').price.mean().plot.bar()
print(round(autos.groupby('gearbox').price.mean(),2))
autos.groupby('gearbox').price.mean().plot.bar()
```
We can see that cars with no damage cost, in average, almost three times more than damaged cars. Also, cars with automatic transmission cost more than twice as much as cars with manual transmissions, in average.
# Conclusion
This project aimed to clean the dataset and then perform some analysis. These objectives are now fulfilled.
I appreciate you reading this all the way to the end. I'm also open to suggestions and ideas for more analysis and projects.
| github_jupyter |
# $$CatBoost\ Object\ Importance\ Tutorial$$
[](https://colab.research.google.com/github/catboost/tutorials/blob/master/model_analysis/object_importance_tutorial.ipynb)
#### In this tutorial we show how you can detect noisy objects in your dataset.
```
import numpy as np
from catboost import CatBoost, Pool, datasets
from sklearn.model_selection import train_test_split
```
#### First, let's load the dataset:
```
train_df, _ = datasets.amazon()
X, y = np.array(train_df.drop(['ACTION'], axis=1)), np.array(train_df.ACTION)
cat_features = np.arange(9) # indices of categorical features
X_train, X_validation, y_train, y_validation = train_test_split(X, y, test_size=0.25, random_state=42)
train_pool = Pool(X_train, y_train, cat_features=cat_features)
validation_pool = Pool(X_validation, y_validation, cat_features=cat_features)
print(train_pool.shape, validation_pool.shape)
```
#### Let's train CatBoost on clear data and take a look at the quality:
```
cb = CatBoost({'iterations': 100, 'verbose': False, 'random_seed': 42})
cb.fit(train_pool);
print(cb.eval_metrics(validation_pool, ['RMSE'])['RMSE'][-1])
```
#### Let's inject random noise into 10% of training labels:
```
np.random.seed(42)
perturbed_idxs = np.random.choice(len(y_train), size=int(len(y_train) * 0.1), replace=False)
y_train_noisy = y_train.copy()
y_train_noisy[perturbed_idxs] = 1 - y_train_noisy[perturbed_idxs]
train_pool_noisy = Pool(X_train, y_train_noisy, cat_features=cat_features)
```
#### And train CatBoost on noisy data and take a look at the quality:
```
cb.fit(train_pool_noisy);
print(cb.eval_metrics(validation_pool, ['RMSE'])['RMSE'][-1])
```
#### Now let's sample random 500 validate objects (because counting object importance on the entire validation dataset can take a long time) and calculate the train objects importance for these validation objects:
```
np.random.seed(42)
test_idx = np.random.choice(np.arange(y_validation.shape[0]), size=500, replace=False)
validation_pool_sampled = Pool(X_validation[test_idx], y_validation[test_idx], cat_features=cat_features)
indices, scores = cb.get_object_importance(
validation_pool_sampled,
train_pool_noisy,
importance_values_sign='Positive' # Positive values means that the optimized metric
# value is increase because of given train objects.
# So here we get the indices of bad train objects.
)
```
#### Finally, in a loop, let's remove noisy objects in batches, retrain the model, and see how the quality on the test dataset improves:
```
def train_and_print_score(train_indices, remove_object_count):
cb.fit(X_train[train_indices], y_train_noisy[train_indices], cat_features=cat_features)
metric_value = cb.eval_metrics(validation_pool, ['RMSE'])['RMSE'][-1]
s = 'RMSE on validation datset when {} harmful objects from train are dropped: {}'
print(s.format(remove_object_count, metric_value))
batch_size = 250
train_indices = np.full(X_train.shape[0], True)
train_and_print_score(train_indices, 0)
for batch_start_index in range(0, 2000, batch_size):
train_indices[indices[batch_start_index:batch_start_index + batch_size]] = False
train_and_print_score(train_indices, batch_start_index + batch_size)
```
#### Therefore, we have the following RMSE values on the validation dataset:
||RMSE on the validation dataset|
|-|-|
|Clear train dataset: | 0.215798485149|
|Noisy train dataset: | 0.259157461226|
|Purified train dataset: | 0.227594310956|
#### $$So\ now\ you\ can\ try\ to\ clear\ the\ train\ dataset\ of\ noisy\ objects\ and\ get\ better\ quality!$$
| github_jupyter |
```
!pip install git+https://github.com/kmadathil/kerala_math.git
```
# The Madhava व्यासे वारिधनिहते Series
The famous Madhava series for circumference relates the circumference and diameter of a circle using the infinite series:
$C = 4d - \frac{4d}{3} + \frac{4d}{7} - \frac{4d}{9} ...$
This is equivalent to
$\frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{7} - \frac{1}{9} ...$
If you are curious about the history of this series, and how this was derived etc., please see this [series of blogposts on this topic](https://blog.madathil.org/2021/04/01/the-logic-behind-%e0%a4%b5%e0%a5%8d%e0%a4%af%e0%a4%be%e0%a4%b8%e0%a5%87-%e0%a4%b5%e0%a4%be%e0%a4%b0%e0%a4%bf%e0%a4%a7%e0%a4%bf%e0%a4%a8%e0%a4%bf%e0%a4%b9%e0%a4%a4%e0%a5%87/)
The kerala_math library can compute this series, with our without correction terms.
## Preliminaries
```
import kerala_math.series as kms
import numpy as np
import pandas as pd
pd.options.display.float_format = '{:,.12f}'.format
```
## Our Target value for $\pi$
```
from math import pi
pi
```
## Convergence without a correction term
Without a correction term, convergence is very slow. Even after a 100 terms, we do not have anything close to usable. However, we note that the error is very close to $\frac{1}{n}$, where $n$ is the number of terms we chose to compute in the series
```
terms = [10, 20, 30, 40, 50, 100]
series_none = pd.DataFrame(dtype=np.float64, index=terms, columns=["Result", "Error"])
for t in terms:
series_none.loc[t, "Result"] = np.float64(kms.vyase(1, t, samskara=None)) # d=1, t terms, no correction factor
series_none.loc[:, "Error"] = pi - series_none.loc[:, "Result"]
series_none
```
## Convergence with first order correction
The first order correction term is $C_p = \frac{4d}{2(p+1)} = \frac{4d}{4n}$ where p is the last denominator, and n is the number of terms, such that $p = 2n-1$
This gives reasonable convergence, but needs a lot of terms. After 100, we're still at 6 significant digits after the decimal point
```
series_one = pd.DataFrame(dtype=np.float64, index=terms, columns=["Result", "Error"])
for t in terms:
series_one.loc[t, "Result"] = np.float64(kms.vyase(1, t, samskara=1)) # d=1, t terms, first order correction factor
series_one.loc[:, "Error"] = pi - series_one.loc[:, "Result"]
series_one
```
## Convergence with second order correction
Second order correction - the type given in the verse यत्सङ्खययात्र हरणे कृते निवृत्ता हृतिस्तु जामितया ... uses a correction term
$C_p = \frac{\frac{p+1}{2}}{(p+1)^2+1}$
Convergence is much better, as can be seen. This is considered the easiest choice for hand calculation.
```
series_two = pd.DataFrame(dtype=np.float64, index=terms, columns=["Result", "Error"])
for t in terms:
series_two.loc[t, "Result"] = np.float64(kms.vyase(1, t, samskara=2)) # d=1, t terms, second order correction factor
series_two.loc[:, "Error"] = pi - series_two.loc[:, "Result"]
series_two
```
## Convergence with third order correction
The third order correction term $C_p = \frac{n^2+1}{4n^3+5n}$ is given separately in Yuktibhasha .
This leads to even quicker convergence, 10 significant decimal digits of accuracy after 30 terms.
```
series_three = pd.DataFrame(dtype=np.float64, index=terms, columns=["Result", "Error"])
for t in terms:
series_three.loc[t, "Result"] = np.float64(kms.vyase(1, t, samskara=3)) # d=1, t terms, third order correction factor
series_three.loc[:, "Error"] = pi - series_three.loc[:, "Result"]
series_three
```
### Summing 28 terms
Summing the Madhava series to 28 terms and adding the third order correction factor is considered to have been used to derive the कटपयादि encoded expression चण्डांशुचन्द्राधमकुम्भिपालैः = 31415926536 for the circumference of a circle of diameter 10000000000, equivalent to $\pi$ to 10 decimal digits of accuracy.
```
cc = np.float64(kms.vyase(1, 28, samskara=3))
cc
```
## Comparing the results so far
zoom into the graph to see the results in further detail
```
%matplotlib notebook
results = pd.concat([series_none["Result"], series_one["Result"], series_two["Result"], series_three["Result"]], axis=1, keys=["none","1st order","2nd order","3rd order"])
results.plot(legend=True)
```
## Alternate Series - Incorporating corrections into the main series
These are alternate series given in Yuktibhasha that are equivalent to using व्यासे वारिधिनिहते with first and second order corrections respectively.
### Alternate series - vyasad
व्यासाद् वारिधिनिहतात् पृथगाप्तं त्र्याद्ययुग्विमूलघनैः
त्रिघ्नव्यासे स्वमृणं क्रमशः कृत्वा परिधिरानेयः ||
This is equivalent to using the first order correction.
$C = 3D + 4D(\frac{1}{3^3-3} - \frac{1}{5^3-5} + \frac{1}{7^3-7} ….)$
We expect the results to be similar to the first order correction - and that can be seen as true.
```
series_onea = pd.DataFrame(dtype=np.float64, index=terms, columns=["Result", "Error"])
for t in terms:
series_onea.loc[t, "Result"] = np.float64(kms.vyasad(1, t)) # vyasad for t terms
series_onea.loc[:, "Error"] = pi - series_onea.loc[:, "Result"]
series_onea
```
### Alternate Series - samapanchahatayoh - Second order
Next, we look at the alternate series with second order correction incorporated,
समपञ्चाहतयो या रुपाद्ययुजां चतुर्घ्नमूलयुताः
ताभिः षोडशगुणितात् पृथगाहृतेषु विषमयुतेः
समफलयुतिमपहाय स्यादिष्टव्याससंभवः परिधिः
Equivalent to
$C = 16D(\frac{1}{1^5+4.1} - \frac{1}{3^5+4.3} + \frac{1}{5^5+4.5} ….)$
Again, the convergence can be seen to be similar to using the original series with the second order correction term.
```
series_twoa = pd.DataFrame(dtype=np.float64, index=terms, columns=["Result", "Error"])
for t in terms:
series_twoa.loc[t, "Result"] = np.float64(kms.samapanchahatayoh(1, t)) # vyasad for t terms
series_twoa.loc[:, "Error"] = pi - series_twoa.loc[:, "Result"]
series_twoa
```
| github_jupyter |
# Figure. Subject Information
```
import copy
import os
import subprocess
import cdpybio as cpb
import matplotlib as mpl
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import ciepy
import cardipspy as cpy
%matplotlib inline
%load_ext rpy2.ipython
dy_name = 'figure_subject_information'
outdir = os.path.join(ciepy.root, 'output', dy_name)
cpy.makedir(outdir)
private_outdir = os.path.join(ciepy.root, 'private_output', dy_name)
cpy.makedir(private_outdir)
```
Each figure should be able to fit on a single 8.5 x 11 inch page. Please do not send figure panels as individual files. We use three standard widths for figures: 1 column, 85 mm; 1.5 column, 114 mm; and 2 column, 174 mm (the full width of the page). Although your figure size may be reduced in the print journal, please keep these widths in mind. For Previews and other three-column formats, these widths are also applicable, though the width of a single column will be 55 mm.
```
fn = os.path.join(ciepy.root, 'output', 'input_data', 'wgs_metadata.tsv')
wgs_meta = pd.read_table(fn, index_col=0, squeeze=True)
fn = os.path.join(ciepy.root, 'output', 'input_data', 'rnaseq_metadata.tsv')
rna_meta = pd.read_table(fn, index_col=0)
rna_meta = rna_meta[rna_meta.in_eqtl]
fn = os.path.join(ciepy.root, 'output', 'input_data', 'subject_metadata.tsv')
subject_meta = pd.read_table(fn, index_col=0)
subject_meta = subject_meta.ix[set(rna_meta.subject_id)]
family_vc = subject_meta.family_id.value_counts()
family_vc = family_vc[family_vc > 1]
eth_vc = subject_meta.ethnicity_group.value_counts().sort_values()
sex_vc = subject_meta.sex.value_counts()
sex_vc.index = pd.Series(['Female', 'Male'], index=['F', 'M'])[sex_vc.index]
sns.set_style('whitegrid')
p = subject_meta.ethnicity_group.value_counts()['European'] / float(subject_meta.shape[0])
print('{:.2f}% of the subjects are European.'.format(p * 100))
n = subject_meta.age.median()
print('Median subject age: {}.'.format(n))
p = sex_vc['Female'] / float(sex_vc.sum())
print('{:.2f}% of subjects are female.'.format(p * 100))
bcolor = (0.29803921568627451, 0.44705882352941179, 0.69019607843137254, 1.0)
fig = plt.figure(figsize=(6.85, 4), dpi=300)
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0, 0])
ax.text(0, 1, 'Figure S1',
size=16, va='top')
ciepy.clean_axis(ax)
ax.set_xticks([])
ax.set_yticks([])
gs.tight_layout(fig, rect=[0, 0.90, 0.5, 1])
# Age
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0, 0])
subject_meta.age.hist(bins=np.arange(5, 95, 5), ax=ax)
for t in ax.get_xticklabels() + ax.get_yticklabels():
t.set_fontsize(8)
ax.set_xlabel('Age (years)', fontsize=8)
ax.set_ylabel('Number of subjects', fontsize=8)
ax.grid(axis='x')
gs.tight_layout(fig, rect=[0, 0.45, 0.4, 0.9])
# Ethnicity
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0, 0])
eth_vc.plot(kind='barh', color=bcolor)
for t in ax.get_xticklabels() + ax.get_yticklabels():
t.set_fontsize(8)
ax.set_ylabel('Ethnicity', fontsize=8)
ax.set_xlabel('Number of subjects', fontsize=8)
ax.grid(axis='y')
gs.tight_layout(fig, rect=[0.4, 0.45, 1, 0.9])
# Family size
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0, 0])
family_vc.plot(kind='bar', color=bcolor)
ax.set_xticks([])
for t in ax.get_xticklabels() + ax.get_yticklabels():
t.set_fontsize(8)
ax.set_xlabel('Family', fontsize=8)
ax.set_ylabel('Number of family members', fontsize=8)
gs.tight_layout(fig, rect=[0.4, 0, 1, 0.45])
# Sex
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0, 0])
sex_vc.plot(kind='barh', color=bcolor)
for t in ax.get_xticklabels() + ax.get_yticklabels():
t.set_fontsize(8)
ax.set_ylabel('Sex', fontsize=8)
ax.set_xlabel('Number of subjects', fontsize=8)
ax.grid(axis='y')
gs.tight_layout(fig, rect=[0, 0, 0.4, 0.45])
t = fig.text(0.005, 0.87, 'A', weight='bold',
size=12)
t = fig.text(0.4, 0.87, 'B', weight='bold',
size=12)
t = fig.text(0.005, 0.45, 'C', weight='bold',
size=12)
t = fig.text(0.4, 0.45, 'D', weight='bold',
size=12)
fig.savefig(os.path.join(outdir, 'subject_info.pdf'))
fig.savefig(os.path.join(outdir, 'subject_info.png'), dpi=300)
fs = 10
bcolor = (0.29803921568627451, 0.44705882352941179, 0.69019607843137254, 1.0)
fig = plt.figure(figsize=(6, 4), dpi=300)
# Age
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0, 0])
subject_meta.age.hist(bins=np.arange(5, 95, 5), ax=ax)
for t in ax.get_xticklabels():
t.set_fontsize(8)
for t in ax.get_yticklabels():
t.set_fontsize(fs)
ax.set_xlabel('Age (years)', fontsize=fs)
ax.set_ylabel('Number of subjects', fontsize=fs)
ax.grid(axis='x')
gs.tight_layout(fig, rect=[0, 0.45, 0.4, 1])
# Ethnicity
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0, 0])
eth_vc.plot(kind='barh', color=bcolor)
ax.set_xticks(ax.get_xticks()[0::2])
for t in ax.get_xticklabels():
t.set_fontsize(8)
for t in ax.get_yticklabels():
t.set_fontsize(fs)
ax.set_ylabel('Ethnicity', fontsize=fs)
ax.set_xlabel('Number of subjects', fontsize=fs)
ax.grid(axis='y')
gs.tight_layout(fig, rect=[0.4, 0.45, 1, 1])
# Family size
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0, 0])
family_vc.plot(kind='bar', color=bcolor)
ax.set_xticks([])
for t in ax.get_xticklabels() + ax.get_yticklabels():
t.set_fontsize(fs)
ax.set_xlabel('Family', fontsize=fs)
ax.set_ylabel('Number of family members', fontsize=fs)
gs.tight_layout(fig, rect=[0.4, 0, 1, 0.5])
# Sex
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0, 0])
sex_vc.plot(kind='barh', color=bcolor)
for t in ax.get_xticklabels():
t.set_fontsize(8)
for t in ax.get_yticklabels():
t.set_fontsize(fs)
ax.set_ylabel('Sex', fontsize=fs)
ax.set_xlabel('Number of subjects', fontsize=fs)
ax.grid(axis='y')
gs.tight_layout(fig, rect=[0, 0, 0.4, 0.5])
fig.savefig(os.path.join(outdir, 'subject_info_presentation.pdf'))
```
| github_jupyter |
# Datafaucet
Datafaucet is a productivity framework for ETL, ML application. Simplifying some of the common activities which are typical in Data pipeline such as project scaffolding, data ingesting, start schema generation, forecasting etc.
Loading the default profile
```
import datafaucet as dfc
# load the metadata
dfc.metadata.load()
```
## Projects Resources
Data binding works with the metadata files. It's a good practice to declare the actual binding in the metadata and avoiding hardcoding the paths in the notebooks and python source files.
Project resources are defined by an alias. For resources sharing the same provider service, it is recommended to define the common metadata configuration in the provider and leave the specific resource detail in the resource metadata.
### Resource metadata
Resource metadata configuration has the same yaml properties as the provider, with the exception of a `provider` property which refers to the correcsponfin provider alias configuration. The bare minimum for a resource metadata is the resource `path` which represent a hierarchical path in a file system or object store. For databases the path can represent either a table or a query.
Resource metadata is assembled using the resource and provider configuration. If the resource alias is not defined, it assumes that the resource is implicitely defined and the alias is actually the path of the resource.
The full metadata configuration of a resource can be inspected with `project.resource(...)`
### Unified resource object
In order to simplify copying data from one format and one provider to another, we define a dictionary/object which can describe various type of resources.
Here below a couple of examples:
#### Local file resource
The following function call, define the same resource metadata
All calls produce the same resource dictionary
```
def mask_rootdir(resource):
d = resource.copy()
if d['service']=='file':
d['url'] = '<project_rootdir>/' + dfc.utils.relpath(d['url'], dfc.rootdir())
return d
def equal(resource, ref):
r = dfc.resources.hash(ref)
s = dfc.resources.hash(mask_rootdir(resource))
return r == s
ref = dfc.yaml.YamlDict(
"""
hash: '0x7161cdea'
url: <project_rootdir>/data/ascombe.csv
service: file
version:
format: csv
host: 127.0.0.1
options:
header: true
inferSchema: true
""")
# via metadata yml resource
src = dfc.Resource('ascombe')
assert equal(src, ref)
# path anf provider in metadata yml
src = dfc.Resource('ascombe.csv', 'localfs')
assert equal(src, ref)
# just local path (relative to project roopath)
src = dfc.Resource('data/ascombe.csv', header=True, inferSchema=True)
assert equal(src, ref)
# absolute path
path = dfc.rootdir() + '/data/ascombe.csv'
src = dfc.Resource(path, header=True, inferSchema=True)
assert equal(src, ref)
# full uri
path = f'file://{dfc.rootdir()}/data/ascombe.csv'
src = dfc.Resource(path, header=True, inferSchema=True)
assert equal(src, ref)
# from resource
src = dfc.Resource(src)
assert equal(src, ref)
mask_rootdir(src)
```
#### HDFS service
The following function call, define a file, e.g parquet in a hdfs filesystem
All calls define the same resource dictionary, default port is 8020, default hdfs version is 3.1.1
```
dfc.Resource('hdfs://test/data.parquet')
```
#### Database table
The following function call, define a table from a database
All calls define the same resource dictionary
```
ref = dfc.yaml.YamlDict(
"""
hash: '0xab5696a2'
url: jdbc:mysql://mysql:3306/sakila
service: mysql
version: 8.0.12
format: jdbc
host: mysql
port: 3306
user: sakila
password: sakila
driver: com.mysql.cj.jdbc.Driver
database: sakila
schema: sakila
table: actor
options: {}
""")
# via metadata yml resource
src = dfc.Resource('actor', 'sakila')
print(src)
assert(src==ref)
# via table and url
src = dfc.Resource('actor', 'jdbc:mysql://sakila:sakila@mysql:3306/sakila')
assert(src==ref)
# via table and url and connection details
src = dfc.Resource('actor', 'jdbc:mysql://mysql/sakila', password='sakila', user='sakila')
assert(src==ref)
# only connection details
src = dfc.Resource(
database='sakila',
table='actor',
host='mysql',
service='mysql',
password='sakila',
user='sakila')
assert(src==ref)
# via db/table and connection details
src = dfc.Resource(
'sakila/actor',
host='mysql',
service='mysql',
password='sakila',
user='sakila')
assert(src==ref)
# from resource
src = dfc.Resource(src)
assert(src==ref)
src
```
#### Database queries
The following function call, will extract the same table as abovem using a query.
Passing a query can be helpfull if you want to join or limit somehow the amount of data extracted. Note that in some cases the enigne is able to push down projections (select) and predicates (where) to the engine, after the database table is loaded, thanks to lazy execution.
```
ref = dfc.yaml.YamlDict(
"""
hash: '0x9b72d98e'
url: jdbc:mysql://mysql:3306/sakila
service: mysql
version: 8.0.12
format: jdbc
host: mysql
port: 3306
user: sakila
password: sakila
driver: com.mysql.cj.jdbc.Driver
database: sakila
schema: sakila
table: ( select * from actor ) as _query
options: {}
""")
# via db/table and connection details
src = dfc.Resource(
'SELECT * FROM actor;',
'sakila',
host='mysql',
service='mysql',
password='sakila',
user='sakila')
assert(src==ref)
```
#### Other service providers
The following function call, define a resource from web, file services and object stores
```
# from various services and protocols
path = 'hdfs:///data/ascombe.csv'
src = dfc.Resource(path, header=True, inferSchema=True)
print(src)
path = 'https://subdomain.example.com:88/data/ascombe.csv'
src = dfc.Resource(path, header=True, inferSchema=True)
print(src)
path = 'http://data.example.org/data/ascombe.csv.gz'
src = dfc.Resource(path, header=True, inferSchema=True)
print(src)
path = 'https://raw.githubusercontent.com/natbusa/dfc-tutorial/master/data/examples/sample.csv'
src = dfc.Resource(path)
print(src)
```
| github_jupyter |
<center>
<h1 style="text-align:center"> Lambda Calculus : Syntax </h1>
<h2 style="text-align:center"> CS3100 Monsoon 2020 </h2>
</center>
## Review
### Last time
* Higher Order Functions
### Today
* Lambda Calculus: Basis of FP!
+ Origin, Syntax, substitution, alpha equivalence
## Computability
<h3> In 1930s </h3>
* What does it mean for the function $f : \mathbb{N} \rightarrow \mathbb{N}$ to be *computable*?
* **Informal definition:** A function is computable if using pencil-and-paper you can compute $f(n)$ for any $n$.
* Three different researchers attempted to formalise *computability*.
## Alan Turning
<img src="images/turing.jpg" style="float:left" width="200">
<div style="float:left;width:75%">
* Defined an idealised computer -- **The Turing Machine** (1935)
* A function is computable if and only if it can be computed by a turning machine
* A programming language is turing complete if:
+ It can map every turing machine to a program.
+ A program can be written to simulate a universal turing machine.
+ It is a superset of a known turning complete language.
</div>
## Alonzo Church
<img src="images/church.jpg" style="float:left" width="200">
<div style="float:left;width:75%">
* Developed the **λ-calculus** as a formal system for mathematical logic (1929 - 1932).
* Postulated that a function is computable (in the intuitive sense) if and only if it can be written as a lambda term (1935).
* Church was Turing's PhD advisor!
* Turing showed that the systems defined by Church and his system were equivalent.
+ **Church-Turing Thesis**
</div>
## Kurt Gödel
<img src="images/godel.jpg" style="float:left" width="200">
<div style="float:left;width:75%">
* Defined the class of **general recursive functions** as the smallest set of functions containing
+ all the constant functions
+ the successor function and
+ closed under certain operations (such as compositions and recursion).
* He postulated that a function is computable (in the intuitive sense) if and only if it is general recursive.
</div>
## Impact of Church-Turing thesis
* The **“Church-Turing Thesis”** is by itself is one of the most important ideas on computer science
+ The impact of Church and Turing’s models goes far beyond the thesis itself.
## Impact of Church-Turing thesis
* Oddly, however, the impact of each has been in almost completely separate communities
+ Turing Machines $\Rightarrow$ Algorithms & Complexity
+ Lambda Calculus $\Rightarrow$ Programming Languages
* Not accidental
+ Turing machines are quite low level $\Rightarrow$ well suited for measuring resources (**efficiency**).
+ Lambda Calculus is quite high level $\Rightarrow$ well suited for abstraction and composition (**structure**).
## Programming Language Expressiveness
* So what language features are needed to express all computable functions?
+ *What's the minimal language that is Turing Complete?*
* Observe that many features that we have seen in this class were syntactic sugar
+ **Multi-argument functions** - simulate using partial application
+ **For loop, while loop** - simulate using recursive functions
+ **Mutable heaps** - simulate using functional maps and pass around.
<center>
<h1 style="text-align:center"> All you need is <strike> Love</strike> <i> Functions.</i> </h1>
</center>
## Lambda Calculus : Syntax
\\[
\begin{array}{rcll}
e & ::= & x & \text{(Variable)} \\
& \mid & \lambda x.e & \text{(Abstraction)} \\
& \mid & e~e & \text{(Application)}
\end{array}
\\]
* This grammar describes ASTs; not for parsing (ambiguous!)
* Lambda expressions also known as lambda **terms**
* $\lambda x.e$ is like `fun x -> e`
<center>
<h2 style="text-align:center"> That's it! Nothing but higher order functions </h2>
</center>
## Why Study Lambda Calculus?
* It is a "core" language
+ Very small but still Turing complete
* But with it can explore general ideas
+ Language features, semantics, proof systems, algorithms, ...
* Plus, higher-order, anonymous functions (aka lambdas) are now very popular!
+ C++ (C++11), PHP (PHP 5.3.0), C# (C# v2.0), Delphi (since 2009), Objective C, Java 8, Swift, Python, Ruby (Procs), ...
+ and functional languages like OCaml, Haskell, F#, ...
## Two Conventions
1. Scope of $\lambda$ extends as far right as possible
+ Subject to scope delimited by parentheses
+ $\lambda x. \lambda y.x~y~$ is the same as $\lambda x.(\lambda y.(x~y))$
2. Function Application is left-associative
+ `x y z` is `(x y) z`
+ Same rule as OCaml
## Lambda calculus interpreter in OCaml
* In Assignment 2, you will be implementing a lambda calculus interpreter in OCaml.
* What is the Abstract Syntax Tree (AST)?
```ocaml
type expr =
| Var of string
| Lam of string * expr
| App of expr * expr
```
## Lambda expressions in OCaml
* $y~$ is `Var "y"`
* $\lambda x.x~$ is `Lam ("x", Var "x")`
* $\lambda x. \lambda y.x ~y~$ is `Lam ("x",(Lam("y",App (Var "x", Var "y"))))`
* $(\lambda x.\lambda y.x ~y) ~(\lambda x.x ~x~)$ is
```ocaml
App
(Lam ("x", Lam ("y",App (Var "x", Var "y"))),
Lam ("x", App (Var "x", Var "x")))
```
```
#use "init.ml";;
parse "y";;
parse "λx.x";;
parse "\\x.\\y.x y";;
parse "(\\x.\\y.x y) (\\x. x x)";;
```
## Quiz 1
$\lambda x.(y ~z)$ and $\lambda x.y ~z$ are equivalent.
1. True
2. False
## Quiz 1
$\lambda x.(y ~z)$ and $\lambda x.y ~z$ are equivalent.
1. True ✅
2. False
## Quiz 2
What is this term’s AST? $\lambda x.x ~x$
1. `App (Lam ("x", Var "x"), Var "x")`
2. `Lam (Var "x", Var "x", Var "x")`
3. `Lam ("x", App (Var "x", Var "x"))`
4. `App (Lam ("x", App ("x", "x")))`
## Quiz 2
What is this term’s AST? $\lambda x.x ~x$
1. `App (Lam ("x", Var "x"), Var "x")`
2. `Lam (Var "x", Var "x", Var "x")`
3. `Lam ("x", App (Var "x", Var "x"))` ✅
4. `App (Lam ("x", App ("x", "x")))`
## Quiz 3
This term is equivalent to which of the following?
$\lambda x.x ~a ~b$
1. $(\lambda x.x) ~(a ~b)$
2. $(((\lambda x.x) ~a) ~b)$
3. $\lambda x.(x ~(a ~b))$
4. $\lambda x.((x ~a) ~b)$
## Quiz 3
This term is equivalent to which of the following?
$\lambda x.x ~a ~b$
1. $(\lambda x.x) ~(a ~b)$
2. $(((\lambda x.x) ~a) ~b)$
3. $\lambda x.(x ~(a ~b))$
4. $(\lambda x.((x ~a) ~b))$ ✅
## Free Variables
In
```ocaml
λx. x y
```
* The first `x` is the binder.
* The second `x` is a **bound** variable.
* The `y` is a **free** variable.
## Free Variables
Let $FV(t)$ denote the free variables in a term $t$.
We can define $FV(t)$ inductively over the definition of terms as follows:
\\[
\begin{array}{rcl}
FV(x) & = & \{x\} \\
FV(\lambda x.t_1) & = & FV(t_1) \setminus \{x\} \\
FV(t_1 ~t_2) & = & FV(t_1) ~\cup~ FV(t_2)
\end{array}
\\]
If $FV(t) = \emptyset$ then we say that $t$ is a **closed** term.
$
\newcommand{\cg}[1]{\color{green}{#1}}
\newcommand{\cr}[1]{\color{red}{#1}}
\newcommand{\cb}[1]{\color{blue}{#1}}
$
## Quiz 4
What are the free variables in the following?
1. $\lambda x.x ~(\lambda y. y)$
2. $x ~y ~z$
3. $\lambda x. (\lambda y. y) ~x ~y$
4. $\lambda x. (\lambda y. x) ~y$
## Quiz 4
What are the free variables in the following?
$
\begin{array}{ll}
1. ~\lambda x.x ~(\lambda y. y) & \{\} \\
2. ~\cr{x ~y ~z} & \{x,y,z\} \\
3. ~\lambda x. (\lambda y. y) ~x ~\cr{y} & \{y\} \\
4. ~\lambda x. (\lambda y. x) ~\cr{y} & \{y\}
\end{array}
$
```
free_variables "\\x.x (\\y. y)";;
free_variables "x y z";;
free_variables "\\x.(\\y. y) x y";;
free_variables "\\x.(\\y.x) y";;
```
# $\alpha$-equivalence
Lambda calculus uses **static scoping** (just like OCaml)
\\[
\lambda \cg{x}. \cg{x} ~(\lambda \cr{x}. \cr{x})
\\]
This is equivalent to:
\\[
\lambda \cg{x}. \cg{x} ~(\lambda \cr{y}. \cr{y})
\\]
* Renaming bound variables consistently preserves meaning
+ This is called as **𝛼-renaming** or **𝛼-conversion**.
* If a term $t_1$ is obtained by 𝛼-renaming another term $t_2$ then $t_1$ and $t_2$ are said to be **𝛼-equivalent**.
## Quiz 5
Which of the following equivalences hold?
1. $\lambda x. x ~(\lambda y. y) ~y =_{\alpha} \lambda y. y ~(\lambda x. x) ~x$
2. $\lambda x. x ~(\lambda y. y) ~y =_{\alpha} \lambda y. y ~(\lambda x. x) ~y$
3. $(\lambda x. x ~(\lambda y. y) ~y) =_{\alpha} \lambda w. w ~(\lambda w. w) ~y$
## Quiz 5
Which of the following equivalences hold?
1. $\lambda x. x ~(\lambda y. y) ~y =_{\alpha} \lambda y. y ~(\lambda x. x) ~x~$ ❌
2. $\lambda x. x ~(\lambda y. y) ~y =_{\alpha} \lambda y. y ~(\lambda x. x) ~y~$ ❌
3. $\lambda x. x ~(\lambda y. y) ~y =_{\alpha} \lambda w. w ~(\lambda w. w) ~y~$ ✅
## Substitution
* In order to formally define $\alpha$-equivalence, we need to define **substitutions**.
* Substitution replaces **free** occurrences of a variable $x$ with a lambda term $N$ in some other term $M$.
+ We write it as $M[N/x]$. (read "N for x in M").
For example,
\\[
(\lambda x.x ~y)[(\lambda z.z)/y] = \lambda x.x ~(\lambda z.z)
\\]
<h4> Substitution is quite subtle. So we will start with our intuitions and see how things break and finally work up to the correct example. <h4>
## Substitution: Take 1
\\[
\begin{array}{rcll}
x[s/x] & = & s \\
y[s/x] & = & y & \text{if } x \neq y\\
(\lambda y.t_1)[s/x] & = & \lambda y.t_1[s/x] \\
(t_1 ~t_2)[s/x] & = & (t_1[s/x]) ~(t_2[s/x])
\end{array}
\\]
This definition works for most examples. For example,
\\[
(\lambda y.x)[(\lambda z.z~w)/x] = \lambda y.\lambda z.z ~w
\\]
## Substitution: Take 1
\\[
\begin{array}{rcll}
x[s/x] & = & s \\
y[s/x] & = & y & \text{if } x \neq y\\
(\lambda y.t_1)[s/x] & = & \lambda y.t_1[s/x] \\
(t_1 ~t_2)[s/x] & = & (t_1[s/x]) ~(t_2[s/x])
\end{array}
\\]
However, it fails if the substitution is on the bound variable:
\\[
(\lambda x.x)[y/x] = \lambda x.y
\\]
The **identity** function has become a **constant** function!
## Substitution: Take 2
\\[
\begin{array}{rcll}
x[s/x] & = & s \\
y[s/x] & = & y & \text{if } x \neq y\\
(\lambda x.t_1)[s/x] & = & \lambda x.t_1\\
(\lambda y.t_1)[s/x] & = & \lambda y.t_1[s/x] & \text{if } x \neq y\\
(t_1 ~t_2)[s/x] & = & (t_1[s/x]) ~(t_2[s/x])
\end{array}
\\]
However, this is not quite right. For example,
\\[
(\lambda x.y)[x/y] = \lambda x.x
\\]
* The **constant** function has become a **identity** function.
* The problem here is that the free $x$ gets **captured** by the binder $x$.
## Substitution: Take 3
Capture-avoiding substitution
\\[
\begin{array}{rcll}
x[s/x] & = & s \\
y[s/x] & = & y & \text{if } x \neq y\\
(\lambda x.t_1)[s/x] & = & \lambda x.t_1\\
(\lambda y.t_1)[s/x] & = & \lambda y.t_1[s/x] & \text{if } x \neq y \text{ and } y \notin FV(s)\\
(t_1 ~t_2)[s/x] & = & (t_1[s/x]) ~(t_2[s/x])
\end{array}
\\]
* Unfortunately, this made substitution a partial function
+ There is no valid rule for $(\lambda x.y)[x/y]$
## Substitution: Take 4
Capture-avoiding substitution + totality
\\[
\begin{array}{rcll}
x[s/x] & = & s \\
y[s/x] & = & y & \text{if } x \neq y\\
(\lambda x.t_1)[s/x] & = & \lambda x.t_1\\
(\lambda y.t_1)[s/x] & = & \lambda y.t_1[s/x] & \text{if } x \neq y \text{ and } y \notin FV(s)\\
(\lambda y.t_1)[s/x] & = & \lambda w.t_1[w/y][s/x] & \text{if } x \neq y \text{ and } y \in FV(s) \text { and } w \text{ is fresh}\\
(t_1 ~t_2)[s/x] & = & (t_1[s/x]) ~(t_2[s/x])
\end{array}
\\]
* A **fresh** binder is different from every other binder in use **(generativity)**.
* In the case above,
\\[
w \text{ is fresh } \equiv w \notin FV(t_1) \cup FV(s) \cup \{x\}
\\]
Now our example works out:
\\[
(\lambda x.y)[x/y] = \lambda w.x
\\]
```
substitute "\\y.x" "x" "\\z.z w"
substitute "\\x.x" "x" "y"
substitute "\\x.y" "y" "x"
```
## $\alpha$-equivalence formally
$=_{\alpha}$ is an equivalence (reflexive, transitive, symmetric) relation such that:
$
\newcommand{\inferrule}[2]{\displaystyle{\frac{#1}{#2}}}
$
\\[
\begin{array}{cc}
\inferrule{}{x =_{\alpha} x} \quad & \quad \inferrule{M =_{\alpha} M' \quad N =_{\alpha} N'}{M ~N =_{\alpha} M' ~N'}
\end{array}
\\]
<br>
\\[
\inferrule{z \notin FV(M) \cup FV(N) \quad M[z/x] =_{\alpha} N[z/y]}{\lambda x.M =_{\alpha} \lambda y.N}
\\]
## Convention
From now on,
* Unless stated otherwise, we identify lambda terms up to α-equivalence.
+ when we speak of lambda terms being **equal**, we mean that they are α-equivalent
<center>
<h1 style="text-align:center"> Fin. </h1>
</center>
| github_jupyter |
# Load dataset
I use the same dataset here as in the exploratory analysis (with the Fourier features).
```
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import lr_scheduler
import torch.optim as optim
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import random
from sklearn.model_selection import train_test_split
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
from sklearn.manifold import MDS
from tqdm.auto import tqdm
from torchsummary import summary
# Fix seed
SEED = 2020
# used by torch:
random.seed(SEED)
torch.manual_seed(SEED)
# used by np/sklearn:
np.random.seed(SEED)
INPUT_SIZE = (2, 128) # (number of channels, number of timepoints)
EMBEDDING_SIZE = 20 # size of the resulting embedding vector
DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
from gaitkeeper.idnet import load_idnet_dataset
from gaitkeeper import preprocess
from gaitkeeper.models import GaitDataset, EmbeddingNet, ClassificationNet, extract_embeddings, train_epoch, test_epoch
idnet, uid_to_label = load_idnet_dataset(INPUT_SIZE[1], INPUT_SIZE[1], "within")
idnet[0].head()
# Split dataset into a training and validation by-user
# (Test dataset will simulate new users)
train_users = list(uid_to_label.values())[:25]
test_users = list(uid_to_label.values())[25:]
# Split separate walk sessions
train = []
test = []
for chunk in idnet:
if chunk.iloc[0]["user_id"] in train_users:
train.append(chunk)
else:
test.append(chunk)
train_dataset = GaitDataset(train)
test_dataset = GaitDataset(test, train=False)
# Since we train the embedding from the classification network, further split the training data into sub-training/sub-validation
# This is needed for accuracy metrics and to know when to stop training (due to overfitting)
train_classification, test_classification = train_test_split(train, test_size=0.1)
train_dataset_classification = GaitDataset(train_classification)
test_dataset_classification = GaitDataset(test_classification)
```
## Model setup
```
# Set up data loaders
batch_size = 64
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
train_loader_classification = torch.utils.data.DataLoader(train_dataset_classification, batch_size=batch_size, shuffle=True)
test_loader_classification = torch.utils.data.DataLoader(test_dataset_classification, batch_size=batch_size, shuffle=False)
embedding_net = EmbeddingNet(EMBEDDING_SIZE)
n_classes = len(uid_to_label)
model = ClassificationNet(embedding_net, n_classes=n_classes).to(DEVICE)
criterion = torch.nn.NLLLoss()
lr = 5e-3
optimizer = optim.Adam(model.parameters(), lr=lr)
scheduler = lr_scheduler.StepLR(optimizer, 8, gamma=0.1, last_epoch=-1)
n_epochs = 15
summary(model, INPUT_SIZE) # Verify model is valid shaped
for epoch in tqdm(range(n_epochs), desc="Epoch"):
train_loss, train_acc = train_epoch(train_loader_classification, model, criterion, optimizer, DEVICE)
scheduler.step() # update learning rate (decrease)
print(f"[{epoch+1}/{n_epochs}] Training: loss = {train_loss:.6f} / acc = {train_acc:.6f}")
valid_loss, valid_acc = test_epoch(test_loader_classification, model, criterion, DEVICE)
print(f"[{epoch+1}/{n_epochs}] Validation: loss = {valid_loss:.6f} / acc = {valid_acc:.6f}")
```
## Evaluate embeddings
```
train_embeddings_baseline, train_labels_baseline = extract_embeddings(train_loader, embedding_net)
val_embeddings_baseline, val_labels_baseline = extract_embeddings(test_loader, embedding_net)
def aggregate_similarities_mean(simi):
# Fill in diagonals so they don't affect the aggregation
np.fill_diagonal(simi.values, np.nan)
pool = simi.groupby(simi.index, axis=0).mean().groupby(simi.columns, axis=1).mean()
return pool
def plot_heatmap(embeddings, labels, dist_method="euclidean", agg=True):
embeddings_df = pd.DataFrame(embeddings, index=labels.astype(int)).sort_index()
if dist_method == "euclidean":
similarity = euclidean_distances(embeddings_df.values, embeddings_df.values)
elif dist_method == "cosine":
similarity = cosine_similarity(embeddings_df.values, embeddings_df.values)
similarity_df = pd.DataFrame(similarity, index=embeddings_df.index, columns=embeddings_df.index)
f, ax = plt.subplots(figsize=(15,15))
if agg:
similarity_df = aggregate_similarities_mean(similarity_df)
sns.heatmap(similarity_df, square=True, ax=ax, cmap="viridis")
return similarity_df
def plot_embeddings_mds(embeddings, labels, metric="euclidean"):
if metric == "euclidean":
mds = MDS()
embeddings_mds = mds.fit_transform(embeddings)
elif metric == "cosine":
# Need to precompute cosine distances
mds = MDS(dissimilarity="precomputed")
embeddings_mds = cosine_similarity(embedding, embeddings)
f, ax = plt.subplots(figsize=(15, 15))
sns.scatterplot(x=embeddings_mds[:,0], y=embeddings_mds[:,1],
hue="user=" + pd.Series(labels).astype(int).astype(str),
ax=ax)
ax.set_xlabel("MDS-1")
ax.set_ylabel("MDS-2")
ax.set_title("Multidimensional scaling representation")
return mds # Return because they take so long to generate
simi_train = plot_heatmap(train_embeddings_baseline, train_labels_baseline, dist_method="cosine")
def intra_vs_inter_avg_similarity(simi_mat):
# Average within diagonal
intra = np.diag(simi_mat).mean()
# Average outside of diagonal
# Get indices of upper-triangle and average
iu, ju = np.triu_indices_from(simi_mat, k=1)
inter = np.mean([simi_mat[i,j] for i, j in zip(iu, ju)])
return intra, inter
# Plot average similarity within same-user vs between different users
intra_vs_inter_avg_similarity(simi_train.values)
simi_test = plot_heatmap(val_embeddings_baseline, val_labels_baseline, dist_method="cosine")
# Plot average similarity within same-user vs between different users
intra_vs_inter_avg_similarity(simi_test.values)
sns.set_context("poster")
mds_fit = plot_embeddings_mds(val_embeddings_baseline, val_labels_baseline)
# Save model
torch.save(embedding_net.state_dict(), "../models/Classification-Trained_EmbeddingNet.pt")
```
| github_jupyter |
# Creating a custom fluid using GenericPhase
OpenPNM comes with a small selection of pre-written phases (Air, Water, Mercury). In many cases users will want different options but it is not feasible or productive to include a wide variety of fluids. Consequntly OpenPNM has a mechanism for creating custom phases for this scneario. This requires that the user have correlations for the properties of interest, such as the viscosity as a function of temperature in the form of a polynomial for instance. This is process is described in the following tutuorial:
Import the usual packages and instantiate a small network for demonstration purposes:
```
import numpy as np
import openpnm as op
pn = op.network.Cubic(shape=[3, 3, 3], spacing=1e-4)
print(pn)
```
Now that a network is defined, we can create a `GenericPhase` object associated with it. For this demo we'll make an oil phase, so let's call it `oil`:
```
oil = op.phases.GenericPhase(network=pn)
print(oil)
```
As can be seen in the above printout, this phase has a temperature and pressure set at all locations, but has no other physical properties.
There are 2 ways add physical properties. They can be hard-coded, or added as a 'pore-scale model'.
- Some are suitable as hard coded values, such as molecular mass
- Others should be added as a model, such as viscosity, which is a function of temperature so could vary spatially and should be updated depending on changing conditions in the simulation.
Start with hard-coding:
```
oil['pore.molecular_mass'] = 100.0 # g/mol
print(oil['pore.molecular_mass'])
```
As can be seen, this puts the value of 100.0 g/mol in every pore. Note that you could also assign each pore explicitly with a numpy array. OpenPNM automatically assigns a scalar value to every location as shown above.
```
oil['pore.molecular_mass'] = np.ones(shape=[pn.Np, ])*120.0
print(oil['pore.molecular_mass'])
```
You can also specify something like viscosity this way as well, but it's not recommended:
```
oil['pore.viscosity'] = 1600.0 # cP
```
The problem with specifying the viscosity as a hard-coded value is that viscosity is a function of temperature (among other things), so if we adjust the temperature on the `oil` object it will have no effect on the hard-coded viscosity:
```
oil['pore.temperature'] = 100.0 # C
print(oil['pore.viscosity'])
```
The correct way to specify something like viscosity is to use pore-scale models. There is a large libary of pre-written models in the `openpnm.models` submodule. For instance, a polynomial can be used as follows:
$$ viscosity = a_0 + a_1 \cdot T + a_2 \cdot T^2 = 1600 + 12 T - 0.05 T^2$$
```
mod = op.models.misc.polynomial
oil.add_model(propname='pore.viscosity', model=mod,
a=[1600, 12, -0.05], prop='pore.temperature')
```
We can now see that our previously written values of viscosity (1600.0) have been overwritten by the values coming from the model:
```
print(oil['pore.viscosity'])
```
And moreover, if we change the temperature the model will update the viscosity values:
```
oil['pore.temperature'] = 40.0 # C
oil.regenerate_models()
print(oil['pore.viscosity'])
```
Note the call to `regenerate_models`, which is necessary to actually re-run the model using the new temperature.
When a pore-scale model is added to an object, it is stored under the `models` attribute, which is a dictionary with names corresponding the property that is being calculated (i.e. 'pore.viscosity'):
```
print(oil.models)
```
We can reach into this dictionary and alter the parameters of the model if necessary:
```
oil.models['pore.viscosity']['a'] = [1200, 10, -0.02]
oil.regenerate_models()
print(oil['pore.viscosity'])
```
The `models` submodule has a variety of common functions, stored under `models.misc.basic_math` or `models.misc.common_funtions`. There are also some models specific to physical properties under `models.phases`.
| github_jupyter |
# Using Amazon Elastic Inference with a pre-trained TensorFlow Serving model on SageMaker
This notebook demonstrates how to enable and use Amazon Elastic Inference with our predefined SageMaker TensorFlow Serving containers.
Amazon Elastic Inference (EI) is a resource you can attach to your Amazon EC2 instances to accelerate your deep learning (DL) inference workloads. EI allows you to add inference acceleration to an Amazon SageMaker hosted endpoint or Jupyter notebook for a fraction of the cost of using a full GPU instance. For more information please visit: https://docs.aws.amazon.com/sagemaker/latest/dg/ei.html
This notebook's main objective is to show how to create an endpoint, backed by an Elastic Inference, to serve our pre-trained TensorFlow Serving model for predictions. With a more efficient cost per performance, Amazon Elastic Inference can prove to be useful for those looking to use GPUs for higher inference performance at a lower cost.
1. [The model](#The-model)
1. [Setup role for SageMaker](#Setup-role-for-SageMaker)
1. [Load the TensorFlow Serving Model on Amazon SageMaker using Python SDK](#Load-the-TensorFlow-Serving-Model-on-Amazon-SageMaker-using-Python-SDK)
1. [Deploy the trained Model to an Endpoint with EI](#Deploy-the-trained-Model-to-an-Endpoint-with-EI)
1. [Using EI with a SageMaker notebook instance](#Using-EI-with-a-SageMaker-notebook-instance)
1. [Invoke the Endpoint to get inferences](#Invoke-the-Endpoint-to-get-inferences)
1. [Delete the Endpoint](#Delete-the-Endpoint)
If you are familiar with SageMaker and already have a trained model, skip ahead to the [Deploy the trained Model to an Endpoint with an attached EI accelerator](#Deploy-the-trained-Model-to-an-Endpoint-with-an-attached-EI-accelerator)
For this example, we will use the SageMaker Python SDK, which helps deploy your models to train and host in SageMaker. In this particular example, we will be interested in only the hosting portion of the SDK.
1. Set up our pre-trained model for consumption in SageMaker
2. Host the model in an endpoint with EI
3. Make a sample inference request to the model
4. Delete our endpoint after we're done using it
## The model
The pre-trained model we will be using for this example is a NCHW ResNet-50 model from the [official Tensorflow model Github repository](https://github.com/tensorflow/models/tree/master/official/resnet#pre-trained-model). For more information in regards to deep residual networks, please check [here](https://github.com/tensorflow/models/tree/master/official/resnet). It isn't a requirement to train our model on SageMaker to use SageMaker for serving our model.
SageMaker expects our models to be compressed in a tar.gz format in S3. Thankfully, our model already comes in that format. The predefined TensorFlow Serving containers use REST API for handling inferences, for more informationm, please see [Deploying to TensorFlow Serving Endpoints](https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/tensorflow/deploying_tensorflow_serving.rst#making-predictions-against-a-sagemaker-endpoint).
To host our model for inferences in SageMaker, we need to first upload the SavedModel to S3. This can be done through the AWS console or AWS command line.
For this example, the SavedModel object will already be hosted in a public S3 bucket owned by SageMaker.
```
%%time
import boto3
# use the region-specific saved model object
region = boto3.Session().region_name
saved_model = 's3://sagemaker-sample-data-{}/tensorflow/model/resnet/resnet_50_v2_fp32_NCHW.tar.gz'.format(region)
```
## Setup role for SageMaker
Let's start by creating a SageMaker session and specifying the IAM role arn used to give hosting access to your model. See the [documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the `sagemaker.get_execution_role()` with a the appropriate full IAM role arn string(s).
```
import sagemaker
role = sagemaker.get_execution_role()
```
## Load the TensorFlow Serving Model on Amazon SageMaker using Python SDK
We can use the SageMaker Python SDK to load our pre-trained TensorFlow Serving model for hosting in SageMaker for predictions.
There are a few parameters that our TensorFlow Serving Model is expecting.
1. `model_data` - The S3 location of a model tar.gz file to load in SageMaker
2. `role` - An IAM role name or ARN for SageMaker to access AWS resources on your behalf.
3. `framework_version` - TensorFlow Serving version you want to use for handling your inference request .
```
from sagemaker.tensorflow.serving import Model
tensorflow_model = Model(model_data=saved_model,
role=role,
framework_version='1.14')
```
# Deploy the trained Model to an Endpoint with an attached EI accelerator
The `deploy()` method creates an endpoint which serves prediction requests in real-time.
The only change required for utilizing EI with our SageMaker TensorFlow Serving containers only requires providing an `accelerator_type` parameter, which determines which type of EI accelerator to attach to your endpoint. The supported types of accelerators can be found here: https://aws.amazon.com/sagemaker/pricing/instance-types/
```
%%time
predictor = tensorflow_model.deploy(initial_instance_count=1,
instance_type='ml.m4.xlarge',
accelerator_type='ml.eia1.medium')
```
## Using EI with a SageMaker notebook instance
There is also the ability to utilize an EI accelerator attached to your local SageMaker notebook instance. For more information, please reference: https://docs.aws.amazon.com/sagemaker/latest/dg/ei-notebook-instance.html
# Invoke the Endpoint to get inferences
Invoking prediction:
```
%%time
import numpy as np
random_input = np.random.rand(1, 1, 3, 3)
prediction = predictor.predict({'inputs': random_input.tolist()})
print(prediction)
```
# Delete the Endpoint
After you have finished with this example, remember to delete the prediction endpoint to release the instance(s) associated with it.
```
print(predictor.endpoint)
import sagemaker
predictor.delete_endpoint()
```
| github_jupyter |

# NumPy
# The NumPy array object
### Section contents
* What are Numpy and Numpy arrays?
* Reference documentation
* Import conventions
* Creating arrays
* Functions for creating arrays
* Element wiseoperations
* Basic visualization
* Indexing and slicing
## What are Numpy and Numpy arrays?
**Python** objects
* high-level number objects: integers, floating point
* containers: lists (costless insertion and append), dictionaries (fast
lookup)
**Numpy** provides
* extension package to Python for multi-dimensional arrays
* closer to hardware (efficiency)
* designed for scientific computation (convenience)
* Also known as *array oriented computing*
For example, a numpy array can contain:
* values of an experiment/simulation at discrete time steps
* signal recorded by a measurement device, e.g. sound wave
* pixels of an image, grey-level or colour
* 3-D data measured at different X-Y-Z positions, e.g. MRI scan
* ...
**Why it is useful:** Memory-efficient container that provides fast
numerical operations.
## Reference documentation
* On the web: [http://docs.scipy.org](http://docs.scipy.org)/
* Interactive help:
* Looking for something:
## Import conventions
The general convention to import numpy is:
Using this style of import is recommended.
## Creating and inspecting arrays
* **1-D**:
* **2-D, 3-D, ...**:
***
## <span style="color:blue">Exercise: Simple arrays</span>
* Create simple one and two dimensional arrays. First, redo the examples
from above. And then create your own.
* Use the functions `len`, `shape` and `ndim` on some of those arrays and
observe their output.
***
## Functions for creating arrays
In practice, we rarely enter items one by one...
* Evenly spaced:
* or by number of points:
* Common arrays:
* `np.random` random numbers (Mersenne Twister PRNG):
***
## <span style="color:blue">Exercise: Creating arrays using functions</span>
* Experiment with `arange`, `linspace`, `ones`, `zeros`, `eye` and `diag`.
* Create different kinds of arrays with random numbers.
* Try setting the seed before creating an array with random values.
* Look at the function `np.empty`. What does it do? When might this be
useful?
***
## Elementwise operations
### Basic operations
With scalars:
All arithmetic operates elementwise:
### Warning
**Array multiplication is not matrix multiplication:**
### Note
**Matrix multiplication:**
***
## <span style="color:blue">Exercise: Elementwise operations</span>
* Try simple arithmetic elementwise operations.
* Try using `dot` or `@` operator.
* Generate:
* `[2**0, 2**1, 2**2, 2**3, 2**4]`
* `a_j = 2^(3*j) - j, j=1,2,3,4`
### Other operations
#### Comparisons:
#### Transcendental functions
#### Shape mismatches
#### Transposition
### Note
**Linear algebra**
The sub-module ``numpy.linalg`` implements basic linear algebra,
such as solving linear systems, singular value decomposition, etc.
However, it is not guaranteed to be compiled using efficient routines,
and thus we recommend the use of ``scipy.linalg``, as detailed in
section ``scipy_linalg``
***
## <span style="color:blue">Exercise other operations</span>
* Look at the help for `np.allclose`. When might this be useful?
* Look at the help for `np.triu` and `np.tril`.
***
## Indexing and slicing
The items of an array can be accessed and assigned to the same way as
other Python sequences (e.g. lists):
## Warning
Indices begin at 0, like other Python sequences (and C/C++). In
contrast, in Fortran or Matlab, indices begin at 1.
The usual python idiom for reversing a sequence is supported:
For multidimensional arrays, indexes are tuples of integers:
Note that:
* In 2D, the first dimension corresponds to rows, the second to columns.
* Let us repeat together: the first dimension corresponds to **rows**, the
second to **columns**.
* for multidimensional `a`, `a[0]` is interpreted by taking all elements
in the unspecified dimensions.
**Slicing**
Arrays, like other Python sequences can also be sliced:
Note that the last index is not included! :
All three slice components are not required: by default, \`start\` is 0,
\`end\` is the last and \`step\` is 1:
A small illustrated summary of Numpy indexing and slicing...
```
from IPython.display import Image
Image(filename='images/numpy_indexing.png')
```
You can also combine assignment and slicing:
| github_jupyter |
```
import pandas as pd
import numpy as np
import os.path
from keras.applications import ResNet50
from keras.optimizers import Adam
import cv2
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras import backend as K
CSV_TRAIN_FILE = 'train.csv'
TRAIN_IMAGES_PATH = '../../data/train_/{}'
CSV_TEST_FILE = 'test.csv'
TEST_IMAGES_PATH = '../../data/test_/{}'
df_train = pd.read_csv(CSV_TRAIN_FILE)
NUM_CLASSES = 15
IMAGE_X_SIZE = 350
IMAGE_Y_SIZE = 350
```
### Loading images
```
def load_images(data, images_path, x_size, y_size, train):
resize=(x_size, y_size)
x = []
y = []
ids = []
for img_id, age, gender, view, file, detected in tqdm(data.values, miniters=100):
img = cv2.imread(images_path.format(file))
x.append(cv2.resize(img, resize))
ids.append(img_id)
if train:
targets = np.zeros(NUM_CLASSES)
index = int(detected.replace("class_", ""))
targets[index] = 1
y.append(targets)
y = np.array(y, np.uint8)
return x, y, ids
X_all, y_all, ids = load_images(df_train, TRAIN_IMAGES_PATH, IMAGE_X_SIZE, IMAGE_Y_SIZE, train=True)
```
### Split dataset to training na test set
```
X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=0.3, random_state=0)
X_train = np.array(X_train, np.float32) / 255
X_test = np.array(X_test, np.float32) / 255
```
### Building a model
```
base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(IMAGE_X_SIZE, IMAGE_Y_SIZE, 3))
for layer in base_model.layers[1:]: #freeze all layers
layer.trainable = False
model = Sequential([
base_model,
Flatten(),
Dense(2048, activation='relu'),
Dropout(0.5),
Dense(512, activation='relu'),
Dropout(0.5),
Dense(NUM_CLASSES, activation='softmax')
])
for layer in model.layers[0].layers[-35:]: #unfreeze some layers
layer.trainable = True
optimizer = Adam(0.0001, decay=0.00000001)
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
model.summary()
```
#### Loading model parameters
```
model.load_weights("ResNet50.hdf5")
```
### Training a model (you don't have to run this, because you already have pretreined weights for this network)
```
history = model.fit(X_train, y_train,
batch_size=64,
epochs=50,
verbose=1,
validation_data=(X_test, y_test))
```
### Predictions
```
df_test = pd.read_csv(CSV_TEST_FILE)
df_test['detected'] = 'dummy'
test_X_all, y_test, ids = load_images(df_test, TEST_IMAGES_PATH, IMAGE_X_SIZE, IMAGE_Y_SIZE, train=False)
test_X_all = np.array(test_X_all, np.float32) / 255
prediction = model.predict(test_X_all, batch_size=64, verbose=1)
```
### Create submission file
```
labels = ["class_" + str(class_number) for class_number in np.argmax(prediction, -1)]
dataFrame = {'row_id': ids, 'detected': labels}
submission = pd.DataFrame(data=dataFrame)
submission[ ['row_id', 'detected'] ].to_csv('answers.csv', index=False)
```
| github_jupyter |
```
#imports
from tbselenium.tbdriver import TorBrowserDriver
from selenium.webdriver.support.ui import WebDriverWait
import os
import time
from bs4 import BeautifulSoup as bs
#URL to visits
URL = 'http://asap4u7rq4tyakf5gdahmj2c77blwc4noxnsppp5lzlhk7x34x2e22yd.onion/'
def visit_and_login(driver):
'''This function opens the marketplace in the url'''
# Log in and solve the captcha
driver.get(URL)
time.sleep(30) #30 seconds to solve the captcha and login
return driver
def get_pages(driver, urls):
print("Starting the crawling")
#visit all listings on the marketplace
for i in range(1, 239): #there are 238 pages
site_page = URL +'search?page='+str(i)+'¤cy=USD&sortType=None' #URL to visit
driver.get(site_page)#go to the url
time.sleep(2) #sleep for 2 seconds
soup = bs(driver.page_source, 'html.parser') #view page source using BS4
hrefs = soup.find_all(href=True) #find all linked urls
for line in hrefs:
urls.append(line['href']) #append all urls on the page to a list
#print statement to show progress
if i%5 == 0:
print('crawled',i,'out of 239 pages')
else:
pass
print('Finished Crawling')
return urls
#this will be the list of urls found at the page
urls = []
#crawling
with TorBrowserDriver("/home/levi/tor-browser_en-US/") as driver:
driver = visit_and_login(driver)
all_urls = get_pages(driver, urls)
#find the urls with links to vendor profiles
vendor_urls = []
for i in all_urls: #go to all scraped urls
if 'profile' in i and 'jheronimus' not in i: #do not save our own profile
vendor_urls.append(i)
vendor_urls = list(dict.fromkeys(vendor_urls))#final list of vendor urls /remove duplicates
vendor_urls = [URL[:-1]+ i for i in vendor_urls]
import json
with open("asap_urls.json", "w") as f: #save urls as a json file
json.dump(vendor_urls, f)
#now visit all the urls we just scraped and download them
def get_vendor_pages(driver, vendor_urls):
print("Starting the crawling")
for index, i in enumerate(vendor_urls): #for all vendors_urls
site_page = i #name of url
driver.get(site_page) #visit page
time.sleep(2)
#find the vendor name in the page
soup = bs(driver.page_source, 'html.parser')
name = soup.find_all(class_ = "btn btn-sm btn-success")
vendor_name = name[0]['href'][15:] #function to extract vendor name
filename = 'asap/'+ vendor_name + '.html' #save file als username
with open("/home/levi/" + filename, "w") as f:
f.write(driver.page_source)
print('dowloaded' ,index+1, 'out of', len(vendor_urls),'pages') #print statement for progress
print('finished crawling')
with TorBrowserDriver("/home/levi/tor-browser_en-US/") as driver:
driver = visit_and_login(driver)
get_vendor_pages(driver, vendor_urls)
#sometimes we get thrown of the website, we check which links we already visited and update the urls accordingly
def links_to_crawl(DIR, vendor_urls):
'''check in directory which pages already have been crawled and make new list with urls to crawl'''
crawled = os.listdir(DIR)
crawled = [i[:-5] for i in crawled]
print('already crawled pages:' , len(crawled))
all_vendors = [i[89:] for i in vendor_urls] #names of all vendors
#all vendors remaining to crawl
to_crawl = [vendor for vendor in all_vendors if vendor not in crawled]
site = URL+'?page=profile&user='
vendors_to_crawl = [site + vendor for vendor in to_crawl] #list of pages to crawl
print('pages left to crawl' , len(vendors_to_crawl))
return vendors_to_crawl
```
| github_jupyter |
# Dr. Semmelweis and the Discovery of Handwashing
> A Summary of project in datacamp
- toc: true
- badges: true
- comments: true
- author: Chanseok Kang
- categories: [Python, Datacamp]
- image: images/Ignaz_Semmelweis_1860.jpg
## 1. Meet Dr. Ignaz Semmelweis
<p><img style="float: left;margin:5px 20px 5px 1px" src="https://assets.datacamp.com/production/project_20/img/ignaz_semmelweis_1860.jpeg"></p>
<!--
<img style="float: left;margin:5px 20px 5px 1px" src="https://assets.datacamp.com/production/project_20/datasets/ignaz_semmelweis_1860.jpeg">
-->
<p>This is Dr. Ignaz Semmelweis, a Hungarian physician born in 1818 and active at the Vienna General Hospital. If Dr. Semmelweis looks troubled it's probably because he's thinking about <em>childbed fever</em>: A deadly disease affecting women that just have given birth. He is thinking about it because in the early 1840s at the Vienna General Hospital as many as 10% of the women giving birth die from it. He is thinking about it because he knows the cause of childbed fever: It's the contaminated hands of the doctors delivering the babies. And they won't listen to him and <em>wash their hands</em>!</p>
<p>In this notebook, we're going to reanalyze the data that made Semmelweis discover the importance of <em>handwashing</em>. Let's start by looking at the data that made Semmelweis realize that something was wrong with the procedures at Vienna General Hospital.</p>
```
# importing modules
import pandas as pd
# Read datasets/yearly_deaths_by_clinic.csv into yearly
yearly = pd.read_csv('./dataset/yearly_deaths_by_clinic.csv')
# Print out yearly
print(yearly)
```
## 2. The alarming number of deaths
<p>The table above shows the number of women giving birth at the two clinics at the Vienna General Hospital for the years 1841 to 1846. You'll notice that giving birth was very dangerous; an <em>alarming</em> number of women died as the result of childbirth, most of them from childbed fever.</p>
<p>We see this more clearly if we look at the <em>proportion of deaths</em> out of the number of women giving birth. Let's zoom in on the proportion of deaths at Clinic 1.</p>
```
# Calculate proportion of deaths per no. births
yearly['proportion_deaths'] = yearly['deaths'] / yearly['births']
# Extract clinic 1 data into yearly1 and clinic 2 data into yearly2
yearly1 = yearly[yearly['clinic'] == 'clinic 1']
yearly2 = yearly[yearly['clinic'] == 'clinic 2']
# Print out yearly1
print(yearly1)
```
## 3. Death at the clinics
<p>If we now plot the proportion of deaths at both clinic 1 and clinic 2 we'll see a curious pattern...</p>
```
# This makes plots appear in the notebook
%matplotlib inline
# Plot yearly proportion of deaths at the two clinics
ax = yearly1.plot(x='year', y='proportion_deaths', label='clinic 1')
yearly2.plot(x='year', y='proportion_deaths', label='clinic 2', ax=ax)
ax.set_ylabel('Proportion deaths')
```
## 4. The handwashing begins
<p>Why is the proportion of deaths constantly so much higher in Clinic 1? Semmelweis saw the same pattern and was puzzled and distressed. The only difference between the clinics was that many medical students served at Clinic 1, while mostly midwife students served at Clinic 2. While the midwives only tended to the women giving birth, the medical students also spent time in the autopsy rooms examining corpses. </p>
<p>Semmelweis started to suspect that something on the corpses, spread from the hands of the medical students, caused childbed fever. So in a desperate attempt to stop the high mortality rates, he decreed: <em>Wash your hands!</em> This was an unorthodox and controversial request, nobody in Vienna knew about bacteria at this point in time. </p>
<p>Let's load in monthly data from Clinic 1 to see if the handwashing had any effect.</p>
```
# Read datasets/monthly_deaths.csv into monthly
monthly = pd.read_csv('./dataset/monthly_deaths.csv', parse_dates=['date'])
# Calculate proportion of deaths per no. births
monthly['proportion_deaths'] = monthly['deaths'] / monthly['births']
# Print out the first rows in monthly
print(monthly.head())
```
## 5. The effect of handwashing
<p>With the data loaded we can now look at the proportion of deaths over time. In the plot below we haven't marked where obligatory handwashing started, but it reduced the proportion of deaths to such a degree that you should be able to spot it!</p>
```
# Plot monthly proportion of deaths
ax = monthly.plot(x='date', y='proportion_deaths')
ax.set_ylabel('Proportion deaths')
```
## 6. The effect of handwashing highlighted
<p>Starting from the summer of 1847 the proportion of deaths is drastically reduced and, yes, this was when Semmelweis made handwashing obligatory. </p>
<p>The effect of handwashing is made even more clear if we highlight this in the graph.</p>
```
# Date when handwashing was made mandatory
handwashing_start = pd.to_datetime('1847-06-01')
# Split monthly into before and after handwashing_start
before_washing = monthly[monthly['date'] < handwashing_start]
after_washing = monthly[monthly['date'] >= handwashing_start]
# Plot monthly proportion of deaths before and after handwashing
ax = before_washing.plot(x='date', y='proportion_deaths', label='before')
after_washing.plot(x='date', y='proportion_deaths', label='after', ax=ax)
ax.set_ylabel('Proportion deaths')
```
## 7. More handwashing, fewer deaths?
<p>Again, the graph shows that handwashing had a huge effect. How much did it reduce the monthly proportion of deaths on average?</p>
```
# Difference in mean monthly proportion of deaths due to handwashing
before_proportion = before_washing.proportion_deaths
after_proportion = after_washing.proportion_deaths
mean_diff = after_proportion.mean() - before_proportion.mean()
mean_diff
```
## 8. A Bootstrap analysis of Semmelweis handwashing data
<p>It reduced the proportion of deaths by around 8 percentage points! From 10% on average to just 2% (which is still a high number by modern standards). </p>
<p>To get a feeling for the uncertainty around how much handwashing reduces mortalities we could look at a confidence interval (here calculated using the bootstrap method).</p>
```
# A bootstrap analysis of the reduction of deaths due to handwashing
boot_mean_diff = []
for i in range(3000):
boot_before = before_proportion.sample(frac=1, replace=True)
boot_after = after_proportion.sample(frac=1, replace=True)
boot_mean_diff.append(boot_after.mean() - boot_before.mean())
# Calculating a 95% confidence interval from boot_mean_diff
confidence_interval = pd.Series(boot_mean_diff).quantile([0.025, 0.975])
confidence_interval
```
## 9. The fate of Dr. Semmelweis
<p>So handwashing reduced the proportion of deaths by between 6.7 and 10 percentage points, according to a 95% confidence interval. All in all, it would seem that Semmelweis had solid evidence that handwashing was a simple but highly effective procedure that could save many lives.</p>
<p>The tragedy is that, despite the evidence, Semmelweis' theory — that childbed fever was caused by some "substance" (what we today know as <em>bacteria</em>) from autopsy room corpses — was ridiculed by contemporary scientists. The medical community largely rejected his discovery and in 1849 he was forced to leave the Vienna General Hospital for good.</p>
<p>One reason for this was that statistics and statistical arguments were uncommon in medical science in the 1800s. Semmelweis only published his data as long tables of raw data, but he didn't show any graphs nor confidence intervals. If he would have had access to the analysis we've just put together he might have been more successful in getting the Viennese doctors to wash their hands.</p>
```
# The data Semmelweis collected points to that:
doctors_should_wash_their_hands = True
```
| github_jupyter |
```
# Useful starting lines
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
```
# Fixed point interation
In numerous applications, we encounter the task of solving equations of the form $$x = g(x)$$
for a continuous function $g$. In week 03 we saw one simple method to solve such problems: $$x_{t+1} = g(x_t)\,.$$
We solved two apparently similar equations $x = log(1+x)$ and $x = log(2+x)$, with showed very different convergence.
## Newton steps
This week's task is to adapt the iterative algorithm to use Newton-style steps. Like in the notebook of week 03, we can do this by expressing the update step as a gradient-descent update and computing its second derivative.
## Plot $g$
Let us see how the two functions look over an interval $[0,2]$.
```
x = np.arange(0, 2, 0.0001)
y1 = np.log(1 + x)
y2 = np.log(2 + x)
fig = plt.figure()
plt.plot(x, x, label='x')
plt.plot(x, y1, label='$\log(1 + x)$')
plt.plot(x, y2, label='$\log(2 + x)$')
plt.grid(linestyle=':')
plt.axhline(0, color='black')
plt.axvline(0, color='black')
plt.legend()
```
Please fill in the functions `fixed_point_newton` below:
```
def fixed_point_newton(initial_x, max_iters, objective, objective_grad):
"""Compute the fixed point."""
# Define parameters to store x and objective func. values
xs = []
errors = []
x = initial_x
for n_iter in range(max_iters):
# compute objective and error
obj = objective(x)
error = np.abs(x - obj)
# store x and error
xs.append(x)
errors.append(error)
########################
# @TODO Insert your code here
# UPDATE x with a Newton step
# x = x - f_prime / f_second
########################
# print the current error
if n_iter % 10 == 0:
print("Fixed point: iteration ={i}, x = {x:.2e}, error={err:.2e}".format(i=n_iter, x=x, err=error))
return errors, xs
def fixed_point(initial_x, max_iters, objective):
"""Compute the fixed point."""
# Define parameters to store x and objective func. values
xs = []
errors = []
x = initial_x
for n_iter in range(max_iters):
# compute objective and error
obj = objective(x)
error = np.abs(x - obj)
# store x and error
xs.append(x)
errors.append(error)
# update x
x = obj
# print the current error
if n_iter % 10 == 0:
print("Fixed point: iteration ={i}, x = {x:.2e}, error={err:.2e}".format(i=n_iter, x=x, err=error))
return errors, xs
```
Let's test the implementations and compare it to the original algorithm from week 03:
```
# Define the parameters of the algorithm.
max_iters = 100
# Initialization
initial_x = 1
# Run fixed point.
errors_func1, xs_func1 = fixed_point(
initial_x,
max_iters,
lambda x: np.log(1 + x)
)
errors_func1_newton, xs_func1_newton = fixed_point_newton(
initial_x,
max_iters,
lambda x: np.log(1 + x),
lambda x: 1./(1. + x)
)
```
Run your implementation on the second function
```
# Define the parameters of the algorithm.
max_iters = 100
# Initialization
initial_x = 1
# Run fixed point.
errors_func2, xs_func2 = fixed_point(
initial_x,
max_iters,
lambda x: np.log(2 + x)
)
errors_func2_newton, xs_func2_newton = fixed_point_newton(
initial_x,
max_iters,
lambda x: np.log(2 + x),
lambda x: 1./(2. + x)
)
```
**Plotting error values**
```
plt.semilogy()
plt.xlabel('Number of steps')
plt.ylabel('Value of Error')
#plt.yscale("log")
plt.plot(range(len(errors_func1)), errors_func1, label='$log(1 + x)$')
plt.plot(range(len(errors_func2)), errors_func2, label='$log(2 + x)$')
plt.plot(range(len(errors_func1_newton)), errors_func1_newton, label='$log(1 + x)$ (Newton)')
plt.plot(range(len(errors_func2_newton)), errors_func2_newton, label='$log(2 + x)$ (Newton)')
plt.legend()
plt.show()
```
What do you observe about the rates of convergence of the two methods? Can you explain this difference?
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.